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
@@ -1,6 +1,19 @@
1
1
  import { lstatSync, realpathSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
3
  const MAX_SOCKET_PATH_BYTES = 4_096;
4
+ /**
5
+ * The longest socket path a client can connect to: `sockaddr_un.sun_path` less
6
+ * its terminating NUL. 108 bytes on Linux, 104 on macOS and the BSDs.
7
+ */
8
+ export function unixSocketPathLimit(platform = process.platform) {
9
+ return platform === "linux" ? 107 : 103;
10
+ }
11
+ export class UnixSocketPathTooLongError extends TypeError {
12
+ constructor(bytes, limit) {
13
+ super(`The tmux socket path is ${bytes} bytes; this platform allows ${limit}. Start the tmux server on a shorter socket path.`);
14
+ this.name = "UnixSocketPathTooLongError";
15
+ }
16
+ }
4
17
  function validSocketPath(path) {
5
18
  return (isAbsolute(path) &&
6
19
  resolve(path) === path &&
@@ -19,13 +32,40 @@ export function captureUnixSocketIdentity(path) {
19
32
  if (!canonical.isSocket() || canonical.dev !== source.dev || canonical.ino !== source.ino)
20
33
  throw new TypeError("Unix socket authority changed while resolving");
21
34
  return Object.freeze({
22
- path: canonicalPath,
35
+ path: reachableSpelling(path, canonicalPath, canonical),
23
36
  dev: Number(canonical.dev),
24
37
  ino: Number(canonical.ino),
25
38
  mtimeNs: canonical.mtimeNs,
26
39
  birthtimeNs: canonical.birthtimeNs,
27
40
  });
28
41
  }
42
+ /**
43
+ * tmux refuses a socket path longer than `sun_path` ("File name too long"). A
44
+ * server can still be running on such a socket when it was started through a
45
+ * shorter spelling. Use that spelling, but only when it names the same socket
46
+ * inode; `revalidateUnixSocketIdentity` checks that inode again before each use.
47
+ */
48
+ function reachableSpelling(given, canonicalPath, canonical) {
49
+ const limit = unixSocketPathLimit();
50
+ if (Buffer.byteLength(canonicalPath) <= limit)
51
+ return canonicalPath;
52
+ const candidates = [given];
53
+ if (process.platform === "darwin" && /^\/private\/(?:tmp|var)\//u.test(canonicalPath))
54
+ candidates.push(canonicalPath.slice("/private".length));
55
+ for (const candidate of candidates) {
56
+ if (candidate === canonicalPath || Buffer.byteLength(candidate) > limit)
57
+ continue;
58
+ try {
59
+ const socket = lstatSync(candidate, { bigint: true });
60
+ if (socket.isSocket() && socket.dev === canonical.dev && socket.ino === canonical.ino)
61
+ return candidate;
62
+ }
63
+ catch {
64
+ // Not a usable spelling; try the next one.
65
+ }
66
+ }
67
+ throw new UnixSocketPathTooLongError(Buffer.byteLength(canonicalPath), limit);
68
+ }
29
69
  export function revalidateUnixSocketIdentity(identity) {
30
70
  if (!validSocketPath(identity.path) ||
31
71
  !Number.isSafeInteger(identity.dev) ||
@@ -41,8 +81,23 @@ export function revalidateUnixSocketIdentity(identity) {
41
81
  if (!current.isSocket() ||
42
82
  current.dev !== BigInt(identity.dev) ||
43
83
  current.ino !== BigInt(identity.ino) ||
44
- current.mtimeNs !== identity.mtimeNs ||
45
- current.birthtimeNs !== identity.birthtimeNs)
84
+ current.birthtimeNs !== identity.birthtimeNs ||
85
+ (!birthtimeIdentifiesFile(process.platform) && current.mtimeNs !== identity.mtimeNs))
46
86
  throw new TypeError("Unix socket authority changed before use");
47
87
  return identity.path;
48
88
  }
89
+ /**
90
+ * A socket that was replaced at the same path can get the same inode number
91
+ * back, so device and inode alone do not identify it. Where the filesystem
92
+ * records a real creation time (macOS and the BSDs), that settles it, and the
93
+ * modification time must not: `touch` on the socket of a healthy tmux server
94
+ * changes mtime and would otherwise retire its owner and close every stream.
95
+ * Linux reports a creation time only on some filesystems and Node substitutes
96
+ * the change time elsewhere, so there mtime stays part of the identity.
97
+ */
98
+ export function birthtimeIdentifiesFile(platform) {
99
+ return (platform === "darwin" ||
100
+ platform === "freebsd" ||
101
+ platform === "openbsd" ||
102
+ platform === "netbsd");
103
+ }
@@ -144,6 +144,13 @@ export function resolveWorkspacePaneTmuxAuthority() {
144
144
  // consulting a later request's TMUX/PATH.
145
145
  return Object.freeze({ executablePath, socketSelector: namespace.tmuxSocket });
146
146
  }
147
+ /**
148
+ * Every synchronous tmux call blocks the daemon's only thread: requests,
149
+ * signal handlers and deadlines all wait for it. A tmux client that never
150
+ * returns must therefore never be waited for without a bound. Callers may
151
+ * pass their own; nobody gets "no timeout".
152
+ */
153
+ export const PINNED_SYNC_TMUX_TIMEOUT_MS = 5_000;
147
154
  export function createPinnedWorkspaceTmuxRunner(authority, options = {}) {
148
155
  const executablePath = realpathSync(authority.executablePath);
149
156
  accessSync(executablePath, constants.X_OK);
@@ -180,7 +187,9 @@ export function createPinnedWorkspaceTmuxRunner(authority, options = {}) {
180
187
  env: environment,
181
188
  maxBuffer: TMUX_OUTPUT_BYTES,
182
189
  stdio: ["ignore", "pipe", "pipe"],
183
- ...(options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs }),
190
+ timeout: options.timeoutMs ?? PINNED_SYNC_TMUX_TIMEOUT_MS,
191
+ // A client that ignores TERM must not outlive the bound.
192
+ killSignal: "SIGKILL",
184
193
  }));
185
194
  // A cold named authority may create its first server with this command.
186
195
  if (namedFence && !namedFence.isPinned())
@@ -21,9 +21,9 @@
21
21
  <key>CFBundlePackageType</key>
22
22
  <string>APPL</string>
23
23
  <key>CFBundleShortVersionString</key>
24
- <string>2.9.21</string>
24
+ <string>2.9.23</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.21</string>
26
+ <string>2.9.23</string>
27
27
  <key>LSMinimumSystemVersion</key>
28
28
  <string>11.0</string>
29
29
  <key>LSUIElement</key>
@@ -10,7 +10,7 @@
10
10
  </data>
11
11
  <key>Resources/Assets.car</key>
12
12
  <data>
13
- EsiTbdQN4UN1DDLvBWMjr8yYs3c=
13
+ eIcSkXParZcC4QAg0KZlGi3qdeA=
14
14
  </data>
15
15
  </dict>
16
16
  <key>files2</key>
@@ -26,7 +26,7 @@
26
26
  <dict>
27
27
  <key>hash2</key>
28
28
  <data>
29
- xcvTSqFPzlTwYR+iWi6YB+E1VIu0wNx6nZxi4ZTQihY=
29
+ s1pgcF7YhjrKOlxkEdh7I3iHyy1chYzX1V7z2eoz8Nk=
30
30
  </data>
31
31
  </dict>
32
32
  </dict>
@@ -112,8 +112,9 @@ export async function nativeControlsNotice(run, pane, executable, wait = {}) {
112
112
  await sleep(250);
113
113
  }
114
114
  }
115
- export function createBrowserPane(run, executable, url, options, environment, cwd, namespace) {
116
- validateBrowserOpen(url, options);
115
+ /** Where a new browser or reader pane goes: resolved IDs, before any mutation. */
116
+ export function resolveOpenPaneTarget(run, options, environment, kind = "BROWSER") {
117
+ const noun = kind.toLowerCase();
117
118
  const inheritedPane = /^%\d+$/u.test(environment.TMUX_PANE ?? "")
118
119
  ? environment.TMUX_PANE
119
120
  : undefined;
@@ -126,7 +127,7 @@ export function createBrowserPane(run, executable, url, options, environment, cw
126
127
  ? `$${inheritedServer[3]}:.${inheritedPane}`
127
128
  : undefined);
128
129
  if (!target)
129
- throw new IdeError("Run tmux-ide open inside a tmux pane, or select a session with --session NAME.", { code: "BROWSER_TARGET_REQUIRED", exitCode: 2 });
130
+ throw new IdeError("Run tmux-ide open inside a tmux pane, or select a session with --session NAME.", { code: `${kind}_TARGET_REQUIRED`, exitCode: 2 });
130
131
  // Resolve IDs before mutation. No implicit last-used session or window target.
131
132
  const identity = run([
132
133
  "display-message",
@@ -142,11 +143,11 @@ export function createBrowserPane(run, executable, url, options, environment, cw
142
143
  !/^\$\d+$/u.test(session ?? "") ||
143
144
  !/^@\d+$/u.test(window ?? "") ||
144
145
  !/^%\d+$/u.test(sourcePane ?? ""))
145
- throw new IdeError("The browser target is no longer available.", {
146
- code: "BROWSER_TARGET_UNAVAILABLE",
146
+ throw new IdeError(`The ${noun} target is no longer available.`, {
147
+ code: `${kind}_TARGET_UNAVAILABLE`,
147
148
  });
148
149
  if (implicit && serverPid !== inheritedServer?.[2])
149
- throw new IdeError("The current pane belongs to a different tmux server. Select a session explicitly.", { code: "BROWSER_TARGET_MISMATCH", exitCode: 2 });
150
+ throw new IdeError("The current pane belongs to a different tmux server. Select a session explicitly.", { code: `${kind}_TARGET_MISMATCH`, exitCode: 2 });
150
151
  if (options.session && options.pane) {
151
152
  const selected = run([
152
153
  "display-message",
@@ -157,21 +158,28 @@ export function createBrowserPane(run, executable, url, options, environment, cw
157
158
  ]).trim();
158
159
  if (selected !== session)
159
160
  throw new IdeError("The pane does not belong to the requested session.", {
160
- code: "BROWSER_TARGET_MISMATCH",
161
+ code: `${kind}_TARGET_MISMATCH`,
161
162
  exitCode: 2,
162
163
  });
163
164
  }
165
+ return { session: session, window: window, sourcePane: sourcePane };
166
+ }
167
+ /**
168
+ * The tmux argv that creates the pane and runs `command` in it directly (no
169
+ * shell parsing). `format` is what tmux prints for the new pane.
170
+ */
171
+ export function openPaneArgs(target, options, environment, cwd, namespace, command, format, windowName) {
164
172
  const args = options.window
165
- ? ["new-window", "-t", `${session}:`, "-n", "Browser"]
173
+ ? ["new-window", "-t", `${target.session}:`, "-n", windowName]
166
174
  : [
167
175
  "split-window",
168
176
  options.split === "down" ? "-v" : "-h",
169
177
  "-t",
170
- `${session}:${window}.${sourcePane}`,
178
+ `${target.session}:${target.window}.${target.sourcePane}`,
171
179
  "-l",
172
180
  `${options.size ?? "50"}%`,
173
181
  ];
174
- args.push("-c", resolve(cwd), "-P", "-F", "#{session_id}\t#{window_id}\t#{pane_id}");
182
+ args.push("-c", resolve(cwd), "-P", "-F", format);
175
183
  // tmux supplies the new pane's TMUX and TMUX_PANE. Never copy the caller's
176
184
  // native-surface route, which belongs to a different pane.
177
185
  const childEnvironment = { ...namespace };
@@ -189,10 +197,16 @@ export function createBrowserPane(run, executable, url, options, environment, cw
189
197
  for (const [key, value] of Object.entries(childEnvironment))
190
198
  args.push("-e", `${key}=${value}`);
191
199
  // Multiple command arguments use tmux's direct exec path, not shell parsing.
192
- args.push(executable, "open", ...(url === undefined ? [] : [url]), "--no-merge");
200
+ args.push(...command);
201
+ return args;
202
+ }
203
+ export function createBrowserPane(run, executable, url, options, environment, cwd, namespace) {
204
+ validateBrowserOpen(url, options);
205
+ const target = resolveOpenPaneTarget(run, options, environment);
206
+ const args = openPaneArgs(target, options, environment, cwd, namespace, [executable, "open", ...(url === undefined ? [] : [url]), "--no-merge"], "#{session_id}\t#{window_id}\t#{pane_id}", "Browser");
193
207
  const [createdSession, createdWindow, pane] = run(args).trim().split("\t");
194
208
  if (!/^%\d+$/u.test(pane ?? "") ||
195
- createdSession !== session ||
209
+ createdSession !== target.session ||
196
210
  !/^@\d+$/u.test(createdWindow ?? ""))
197
211
  throw new IdeError("tmux did not return the created browser pane ID.", {
198
212
  code: "BROWSER_CREATE_FAILED",
@@ -0,0 +1,84 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { relative, resolve } from "node:path";
3
+ import { resolveCliCommand } from "./lib/cli-command.js";
4
+ import { IdeError } from "./lib/errors.js";
5
+ import { resolveRuntimeNamespace, runtimeNamespaceEnvironment } from "./lib/runtime-namespace.js";
6
+ import { createPinnedWorkspaceTmuxRunner, resolveWorkspacePaneTmuxAuthority, } from "./lib/workspace-pane-creation.js";
7
+ import { openPaneArgs, resolveOpenPaneTarget, validateBrowserOpen, } from "./open-browser.js";
8
+ import { isMarkdownPath } from "./terminal/protocol/reader-option.js";
9
+ const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//iu;
10
+ const MARKDOWN_ARGUMENT = /\.(?:md|markdown)$/iu;
11
+ /**
12
+ * Decides what `tmux-ide open <arg>` opens. A Markdown file name with no
13
+ * `scheme://` is read in the native reader and must exist; everything else
14
+ * goes to the browser exactly as before.
15
+ */
16
+ export function classifyOpenTarget(arg, cwd, fs = {
17
+ realpath: (path) => realpathSync(path),
18
+ isFile: (path) => statSync(path).isFile(),
19
+ }) {
20
+ if (arg === undefined || SCHEME_URL.test(arg) || !MARKDOWN_ARGUMENT.test(arg))
21
+ return { kind: "browser" };
22
+ const named = resolve(cwd, arg);
23
+ const display = relative(cwd, named) || named;
24
+ let path;
25
+ try {
26
+ path = fs.realpath(named);
27
+ if (!fs.isFile(path))
28
+ throw new Error("not a file");
29
+ }
30
+ catch {
31
+ throw new IdeError(`No Markdown file at ${display}.`, {
32
+ code: "FILE_NOT_FOUND",
33
+ exitCode: 2,
34
+ });
35
+ }
36
+ if (!isMarkdownPath(path))
37
+ throw new IdeError(`${display} does not resolve to a Markdown file.`, {
38
+ code: "NOT_MARKDOWN",
39
+ exitCode: 2,
40
+ });
41
+ return { kind: "reader", path, display };
42
+ }
43
+ /**
44
+ * Splits a pane running `tmux-ide show <file>` (the TUI renderer, which also
45
+ * watches the file) and stamps `@tmux_ide_reader` with that process's pid,
46
+ * which is what lets the Mac app paint its native reader over the pane.
47
+ */
48
+ export function createReaderPane(run, cli, path, options, environment, cwd, namespace) {
49
+ validateBrowserOpen(undefined, options);
50
+ const target = resolveOpenPaneTarget(run, options, environment, "READER");
51
+ const args = openPaneArgs(target, options, environment, cwd, namespace, [...cli, "show", path], "#{session_id}\t#{window_id}\t#{pane_id}\t#{pane_pid}", "Reader");
52
+ const [session, window, pane, pid] = run(args).trim().split("\t");
53
+ if (!/^%\d+$/u.test(pane ?? "") ||
54
+ session !== target.session ||
55
+ !/^@\d+$/u.test(window ?? "") ||
56
+ !/^[1-9]\d{0,9}$/u.test(pid ?? ""))
57
+ throw new IdeError("tmux did not return the created reader pane.", {
58
+ code: "READER_CREATE_FAILED",
59
+ });
60
+ run([
61
+ "set-option",
62
+ "-p",
63
+ "-t",
64
+ pane,
65
+ "@tmux_ide_reader",
66
+ JSON.stringify({ version: 1, pid: Number(pid), path }),
67
+ ]);
68
+ return { pane: pane, session: session, window: window, status: "created", kind: "reader" };
69
+ }
70
+ export async function openReader(target, options = {}) {
71
+ validateBrowserOpen(undefined, options);
72
+ try {
73
+ const namespace = { ...runtimeNamespaceEnvironment(resolveRuntimeNamespace()) };
74
+ const run = createPinnedWorkspaceTmuxRunner(resolveWorkspacePaneTmuxAuthority(), {
75
+ timeoutMs: 10_000,
76
+ });
77
+ return createReaderPane(run, resolveCliCommand(), target.path, options, process.env, process.cwd(), namespace);
78
+ }
79
+ catch (error) {
80
+ if (error instanceof IdeError)
81
+ throw error;
82
+ throw new IdeError("Could not create the reader pane. Check that the target tmux session is running.", { code: "READER_CREATE_FAILED", cause: error instanceof Error ? error : undefined });
83
+ }
84
+ }
@@ -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");
@@ -10,6 +10,7 @@ import { stateHome } from "../lib/state-home.js";
10
10
  import { appendPluginLog, pluginLogPath } from "./plugin-log.js";
11
11
  import { createHostCallHandler, } from "./host-calls.js";
12
12
  import { cliRunner } from "./worktree-calls.js";
13
+ import { resolveCliCommand } from "../lib/cli-command.js";
13
14
  import { defaultControlSocketPath } from "../control/server.js";
14
15
  import { DEFAULT_PLUGIN_LIMITS } from "./protocol.js";
15
16
  import { minimalHostEnv, PluginSupervisor, secretEnvValues } from "./supervisor.js";
@@ -62,16 +63,7 @@ export async function tmuxSocketDirs(tmux, env = process.env, uid = process.getu
62
63
  }
63
64
  return [...dirs];
64
65
  }
65
- /**
66
- * The argv prefix that runs this tmux-ide's CLI: the bundled `bin/cli.js`,
67
- * or `bin/cli.ts` under the runtime's loader flags when run from source.
68
- */
69
- export function resolveCliCommand(here = fileURLToPath(import.meta.url), runtime = process) {
70
- if (basename(here) === "cli.js")
71
- return [runtime.execPath, here];
72
- const cli = join(dirname(here), "..", "..", "..", "..", "bin", `cli${extname(here)}`);
73
- return [runtime.execPath, ...runtime.execArgv, cli];
74
- }
66
+ export { resolveCliCommand } from "../lib/cli-command.js";
75
67
  /**
76
68
  * Files programs from plugins may not read: the daemon record (its port and
77
69
  * owner token), the app settings (the remote-access token), the consent
@@ -301,31 +301,57 @@ function liveSessions() {
301
301
  * (flag ORed with the `~/.tmux-ide/config.json` default) revives agent
302
302
  * conversations via `claude --resume <id>`.
303
303
  */
304
- export async function restore({ json = false, dryRun = false, runCommands = false, resumeAgents = false, } = {}) {
305
- const snapshot = readSnapshot();
304
+ export async function restore(options = {}) {
305
+ const { json = false, dryRun = false } = options;
306
+ const outcome = await restoreFleet(options);
307
+ reportPlan(outcome.plan, outcome.snapshot, { ...outcome, json, dryRun });
308
+ if (outcome.failed.length) {
309
+ throw new IdeError(`could not rebuild ${outcome.failed.join(", ")}`, {
310
+ code: "RESTORE_FAILED",
311
+ exitCode: 1,
312
+ });
313
+ }
314
+ }
315
+ /**
316
+ * Rebuild the fleet without printing. One session failing to rebuild does not
317
+ * stop the rest; it is listed in `failed`.
318
+ */
319
+ export async function restoreFleet({ json = false, dryRun = false, runCommands = false, resumeAgents = false, from, snapshotOnly = false, resumeFromConfig = true, } = {}) {
320
+ const snapshot = readSnapshot(from);
306
321
  if (!snapshot) {
307
- throw new IdeError("no snapshot yet — the updater writes one every ~30s while any session is adopted", { code: "NO_SNAPSHOT", exitCode: 1 });
322
+ throw new IdeError(from
323
+ ? `no readable snapshot at ${from}`
324
+ : "no snapshot yet — the updater writes one every ~30s while any session is adopted", { code: "NO_SNAPSHOT", exitCode: 1 });
308
325
  }
309
326
  // The flag forces resume on; config makes it the default. No negative flag.
310
- const resume = resumeAgents || readRestorePrefs().resumeAgents;
311
- const plan = buildRestorePlan(snapshot, liveSessions(), ideBackedProjects());
312
- if (dryRun) {
313
- reportPlan(plan, snapshot, {
314
- json,
315
- dryRun: true,
316
- restored: [],
317
- launched: [],
318
- resumed: [],
319
- resumeAgents: resume,
320
- });
321
- return;
322
- }
323
- const restored = [];
324
- const launched = [];
325
- const resumed = [];
327
+ const resume = resumeAgents || (resumeFromConfig && readRestorePrefs().resumeAgents);
328
+ const plan = buildRestorePlan(snapshot, liveSessions(), snapshotOnly ? new Map() : ideBackedProjects());
329
+ const outcome = {
330
+ snapshot,
331
+ plan,
332
+ restored: [],
333
+ launched: [],
334
+ resumed: [],
335
+ failed: [],
336
+ resumeAgents: resume,
337
+ };
338
+ if (dryRun)
339
+ return outcome;
326
340
  const recordResumed = (session, panes) => {
327
341
  if (panes.length)
328
- resumed.push({ session, panes });
342
+ outcome.resumed.push({ session, panes });
343
+ };
344
+ const rebuild = (session) => {
345
+ try {
346
+ recordResumed(session.name, rebuildSession(session, { runCommands, resumeAgents: resume }));
347
+ }
348
+ catch {
349
+ outcome.failed.push(session.name);
350
+ return;
351
+ }
352
+ if (session.adopted)
353
+ safeAdopt(session.name);
354
+ outcome.restored.push(session.name);
329
355
  };
330
356
  for (const action of plan.actions) {
331
357
  if (action.kind === "skip")
@@ -333,33 +359,19 @@ export async function restore({ json = false, dryRun = false, runCommands = fals
333
359
  if (action.kind === "launch") {
334
360
  const ok = await launchProject(action.dir, json);
335
361
  if (ok)
336
- launched.push(action.session);
362
+ outcome.launched.push(action.session);
337
363
  else {
338
364
  // Launch failed — fall back to a raw rebuild from the snapshot so the
339
365
  // session still comes back.
340
366
  const snap = snapshot.sessions.find((s) => s.name === action.session);
341
- if (snap) {
342
- recordResumed(snap.name, rebuildSession(snap, { runCommands, resumeAgents: resume }));
343
- if (snap.adopted)
344
- safeAdopt(snap.name);
345
- restored.push(action.session);
346
- }
367
+ if (snap)
368
+ rebuild(snap);
347
369
  }
348
370
  continue;
349
371
  }
350
- recordResumed(action.session.name, rebuildSession(action.session, { runCommands, resumeAgents: resume }));
351
- if (action.session.adopted)
352
- safeAdopt(action.session.name);
353
- restored.push(action.session.name);
372
+ rebuild(action.session);
354
373
  }
355
- reportPlan(plan, snapshot, {
356
- json,
357
- dryRun: false,
358
- restored,
359
- launched,
360
- resumed,
361
- resumeAgents: resume,
362
- });
374
+ return outcome;
363
375
  }
364
376
  /** Adopt a restored session into the chrome; never let a chrome failure abort restore. */
365
377
  function safeAdopt(session) {
@@ -391,7 +403,7 @@ async function launchProject(dir, json) {
391
403
  console.log = restoreLog;
392
404
  }
393
405
  }
394
- function reportPlan(plan, snapshot, { json, dryRun, restored, launched, resumed, resumeAgents }) {
406
+ function reportPlan(plan, snapshot, { json, dryRun, restored, launched, resumed, resumeAgents, failed }) {
395
407
  const skipped = plan.actions.filter((a) => a.kind === "skip").map((a) => a.session);
396
408
  const willLaunch = plan.actions.filter((a) => a.kind === "launch").map((a) => a.session);
397
409
  const willRebuild = plan.actions.filter((a) => a.kind === "rebuild").map((a) => a.session.name);
@@ -407,6 +419,7 @@ function reportPlan(plan, snapshot, { json, dryRun, restored, launched, resumed,
407
419
  resumeAgents,
408
420
  resumedPanes,
409
421
  resumed,
422
+ failed,
410
423
  }, null, 2));
411
424
  return;
412
425
  }
@@ -443,5 +456,9 @@ function reportPlan(plan, snapshot, { json, dryRun, restored, launched, resumed,
443
456
  parts.push(`launched ${launched.join(", ")}`);
444
457
  if (skipped.length)
445
458
  parts.push(`skipped ${skipped.join(", ")} (already running)`);
459
+ if (failed.length)
460
+ parts.push(`failed to rebuild ${failed.join(", ")}`);
461
+ // Name the snapshot's age: an old snapshot brings back an old fleet (#766).
462
+ console.log(`Snapshot saved ${snapshot.savedAt}.`);
446
463
  console.log(parts.length ? `Restored: ${parts.join("; ")}` : "Nothing to restore.");
447
464
  }
@@ -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
+ }