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,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
+ }
@@ -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
  }
@@ -365,6 +365,7 @@ export class SessionChannel {
365
365
  await this.io.start();
366
366
  await this.captureAttachedSessionIdentity();
367
367
  this.io.send("refresh-client -B 'tmux-ide-browser-icon:%*:#{@tmux_ide_browser_icon}'");
368
+ this.io.send("refresh-client -B 'tmux-ide-reader:%*:#{@tmux_ide_reader}'");
368
369
  // Changing border placement can resize PTYs without changing the layout
369
370
  // string, so tmux emits no layout-change. Subscribe to this window option.
370
371
  this.io.send("refresh-client -B 'tmux-ide-pane-borders:@*:#{pane-border-status}'");
@@ -2266,7 +2267,8 @@ export class SessionChannel {
2266
2267
  name === "session-renamed" ||
2267
2268
  name === "sessions-changed")
2268
2269
  this.opts.onWindowTopologyChanged?.();
2269
- if (name === "subscription-changed" && rest.startsWith("tmux-ide-browser-icon ")) {
2270
+ if (name === "subscription-changed" &&
2271
+ (rest.startsWith("tmux-ide-browser-icon ") || rest.startsWith("tmux-ide-reader "))) {
2270
2272
  this.scheduleSync();
2271
2273
  return;
2272
2274
  }
@@ -2672,6 +2674,7 @@ export class SessionChannel {
2672
2674
  displayName: display?.name ?? null,
2673
2675
  displayNameSource: display?.source ?? null,
2674
2676
  browserIcon: pane?.descriptor?.browserIcon ?? null,
2677
+ reader: pane?.descriptor?.reader ?? null,
2675
2678
  left: leaf.left,
2676
2679
  top: leaf.top,
2677
2680
  width: leaf.width,
@@ -2,7 +2,7 @@ import { TERMINAL_SURFACE_MAX_CONTROL_BYTES, TERMINAL_SURFACE_CAPABILITY_VERSION
2
2
  import { NativeSurfaceViewer } from "../graphics/native-surface-viewer.js";
3
3
  import { compressGraphicsChunk } from "../graphics/compress-chunk.js";
4
4
  import { TERMINAL_GRAPHICS_COMPRESSED_CAPABILITY_VERSION, TERMINAL_GRAPHICS_COMPRESSED_LOCAL_CAPABILITY_VERSION, TERMINAL_PROJECTION_CAPABILITY_VERSION, TERMINAL_PROJECTION_LOCAL_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
5
- import { PANE_STREAM_INPUT_LIFETIME_CAPABILITY_VERSION, PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
5
+ import { PANE_STREAM_INPUT_LIFETIME_CAPABILITY_VERSION, PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION, PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION, PANE_STREAM_READER_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
6
6
  import { inflateSync } from "node:zlib";
7
7
  import { PaneStreamLayoutSnapshotFrameSchemaZ } from "@tmux-ide/contracts";
8
8
  import { z } from "zod";
@@ -1332,7 +1332,9 @@ export class PaneStreamLiveConnection {
1332
1332
  this.#observeSurfaceDemand([channel.semanticPaneId]);
1333
1333
  // Renderers that cannot inflate see raw formats; their bytes are inflated
1334
1334
  // when served.
1335
- const zlib = this.#descriptor.terminalDelivery?.protocolVersions.some((version) => version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION || version === 117) === true;
1335
+ const zlib = this.#descriptor.terminalDelivery?.protocolVersions.some((version) => version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION ||
1336
+ version === PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION ||
1337
+ version === PANE_STREAM_READER_CAPABILITY_VERSION) === true;
1336
1338
  channel.graphicsZlib = zlib;
1337
1339
  channel.graphicsLocal =
1338
1340
  !!this.#localImages &&
@@ -1793,6 +1795,9 @@ export class PaneStreamLiveConnection {
1793
1795
  }
1794
1796
  this.#sendFrame(null, frame);
1795
1797
  }
1798
+ #offers(version) {
1799
+ return this.#descriptor.terminalDelivery?.protocolVersions.includes(version) === true;
1800
+ }
1796
1801
  #layoutFrame(event) {
1797
1802
  const frame = {
1798
1803
  type: "layout",
@@ -1808,9 +1813,13 @@ export class PaneStreamLiveConnection {
1808
1813
  pane: pane.semanticPaneId,
1809
1814
  displayName: pane.displayName,
1810
1815
  displayNameSource: pane.displayNameSource,
1811
- ...(this.#descriptor.terminalDelivery?.protocolVersions.includes(117)
1816
+ ...(this.#offers(PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION) ||
1817
+ this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
1812
1818
  ? { browserIcon: pane.browserIcon ?? null }
1813
1819
  : {}),
1820
+ ...(this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
1821
+ ? { reader: pane.reader ? { name: pane.reader.name } : null }
1822
+ : {}),
1814
1823
  left: pane.left,
1815
1824
  top: pane.top,
1816
1825
  width: pane.width,
@@ -0,0 +1,66 @@
1
+ import { basename, isAbsolute } from "node:path";
2
+ import { hasControlCharacter } from "@tmux-ide/contracts";
3
+ const MARKDOWN = /\.(?:md|markdown)$/iu;
4
+ export function isMarkdownPath(path) {
5
+ const name = basename(path);
6
+ return MARKDOWN.test(name) && !/^\.(?:md|markdown)$/iu.test(name);
7
+ }
8
+ /**
9
+ * Parse `@tmux_ide_reader`: `{"version":1,"pid":N,"path":"/abs/notes.md"}`.
10
+ * A reader exists only while the process that set the option is alive, and
11
+ * only on the pane whose own process it is: `panePid` is that pane's
12
+ * `#{pane_pid}`. The CLI starts `tmux-ide show` with tmux's direct exec (no
13
+ * shell), so the pane's process is the reader itself and records exactly that
14
+ * pid. Equality rather than "a descendant of" needs no process-tree walk.
15
+ *
16
+ * What the tie rules out: an option left behind by a reader that has exited,
17
+ * and a later process that happens to reuse its pid. What it does not: the
18
+ * option is not proof that `tmux-ide show` set it. In a shell pane the shell
19
+ * is the pane's process, so the shell can set an option naming its own pid,
20
+ * and any process that can talk to the tmux server can read another pane's
21
+ * pid and set that pane's option. Both are the same user, who can already
22
+ * read the file; the reader grants no access they do not have.
23
+ */
24
+ export function readerOption(value, panePid, alive = processAlive) {
25
+ if (!value || value.length > 8192)
26
+ return null;
27
+ let parsed;
28
+ try {
29
+ parsed = JSON.parse(value);
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
35
+ return null;
36
+ const record = parsed;
37
+ if (Object.keys(record).sort().join(",") !== "path,pid,version")
38
+ return null;
39
+ const { version, pid, path } = record;
40
+ if (version !== 1 || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
41
+ return null;
42
+ if (!/^[1-9][0-9]*$/u.test(panePid) || String(pid) !== panePid)
43
+ return null;
44
+ if (typeof path !== "string" ||
45
+ path.length > 4096 ||
46
+ !isAbsolute(path) ||
47
+ hasControlCharacter(path) ||
48
+ !isMarkdownPath(path))
49
+ return null;
50
+ const name = basename(path);
51
+ if (name.length > 255)
52
+ return null;
53
+ if (!alive(pid))
54
+ return null;
55
+ return { name, path, pid };
56
+ }
57
+ function processAlive(pid) {
58
+ try {
59
+ process.kill(pid, 0);
60
+ return true;
61
+ }
62
+ catch {
63
+ // Including EPERM: a pid now owned by another user is not our reader.
64
+ return false;
65
+ }
66
+ }
@@ -1,4 +1,5 @@
1
1
  import { browserIcon } from "./browser-icon.js";
2
+ import { readerOption } from "./reader-option.js";
2
3
  /**
3
4
  * `qa` asks tmux to escape each value as a command argument. In particular,
4
5
  * embedded tabs/newlines/backslashes become escapes, leaving our record tabs
@@ -29,6 +30,9 @@ export const SESSION_PANE_DESCRIPTOR_FORMAT = [
29
30
  "#{pane_birth_id}",
30
31
  "#{qa:@tmux_ide_name_source}",
31
32
  "#{qa:@tmux_ide_browser_icon}",
33
+ "#{qa:@tmux_ide_reader}",
34
+ // The reader option belongs to the pane only when its own process set it.
35
+ "#{pane_pid}",
32
36
  ].join("\t");
33
37
  /** Decode the escapes emitted by tmux's `qa` format modifier. */
34
38
  export function decodeTmuxArgument(value) {
@@ -102,9 +106,9 @@ export function parseSessionPaneDescriptorReply(lines) {
102
106
  continue;
103
107
  }
104
108
  const encoded = utf8Line.split("\t");
105
- if (encoded.length !== 21 && encoded.length !== 22 && encoded.length !== 23)
109
+ if (encoded.length < 21 || encoded.length > 25)
106
110
  continue;
107
- const [runtimePaneId = "", semanticPaneId = "", role = "", type = "", currentCommand = "", cwd = "", windowIndexRaw = "", windowName = "", windowId = "", title = "", runtimeSessionId = "", paneIndexRaw = "", name = "", missionStamp = "", paneActiveRaw = "", windowActiveRaw = "", semanticWindowId = "", sessionName = "", windowPaneCountRaw = "", sessionWindowCountRaw = "", nativePaneBirthId = "", nameSource = "", browserIconRaw = "",] = encoded.map(decodeTmuxArgument);
111
+ const [runtimePaneId = "", semanticPaneId = "", role = "", type = "", currentCommand = "", cwd = "", windowIndexRaw = "", windowName = "", windowId = "", title = "", runtimeSessionId = "", paneIndexRaw = "", name = "", missionStamp = "", paneActiveRaw = "", windowActiveRaw = "", semanticWindowId = "", sessionName = "", windowPaneCountRaw = "", sessionWindowCountRaw = "", nativePaneBirthId = "", nameSource = "", browserIconRaw = "", readerRaw = "", panePidRaw = "",] = encoded.map(decodeTmuxArgument);
108
112
  if (!/^%(?:0|[1-9][0-9]*)$/u.test(runtimePaneId) || runtimePaneId.length > 32)
109
113
  continue;
110
114
  if (!/^\$(?:0|[1-9][0-9]*)$/u.test(runtimeSessionId) || runtimeSessionId.length > 32)
@@ -142,6 +146,7 @@ export function parseSessionPaneDescriptorReply(lines) {
142
146
  }
143
147
  descriptors.push({
144
148
  browserIcon: browserIcon(browserIconRaw),
149
+ reader: readerOption(readerRaw, panePidRaw),
145
150
  sessionName,
146
151
  runtimePaneId,
147
152
  runtimeSessionId,
@@ -0,0 +1,106 @@
1
+ /**
2
+ * `tmux-ide servers upgrade` (#766): flags, the `--ssh` hand-off, the detached
3
+ * worker's `--continue`, and the exit code. The steps are in ./run.ts.
4
+ */
5
+ import { spawnSync } from "node:child_process";
6
+ import { readFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { SavedMachineSchema } from "@tmux-ide/contracts";
9
+ import { IdeError } from "../lib/errors.js";
10
+ import { remoteTmuxIdeArgsCommand } from "../lib/remote-tmux-command.js";
11
+ import { createUpgradeIo, parseWorkerState, writeWorkerResult } from "./io.js";
12
+ import { finishUpgrade, retryCommand, upgradeServer, } from "./run.js";
13
+ /** The flags a remote run gets: the same choices, never the local socket defaults. */
14
+ export function forwardedUpgradeArgs(options) {
15
+ const args = [];
16
+ if (options.yes)
17
+ args.push("--yes");
18
+ if (options.endRunningAgents)
19
+ args.push("--end-running-agents");
20
+ if (!options.resumeAgents)
21
+ args.push("--no-resume-agents");
22
+ if (options.dryRun)
23
+ args.push("--dry-run");
24
+ if (options.json)
25
+ args.push("--json");
26
+ if (options.socketPath)
27
+ args.push("--socket-path", options.socketPath);
28
+ if (options.socketName)
29
+ args.push("--socket-name", options.socketName);
30
+ return args;
31
+ }
32
+ const EXIT = {
33
+ "already-full": 0,
34
+ preview: 0,
35
+ declined: 0,
36
+ "handed-off": 0,
37
+ upgraded: 0,
38
+ refused: 1,
39
+ failed: 1,
40
+ };
41
+ function report(result, json) {
42
+ if (json) {
43
+ process.stdout.write(`${JSON.stringify(result)}\n`);
44
+ return;
45
+ }
46
+ // The plan was already printed before the question; print it here only for a preview.
47
+ console.log(result.status === "preview"
48
+ ? `${result.message}\n\nDry run: nothing was stopped.`
49
+ : result.message);
50
+ }
51
+ export async function runUpgradeCli(options) {
52
+ if (options.socketPath && options.socketName)
53
+ throw new IdeError("Pass --socket-path or --socket-name, not both.", {
54
+ code: "USAGE",
55
+ exitCode: 2,
56
+ });
57
+ if (options.ssh !== undefined) {
58
+ SavedMachineSchema.shape.sshTarget.parse(options.ssh);
59
+ // The remote runs the same command against its own server, bundle and
60
+ // hostname; its prompt answers here through the terminal.
61
+ const child = spawnSync("ssh", [
62
+ ...(options.json ? ["-T"] : ["-t"]),
63
+ "--",
64
+ options.ssh,
65
+ remoteTmuxIdeArgsCommand(["servers", "upgrade", ...forwardedUpgradeArgs(options)]),
66
+ ], { stdio: "inherit" });
67
+ if (child.error)
68
+ throw new IdeError("Could not start ssh.", { code: "SSH", exitCode: 1 });
69
+ if (child.status !== 0)
70
+ process.exitCode = child.status ?? 1;
71
+ return;
72
+ }
73
+ if (options.continueFrom !== undefined) {
74
+ const work = parseWorkerState(readFileSync(options.continueFrom, "utf8"));
75
+ const io = createUpgradeIo({
76
+ target: { socketPath: work.server.socketPath },
77
+ cliEntry: options.cliEntry,
78
+ json: false,
79
+ });
80
+ // Nothing the foreground's terminal does may stop the worker mid-restore.
81
+ for (const signal of ["SIGHUP", "SIGINT", "SIGPIPE"])
82
+ process.on(signal, () => { });
83
+ let result;
84
+ try {
85
+ result = await finishUpgrade(io, work);
86
+ }
87
+ catch (error) {
88
+ result = {
89
+ status: "failed",
90
+ message: `${error.message} If the sessions are missing, run: ${retryCommand(work.snapshotPath, work.resumeAgents)}`,
91
+ };
92
+ }
93
+ console.log(`${new Date().toISOString()} ${result.status}: ${result.message}`);
94
+ writeWorkerResult(join(dirname(options.continueFrom), "result.json"), result);
95
+ process.exitCode = EXIT[result.status];
96
+ return;
97
+ }
98
+ const io = createUpgradeIo({
99
+ target: { socketPath: options.socketPath, socketName: options.socketName },
100
+ cliEntry: options.cliEntry,
101
+ json: options.json,
102
+ });
103
+ const result = await upgradeServer(io, options);
104
+ report(result, options.json);
105
+ process.exitCode = EXIT[result.status];
106
+ }