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
@@ -114,7 +114,7 @@ export function validateBrowserOpen(url: string | undefined, options: OpenBrowse
114
114
  });
115
115
  }
116
116
 
117
- type Run = (args: readonly string[]) => string;
117
+ export type Run = (args: readonly string[]) => string;
118
118
 
119
119
  /** Printed when the opened browser never publishes tmux-ide's native controls. */
120
120
  export const NO_NATIVE_CONTROLS_NOTICE =
@@ -163,16 +163,16 @@ export async function nativeControlsNotice(
163
163
  await sleep(250);
164
164
  }
165
165
  }
166
- export function createBrowserPane(
166
+ type PaneKind = "BROWSER" | "READER";
167
+
168
+ /** Where a new browser or reader pane goes: resolved IDs, before any mutation. */
169
+ export function resolveOpenPaneTarget(
167
170
  run: Run,
168
- executable: string,
169
- url: string | undefined,
170
171
  options: OpenBrowserOptions,
171
172
  environment: NodeJS.ProcessEnv,
172
- cwd: string,
173
- namespace: Readonly<Record<string, string>>,
174
- ): { pane: string; session: string; window: string; status: "created" } {
175
- validateBrowserOpen(url, options);
173
+ kind: PaneKind = "BROWSER",
174
+ ): { session: string; window: string; sourcePane: string } {
175
+ const noun = kind.toLowerCase();
176
176
  const inheritedPane = /^%\d+$/u.test(environment.TMUX_PANE ?? "")
177
177
  ? environment.TMUX_PANE
178
178
  : undefined;
@@ -188,7 +188,7 @@ export function createBrowserPane(
188
188
  if (!target)
189
189
  throw new IdeError(
190
190
  "Run tmux-ide open inside a tmux pane, or select a session with --session NAME.",
191
- { code: "BROWSER_TARGET_REQUIRED", exitCode: 2 },
191
+ { code: `${kind}_TARGET_REQUIRED`, exitCode: 2 },
192
192
  );
193
193
  // Resolve IDs before mutation. No implicit last-used session or window target.
194
194
  const identity = run([
@@ -207,13 +207,13 @@ export function createBrowserPane(
207
207
  !/^@\d+$/u.test(window ?? "") ||
208
208
  !/^%\d+$/u.test(sourcePane ?? "")
209
209
  )
210
- throw new IdeError("The browser target is no longer available.", {
211
- code: "BROWSER_TARGET_UNAVAILABLE",
210
+ throw new IdeError(`The ${noun} target is no longer available.`, {
211
+ code: `${kind}_TARGET_UNAVAILABLE`,
212
212
  });
213
213
  if (implicit && serverPid !== inheritedServer?.[2])
214
214
  throw new IdeError(
215
215
  "The current pane belongs to a different tmux server. Select a session explicitly.",
216
- { code: "BROWSER_TARGET_MISMATCH", exitCode: 2 },
216
+ { code: `${kind}_TARGET_MISMATCH`, exitCode: 2 },
217
217
  );
218
218
  if (options.session && options.pane) {
219
219
  const selected = run([
@@ -225,21 +225,38 @@ export function createBrowserPane(
225
225
  ]).trim();
226
226
  if (selected !== session)
227
227
  throw new IdeError("The pane does not belong to the requested session.", {
228
- code: "BROWSER_TARGET_MISMATCH",
228
+ code: `${kind}_TARGET_MISMATCH`,
229
229
  exitCode: 2,
230
230
  });
231
231
  }
232
+ return { session: session!, window: window!, sourcePane: sourcePane! };
233
+ }
234
+
235
+ /**
236
+ * The tmux argv that creates the pane and runs `command` in it directly (no
237
+ * shell parsing). `format` is what tmux prints for the new pane.
238
+ */
239
+ export function openPaneArgs(
240
+ target: { session: string; window: string; sourcePane: string },
241
+ options: OpenBrowserOptions,
242
+ environment: NodeJS.ProcessEnv,
243
+ cwd: string,
244
+ namespace: Readonly<Record<string, string>>,
245
+ command: readonly string[],
246
+ format: string,
247
+ windowName: string,
248
+ ): string[] {
232
249
  const args = options.window
233
- ? ["new-window", "-t", `${session}:`, "-n", "Browser"]
250
+ ? ["new-window", "-t", `${target.session}:`, "-n", windowName]
234
251
  : [
235
252
  "split-window",
236
253
  options.split === "down" ? "-v" : "-h",
237
254
  "-t",
238
- `${session}:${window}.${sourcePane}`,
255
+ `${target.session}:${target.window}.${target.sourcePane}`,
239
256
  "-l",
240
257
  `${options.size ?? "50"}%`,
241
258
  ];
242
- args.push("-c", resolve(cwd), "-P", "-F", "#{session_id}\t#{window_id}\t#{pane_id}");
259
+ args.push("-c", resolve(cwd), "-P", "-F", format);
243
260
  // tmux supplies the new pane's TMUX and TMUX_PANE. Never copy the caller's
244
261
  // native-surface route, which belongs to a different pane.
245
262
  const childEnvironment: Record<string, string> = { ...namespace };
@@ -255,11 +272,35 @@ export function createBrowserPane(
255
272
  if (environment[key] !== undefined) childEnvironment[key] = environment[key];
256
273
  for (const [key, value] of Object.entries(childEnvironment)) args.push("-e", `${key}=${value}`);
257
274
  // Multiple command arguments use tmux's direct exec path, not shell parsing.
258
- args.push(executable, "open", ...(url === undefined ? [] : [url]), "--no-merge");
275
+ args.push(...command);
276
+ return args;
277
+ }
278
+
279
+ export function createBrowserPane(
280
+ run: Run,
281
+ executable: string,
282
+ url: string | undefined,
283
+ options: OpenBrowserOptions,
284
+ environment: NodeJS.ProcessEnv,
285
+ cwd: string,
286
+ namespace: Readonly<Record<string, string>>,
287
+ ): { pane: string; session: string; window: string; status: "created" } {
288
+ validateBrowserOpen(url, options);
289
+ const target = resolveOpenPaneTarget(run, options, environment);
290
+ const args = openPaneArgs(
291
+ target,
292
+ options,
293
+ environment,
294
+ cwd,
295
+ namespace,
296
+ [executable, "open", ...(url === undefined ? [] : [url]), "--no-merge"],
297
+ "#{session_id}\t#{window_id}\t#{pane_id}",
298
+ "Browser",
299
+ );
259
300
  const [createdSession, createdWindow, pane] = run(args).trim().split("\t");
260
301
  if (
261
302
  !/^%\d+$/u.test(pane ?? "") ||
262
- createdSession !== session ||
303
+ createdSession !== target.session ||
263
304
  !/^@\d+$/u.test(createdWindow ?? "")
264
305
  )
265
306
  throw new IdeError("tmux did not return the created browser pane ID.", {
@@ -0,0 +1,148 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { relative, resolve } from "node:path";
3
+ import { resolveCliCommand } from "./lib/cli-command.ts";
4
+ import { IdeError } from "./lib/errors.ts";
5
+ import { resolveRuntimeNamespace, runtimeNamespaceEnvironment } from "./lib/runtime-namespace.ts";
6
+ import {
7
+ createPinnedWorkspaceTmuxRunner,
8
+ resolveWorkspacePaneTmuxAuthority,
9
+ } from "./lib/workspace-pane-creation.ts";
10
+ import {
11
+ openPaneArgs,
12
+ resolveOpenPaneTarget,
13
+ validateBrowserOpen,
14
+ type OpenBrowserOptions,
15
+ type Run,
16
+ } from "./open-browser.ts";
17
+ import { isMarkdownPath } from "./terminal/protocol/reader-option.ts";
18
+
19
+ export type OpenTarget =
20
+ | { kind: "browser" }
21
+ | {
22
+ kind: "reader";
23
+ /** Absolute real path. */
24
+ path: string;
25
+ /** The path as the user named it, relative to their cwd. */
26
+ display: string;
27
+ };
28
+
29
+ const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//iu;
30
+ const MARKDOWN_ARGUMENT = /\.(?:md|markdown)$/iu;
31
+
32
+ /**
33
+ * Decides what `tmux-ide open <arg>` opens. A Markdown file name with no
34
+ * `scheme://` is read in the native reader and must exist; everything else
35
+ * goes to the browser exactly as before.
36
+ */
37
+ export function classifyOpenTarget(
38
+ arg: string | undefined,
39
+ cwd: string,
40
+ fs: { realpath(path: string): string; isFile(path: string): boolean } = {
41
+ realpath: (path) => realpathSync(path),
42
+ isFile: (path) => statSync(path).isFile(),
43
+ },
44
+ ): OpenTarget {
45
+ if (arg === undefined || SCHEME_URL.test(arg) || !MARKDOWN_ARGUMENT.test(arg))
46
+ return { kind: "browser" };
47
+ const named = resolve(cwd, arg);
48
+ const display = relative(cwd, named) || named;
49
+ let path: string;
50
+ try {
51
+ path = fs.realpath(named);
52
+ if (!fs.isFile(path)) throw new Error("not a file");
53
+ } catch {
54
+ throw new IdeError(`No Markdown file at ${display}.`, {
55
+ code: "FILE_NOT_FOUND",
56
+ exitCode: 2,
57
+ });
58
+ }
59
+ if (!isMarkdownPath(path))
60
+ throw new IdeError(`${display} does not resolve to a Markdown file.`, {
61
+ code: "NOT_MARKDOWN",
62
+ exitCode: 2,
63
+ });
64
+ return { kind: "reader", path, display };
65
+ }
66
+
67
+ export interface ReaderPaneResult {
68
+ pane: string;
69
+ session: string;
70
+ window: string;
71
+ status: "created";
72
+ kind: "reader";
73
+ }
74
+
75
+ /**
76
+ * Splits a pane running `tmux-ide show <file>` (the TUI renderer, which also
77
+ * watches the file) and stamps `@tmux_ide_reader` with that process's pid,
78
+ * which is what lets the Mac app paint its native reader over the pane.
79
+ */
80
+ export function createReaderPane(
81
+ run: Run,
82
+ cli: readonly string[],
83
+ path: string,
84
+ options: OpenBrowserOptions,
85
+ environment: NodeJS.ProcessEnv,
86
+ cwd: string,
87
+ namespace: Readonly<Record<string, string>>,
88
+ ): ReaderPaneResult {
89
+ validateBrowserOpen(undefined, options);
90
+ const target = resolveOpenPaneTarget(run, options, environment, "READER");
91
+ const args = openPaneArgs(
92
+ target,
93
+ options,
94
+ environment,
95
+ cwd,
96
+ namespace,
97
+ [...cli, "show", path],
98
+ "#{session_id}\t#{window_id}\t#{pane_id}\t#{pane_pid}",
99
+ "Reader",
100
+ );
101
+ const [session, window, pane, pid] = run(args).trim().split("\t");
102
+ if (
103
+ !/^%\d+$/u.test(pane ?? "") ||
104
+ session !== target.session ||
105
+ !/^@\d+$/u.test(window ?? "") ||
106
+ !/^[1-9]\d{0,9}$/u.test(pid ?? "")
107
+ )
108
+ throw new IdeError("tmux did not return the created reader pane.", {
109
+ code: "READER_CREATE_FAILED",
110
+ });
111
+ run([
112
+ "set-option",
113
+ "-p",
114
+ "-t",
115
+ pane!,
116
+ "@tmux_ide_reader",
117
+ JSON.stringify({ version: 1, pid: Number(pid), path }),
118
+ ]);
119
+ return { pane: pane!, session: session!, window: window!, status: "created", kind: "reader" };
120
+ }
121
+
122
+ export async function openReader(
123
+ target: Extract<OpenTarget, { kind: "reader" }>,
124
+ options: OpenBrowserOptions = {},
125
+ ): Promise<ReaderPaneResult> {
126
+ validateBrowserOpen(undefined, options);
127
+ try {
128
+ const namespace = { ...runtimeNamespaceEnvironment(resolveRuntimeNamespace()) };
129
+ const run = createPinnedWorkspaceTmuxRunner(resolveWorkspacePaneTmuxAuthority(), {
130
+ timeoutMs: 10_000,
131
+ });
132
+ return createReaderPane(
133
+ run,
134
+ resolveCliCommand(),
135
+ target.path,
136
+ options,
137
+ process.env,
138
+ process.cwd(),
139
+ namespace,
140
+ );
141
+ } catch (error) {
142
+ if (error instanceof IdeError) throw error;
143
+ throw new IdeError(
144
+ "Could not create the reader pane. Check that the target tmux session is running.",
145
+ { code: "READER_CREATE_FAILED", cause: error instanceof Error ? error : undefined },
146
+ );
147
+ }
148
+ }
@@ -15,6 +15,7 @@ import {
15
15
  type NotifyLevel,
16
16
  } from "./host-calls.ts";
17
17
  import { cliRunner } from "./worktree-calls.ts";
18
+ import { resolveCliCommand } from "../lib/cli-command.ts";
18
19
  import { defaultControlSocketPath } from "../control/server.ts";
19
20
  import { DEFAULT_PLUGIN_LIMITS } from "./protocol.ts";
20
21
  import { minimalHostEnv, PluginSupervisor, secretEnvValues } from "./supervisor.ts";
@@ -85,18 +86,7 @@ export async function tmuxSocketDirs(
85
86
  return [...dirs];
86
87
  }
87
88
 
88
- /**
89
- * The argv prefix that runs this tmux-ide's CLI: the bundled `bin/cli.js`,
90
- * or `bin/cli.ts` under the runtime's loader flags when run from source.
91
- */
92
- export function resolveCliCommand(
93
- here: string = fileURLToPath(import.meta.url),
94
- runtime: { execPath: string; execArgv: readonly string[] } = process,
95
- ): string[] {
96
- if (basename(here) === "cli.js") return [runtime.execPath, here];
97
- const cli = join(dirname(here), "..", "..", "..", "..", "bin", `cli${extname(here)}`);
98
- return [runtime.execPath, ...runtime.execArgv, cli];
99
- }
89
+ export { resolveCliCommand } from "../lib/cli-command.ts";
100
90
 
101
91
  /**
102
92
  * Files programs from plugins may not read: the daemon record (its port and
@@ -365,6 +365,23 @@ export interface RestoreOptions {
365
365
  runCommands?: boolean;
366
366
  /** Relaunch resumable agent panes (`--resume-agents`); ORed with config default. */
367
367
  resumeAgents?: boolean;
368
+ /** Read this snapshot file instead of `~/.tmux-ide/snapshot.json` (`--from`). */
369
+ from?: string;
370
+ /** Rebuild every session from the snapshot, never from its workspace config. */
371
+ snapshotOnly?: boolean;
372
+ /** OR `resumeAgents` with the config default (default true). The upgrade passes false. */
373
+ resumeFromConfig?: boolean;
374
+ }
375
+
376
+ /** What one restore run did; sessions that threw while rebuilding are in `failed`. */
377
+ export interface RestoreOutcome {
378
+ snapshot: FleetSnapshot;
379
+ plan: RestorePlan;
380
+ restored: string[];
381
+ launched: string[];
382
+ resumed: ResumedSession[];
383
+ failed: string[];
384
+ resumeAgents: boolean;
368
385
  }
369
386
 
370
387
  /** One rebuilt session's resumed agent panes (for the report). */
@@ -380,75 +397,88 @@ interface ResumedSession {
380
397
  * (flag ORed with the `~/.tmux-ide/config.json` default) revives agent
381
398
  * conversations via `claude --resume <id>`.
382
399
  */
383
- export async function restore({
400
+ export async function restore(options: RestoreOptions = {}): Promise<void> {
401
+ const { json = false, dryRun = false } = options;
402
+ const outcome = await restoreFleet(options);
403
+ reportPlan(outcome.plan, outcome.snapshot, { ...outcome, json, dryRun });
404
+ if (outcome.failed.length) {
405
+ throw new IdeError(`could not rebuild ${outcome.failed.join(", ")}`, {
406
+ code: "RESTORE_FAILED",
407
+ exitCode: 1,
408
+ });
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Rebuild the fleet without printing. One session failing to rebuild does not
414
+ * stop the rest; it is listed in `failed`.
415
+ */
416
+ export async function restoreFleet({
384
417
  json = false,
385
418
  dryRun = false,
386
419
  runCommands = false,
387
420
  resumeAgents = false,
388
- }: RestoreOptions = {}): Promise<void> {
389
- const snapshot = readSnapshot();
421
+ from,
422
+ snapshotOnly = false,
423
+ resumeFromConfig = true,
424
+ }: RestoreOptions = {}): Promise<RestoreOutcome> {
425
+ const snapshot = readSnapshot(from);
390
426
  if (!snapshot) {
391
427
  throw new IdeError(
392
- "no snapshot yet — the updater writes one every ~30s while any session is adopted",
428
+ from
429
+ ? `no readable snapshot at ${from}`
430
+ : "no snapshot yet — the updater writes one every ~30s while any session is adopted",
393
431
  { code: "NO_SNAPSHOT", exitCode: 1 },
394
432
  );
395
433
  }
396
434
 
397
435
  // The flag forces resume on; config makes it the default. No negative flag.
398
- const resume = resumeAgents || readRestorePrefs().resumeAgents;
399
- const plan = buildRestorePlan(snapshot, liveSessions(), ideBackedProjects());
400
-
401
- if (dryRun) {
402
- reportPlan(plan, snapshot, {
403
- json,
404
- dryRun: true,
405
- restored: [],
406
- launched: [],
407
- resumed: [],
408
- resumeAgents: resume,
409
- });
410
- return;
411
- }
436
+ const resume = resumeAgents || (resumeFromConfig && readRestorePrefs().resumeAgents);
437
+ const plan = buildRestorePlan(
438
+ snapshot,
439
+ liveSessions(),
440
+ snapshotOnly ? new Map() : ideBackedProjects(),
441
+ );
442
+ const outcome: RestoreOutcome = {
443
+ snapshot,
444
+ plan,
445
+ restored: [],
446
+ launched: [],
447
+ resumed: [],
448
+ failed: [],
449
+ resumeAgents: resume,
450
+ };
451
+ if (dryRun) return outcome;
412
452
 
413
- const restored: string[] = [];
414
- const launched: string[] = [];
415
- const resumed: ResumedSession[] = [];
416
453
  const recordResumed = (session: string, panes: string[]) => {
417
- if (panes.length) resumed.push({ session, panes });
454
+ if (panes.length) outcome.resumed.push({ session, panes });
455
+ };
456
+ const rebuild = (session: SessionSnapshot) => {
457
+ try {
458
+ recordResumed(session.name, rebuildSession(session, { runCommands, resumeAgents: resume }));
459
+ } catch {
460
+ outcome.failed.push(session.name);
461
+ return;
462
+ }
463
+ if (session.adopted) safeAdopt(session.name);
464
+ outcome.restored.push(session.name);
418
465
  };
419
466
  for (const action of plan.actions) {
420
467
  if (action.kind === "skip") continue;
421
468
  if (action.kind === "launch") {
422
469
  const ok = await launchProject(action.dir, json);
423
- if (ok) launched.push(action.session);
470
+ if (ok) outcome.launched.push(action.session);
424
471
  else {
425
472
  // Launch failed — fall back to a raw rebuild from the snapshot so the
426
473
  // session still comes back.
427
474
  const snap = snapshot.sessions.find((s) => s.name === action.session);
428
- if (snap) {
429
- recordResumed(snap.name, rebuildSession(snap, { runCommands, resumeAgents: resume }));
430
- if (snap.adopted) safeAdopt(snap.name);
431
- restored.push(action.session);
432
- }
475
+ if (snap) rebuild(snap);
433
476
  }
434
477
  continue;
435
478
  }
436
- recordResumed(
437
- action.session.name,
438
- rebuildSession(action.session, { runCommands, resumeAgents: resume }),
439
- );
440
- if (action.session.adopted) safeAdopt(action.session.name);
441
- restored.push(action.session.name);
479
+ rebuild(action.session);
442
480
  }
443
-
444
- reportPlan(plan, snapshot, {
445
- json,
446
- dryRun: false,
447
- restored,
448
- launched,
449
- resumed,
450
- resumeAgents: resume,
451
- });
481
+ return outcome;
452
482
  }
453
483
 
454
484
  /** Adopt a restored session into the chrome; never let a chrome failure abort restore. */
@@ -488,12 +518,14 @@ interface ReportContext {
488
518
  resumed: ResumedSession[];
489
519
  /** Whether resume is on (drives the dry-run `(would resume N agents)` note). */
490
520
  resumeAgents: boolean;
521
+ /** Sessions whose rebuild threw. */
522
+ failed: string[];
491
523
  }
492
524
 
493
525
  function reportPlan(
494
526
  plan: RestorePlan,
495
527
  snapshot: FleetSnapshot,
496
- { json, dryRun, restored, launched, resumed, resumeAgents }: ReportContext,
528
+ { json, dryRun, restored, launched, resumed, resumeAgents, failed }: ReportContext,
497
529
  ): void {
498
530
  const skipped = plan.actions.filter((a) => a.kind === "skip").map((a) => a.session);
499
531
  const willLaunch = plan.actions.filter((a) => a.kind === "launch").map((a) => a.session);
@@ -513,6 +545,7 @@ function reportPlan(
513
545
  resumeAgents,
514
546
  resumedPanes,
515
547
  resumed,
548
+ failed,
516
549
  },
517
550
  null,
518
551
  2,
@@ -553,5 +586,8 @@ function reportPlan(
553
586
  parts.push(`rebuilt ${restored.map((s) => `${s}${resumeSuffix(s)}`).join(", ")}`);
554
587
  if (launched.length) parts.push(`launched ${launched.join(", ")}`);
555
588
  if (skipped.length) parts.push(`skipped ${skipped.join(", ")} (already running)`);
589
+ if (failed.length) parts.push(`failed to rebuild ${failed.join(", ")}`);
590
+ // Name the snapshot's age: an old snapshot brings back an old fleet (#766).
591
+ console.log(`Snapshot saved ${snapshot.savedAt}.`);
556
592
  console.log(parts.length ? `Restored: ${parts.join("; ")}` : "Nothing to restore.");
557
593
  }
@@ -92,6 +92,8 @@ export type MirrorPaneEvent =
92
92
  /** One visible pane rectangle inside a layout event, in window cells. */
93
93
  export interface MirrorLayoutPane {
94
94
  browserIcon?: string | null;
95
+ /** A live Markdown reader pane; the path is daemon-only and never framed. */
96
+ reader?: { name: string; path: string } | null;
95
97
  /** Null while the pane's semantic identity join is still unverified. */
96
98
  semanticPaneId: string | null;
97
99
  /** Daemon-authored presentation; clients never infer this from terminal bytes. */
@@ -753,6 +753,7 @@ export class SessionChannel {
753
753
  await this.io.start();
754
754
  await this.captureAttachedSessionIdentity();
755
755
  this.io.send("refresh-client -B 'tmux-ide-browser-icon:%*:#{@tmux_ide_browser_icon}'");
756
+ this.io.send("refresh-client -B 'tmux-ide-reader:%*:#{@tmux_ide_reader}'");
756
757
  // Changing border placement can resize PTYs without changing the layout
757
758
  // string, so tmux emits no layout-change. Subscribe to this window option.
758
759
  this.io.send("refresh-client -B 'tmux-ide-pane-borders:@*:#{pane-border-status}'");
@@ -2904,7 +2905,10 @@ export class SessionChannel {
2904
2905
  name === "sessions-changed"
2905
2906
  )
2906
2907
  this.opts.onWindowTopologyChanged?.();
2907
- if (name === "subscription-changed" && rest.startsWith("tmux-ide-browser-icon ")) {
2908
+ if (
2909
+ name === "subscription-changed" &&
2910
+ (rest.startsWith("tmux-ide-browser-icon ") || rest.startsWith("tmux-ide-reader "))
2911
+ ) {
2908
2912
  this.scheduleSync();
2909
2913
  return;
2910
2914
  }
@@ -3325,6 +3329,7 @@ export class SessionChannel {
3325
3329
  displayName: display?.name ?? null,
3326
3330
  displayNameSource: display?.source ?? null,
3327
3331
  browserIcon: pane?.descriptor?.browserIcon ?? null,
3332
+ reader: pane?.descriptor?.reader ?? null,
3328
3333
  left: leaf.left,
3329
3334
  top: leaf.top,
3330
3335
  width: leaf.width,
@@ -22,6 +22,8 @@ import type { LocalImageOwner } from "../graphics/local-image-owner.ts";
22
22
  import {
23
23
  PANE_STREAM_INPUT_LIFETIME_CAPABILITY_VERSION,
24
24
  PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION,
25
+ PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION,
26
+ PANE_STREAM_READER_CAPABILITY_VERSION,
25
27
  type PaneStreamInputLifetime,
26
28
  } from "@tmux-ide/contracts";
27
29
  import { inflateSync } from "node:zlib";
@@ -1933,7 +1935,10 @@ export class PaneStreamLiveConnection {
1933
1935
  // when served.
1934
1936
  const zlib =
1935
1937
  this.#descriptor.terminalDelivery?.protocolVersions.some(
1936
- (version) => version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION || version === 117,
1938
+ (version) =>
1939
+ version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION ||
1940
+ version === PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION ||
1941
+ version === PANE_STREAM_READER_CAPABILITY_VERSION,
1937
1942
  ) === true;
1938
1943
  channel.graphicsZlib = zlib;
1939
1944
  channel.graphicsLocal =
@@ -2414,6 +2419,10 @@ export class PaneStreamLiveConnection {
2414
2419
  this.#sendFrame(null, frame);
2415
2420
  }
2416
2421
 
2422
+ #offers(version: number): boolean {
2423
+ return this.#descriptor.terminalDelivery?.protocolVersions.includes(version) === true;
2424
+ }
2425
+
2417
2426
  #layoutFrame(event: MirrorLayoutEvent): PaneStreamServerFrame | null {
2418
2427
  const frame = {
2419
2428
  type: "layout",
@@ -2429,9 +2438,13 @@ export class PaneStreamLiveConnection {
2429
2438
  pane: pane.semanticPaneId,
2430
2439
  displayName: pane.displayName,
2431
2440
  displayNameSource: pane.displayNameSource,
2432
- ...(this.#descriptor.terminalDelivery?.protocolVersions.includes(117)
2441
+ ...(this.#offers(PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION) ||
2442
+ this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
2433
2443
  ? { browserIcon: pane.browserIcon ?? null }
2434
2444
  : {}),
2445
+ ...(this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
2446
+ ? { reader: pane.reader ? { name: pane.reader.name } : null }
2447
+ : {}),
2435
2448
  left: pane.left,
2436
2449
  top: pane.top,
2437
2450
  width: pane.width,
@@ -0,0 +1,77 @@
1
+ import { basename, isAbsolute } from "node:path";
2
+ import { hasControlCharacter } from "@tmux-ide/contracts";
3
+
4
+ export interface ReaderOption {
5
+ /** The file name shown in the pane header. */
6
+ name: string;
7
+ /** Absolute real path; daemon-only, never sent to clients. */
8
+ path: string;
9
+ /** The reader process: the pane's own process. */
10
+ pid: number;
11
+ }
12
+
13
+ const MARKDOWN = /\.(?:md|markdown)$/iu;
14
+
15
+ export function isMarkdownPath(path: string): boolean {
16
+ const name = basename(path);
17
+ return MARKDOWN.test(name) && !/^\.(?:md|markdown)$/iu.test(name);
18
+ }
19
+
20
+ /**
21
+ * Parse `@tmux_ide_reader`: `{"version":1,"pid":N,"path":"/abs/notes.md"}`.
22
+ * A reader exists only while the process that set the option is alive, and
23
+ * only on the pane whose own process it is: `panePid` is that pane's
24
+ * `#{pane_pid}`. The CLI starts `tmux-ide show` with tmux's direct exec (no
25
+ * shell), so the pane's process is the reader itself and records exactly that
26
+ * pid. Equality rather than "a descendant of" needs no process-tree walk.
27
+ *
28
+ * What the tie rules out: an option left behind by a reader that has exited,
29
+ * and a later process that happens to reuse its pid. What it does not: the
30
+ * option is not proof that `tmux-ide show` set it. In a shell pane the shell
31
+ * is the pane's process, so the shell can set an option naming its own pid,
32
+ * and any process that can talk to the tmux server can read another pane's
33
+ * pid and set that pane's option. Both are the same user, who can already
34
+ * read the file; the reader grants no access they do not have.
35
+ */
36
+ export function readerOption(
37
+ value: string,
38
+ panePid: string,
39
+ alive = processAlive,
40
+ ): ReaderOption | null {
41
+ if (!value || value.length > 8192) return null;
42
+ let parsed: unknown;
43
+ try {
44
+ parsed = JSON.parse(value);
45
+ } catch {
46
+ return null;
47
+ }
48
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
49
+ const record = parsed as Record<string, unknown>;
50
+ if (Object.keys(record).sort().join(",") !== "path,pid,version") return null;
51
+ const { version, pid, path } = record;
52
+ if (version !== 1 || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
53
+ return null;
54
+ if (!/^[1-9][0-9]*$/u.test(panePid) || String(pid) !== panePid) return null;
55
+ if (
56
+ typeof path !== "string" ||
57
+ path.length > 4096 ||
58
+ !isAbsolute(path) ||
59
+ hasControlCharacter(path) ||
60
+ !isMarkdownPath(path)
61
+ )
62
+ return null;
63
+ const name = basename(path);
64
+ if (name.length > 255) return null;
65
+ if (!alive(pid)) return null;
66
+ return { name, path, pid };
67
+ }
68
+
69
+ function processAlive(pid: number): boolean {
70
+ try {
71
+ process.kill(pid, 0);
72
+ return true;
73
+ } catch {
74
+ // Including EPERM: a pid now owned by another user is not our reader.
75
+ return false;
76
+ }
77
+ }