tmux-ide 2.9.24 → 2.9.26

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 (77) hide show
  1. package/bin/cli.js +1689 -393
  2. package/package.json +5 -2
  3. package/packages/contracts/src/pane-stream.ts +72 -0
  4. package/packages/contracts/src/terminal-delivery.ts +8 -2
  5. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  6. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  7. package/packages/daemon/dist/command-center/discovery.js +24 -5
  8. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  9. package/packages/daemon/dist/command-center/server.js +81 -75
  10. package/packages/daemon/dist/command-center/tmux-servers.js +17 -7
  11. package/packages/daemon/dist/doctor.js +46 -10
  12. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  13. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  14. package/packages/daemon/dist/lib/daemon-embed.js +6 -0
  15. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  16. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  17. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  18. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  19. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  20. package/packages/daemon/dist/lib/update-check.js +18 -0
  21. package/packages/daemon/dist/lib/update-daemon-outcome.js +31 -0
  22. package/packages/daemon/dist/lib/update.js +39 -14
  23. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  27. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  28. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  29. package/packages/daemon/dist/terminal/mirror/session-channel.js +31 -2
  30. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  31. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +831 -222
  32. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  33. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  34. package/packages/daemon/dist/terminal/session-runtime/registry.js +25 -2
  35. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +121 -6
  36. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +79 -2
  37. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  38. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  39. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  40. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  41. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  42. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  43. package/packages/daemon/src/command-center/discovery.ts +24 -4
  44. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  45. package/packages/daemon/src/command-center/server.ts +67 -67
  46. package/packages/daemon/src/command-center/tmux-servers.ts +19 -6
  47. package/packages/daemon/src/doctor.ts +50 -9
  48. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  49. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  50. package/packages/daemon/src/lib/daemon-embed.ts +22 -0
  51. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  52. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  53. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  54. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  55. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  56. package/packages/daemon/src/lib/update-check.ts +34 -0
  57. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  58. package/packages/daemon/src/lib/update.ts +58 -16
  59. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  60. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  61. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  62. package/packages/daemon/src/terminal/mirror/session-channel.ts +38 -2
  63. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  64. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +915 -236
  65. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  66. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  67. package/packages/daemon/src/terminal/session-runtime/registry.ts +36 -2
  68. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +136 -6
  69. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  70. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +76 -2
  71. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  72. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  73. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
  74. package/packages/daemon/src/tui/chrome/snapshot.ts +47 -1
  75. package/packages/daemon/src/tui/chrome/statusline.ts +7 -4
  76. package/packages/daemon/src/tui/chrome/updater.ts +3 -0
  77. package/packages/daemon-client/src/pane-stream-client.ts +47 -5
@@ -6,7 +6,7 @@ import { accessSync, constants, existsSync, mkdtempSync, realpathSync, rmSync }
6
6
  import { tmpdir } from "node:os";
7
7
  import { delimiter, resolve, dirname, join } from "node:path";
8
8
  import { resolveBundledTmux } from "./lib/bundled-tmux.ts";
9
- import { readSnapshot } from "./tui/chrome/snapshot.ts";
9
+ import { readSnapshot, snapshotIsRestorePoint } from "./tui/chrome/snapshot.ts";
10
10
  import { isListableSession } from "./tui/team/sessions.ts";
11
11
  import { nativeCommands, type NativeAnswer, type TmuxProbe } from "./lib/tmux-server-features.ts";
12
12
  import { fileURLToPath } from "node:url";
@@ -194,7 +194,7 @@ export function tmuxFeaturesRow(probeServer: TmuxProbe, probeBinary: TmuxProbe):
194
194
  : "";
195
195
  const details: Record<NativeAnswer, string> = {
196
196
  full: "bundled tmux: full features",
197
- stock: `stock tmux: reduced features${upgrade}`,
197
+ stock: `stock tmux: reduced features (tab positions in saved output are reconstructed)${upgrade}`,
198
198
  older: `older tmux-ide tmux: reduced features${upgrade}`,
199
199
  partial: "this tmux has only some tmux-ide commands: no pane dividers",
200
200
  "no-server": "could not read the tmux server's features",
@@ -235,17 +235,20 @@ const DAY_MS = 24 * 60 * 60 * 1000;
235
235
 
236
236
  /**
237
237
  * PURE — is the crash snapshot fresh enough to restore from? It fails when it
238
- * is missing a live session, or is over a day old while sessions run. Only the
239
- * chrome updater writes it, and that runs only while a session is adopted.
238
+ * is missing a live session, or is over a day old while sessions run. The
239
+ * chrome updater writes it while a session is adopted; otherwise the background
240
+ * service does, for its default server (lib/daemon-crash-snapshot.ts).
240
241
  */
241
242
  export function snapshotRow(
242
243
  snapshot: { savedAt: string; sessions: readonly { name: string }[] } | null,
243
244
  liveSessions: readonly string[] | null,
244
245
  nowMs: number,
246
+ /** When the running tmux server started, if known. */
247
+ serverStartMs: number | null = null,
245
248
  ): CheckResult {
246
249
  const label = "crash snapshot (restore)";
247
250
  const hint =
248
- "Only the chrome updater writes it, while a session is adopted: `tmux-ide adopt --all` starts it";
251
+ "The background service writes it within a minute while it runs; without the service, `tmux-ide adopt --all` starts a writer";
249
252
  if (!snapshot) {
250
253
  return liveSessions?.length
251
254
  ? { label, pass: false, detail: `none yet. ${hint}`, optional: true }
@@ -256,6 +259,22 @@ export function snapshotRow(
256
259
  ageMs >= DAY_MS
257
260
  ? `${Math.floor(ageMs / DAY_MS)} days old`
258
261
  : `${Math.max(0, Math.round(ageMs / 60_000))} min old`;
262
+ if (
263
+ liveSessions &&
264
+ serverStartMs !== null &&
265
+ snapshotIsRestorePoint(snapshot, { serverStartMs, sessions: liveSessions })
266
+ ) {
267
+ // No writer replaces this file: it is the only record of the server that died.
268
+ const gone = snapshot.sessions
269
+ .map((session) => session.name)
270
+ .filter((name) => !liveSessions.includes(name));
271
+ return {
272
+ label,
273
+ pass: false,
274
+ detail: `restore point kept: saved ${age}, before this tmux server started; ${gone.length} of its sessions ${gone.length === 1 ? "is" : "are"} not running (${gone.slice(0, 5).join(", ")}${gone.length > 5 ? ", …" : ""}). \`tmux-ide restore\` brings them back; delete snapshot.json to let a new snapshot replace it`,
275
+ optional: true,
276
+ };
277
+ }
259
278
  const saved = new Set(snapshot.sessions.map((session) => session.name));
260
279
  const missing = (liveSessions ?? []).filter((name) => !saved.has(name));
261
280
  if (missing.length)
@@ -291,12 +310,34 @@ function safeBundledTmux(): string | null {
291
310
  }
292
311
  }
293
312
 
313
+ /** The `-S`/`-L` arguments that name the server doctor reads. */
314
+ function doctorTmuxServer(): string[] {
315
+ const socketPath = process.env[TMUX_SOCKET_PATH_ENV];
316
+ const socketName = process.env.TMUX_IDE_TMUX_SOCKET_NAME;
317
+ return socketPath ? ["-S", socketPath] : socketName ? ["-L", socketName] : [];
318
+ }
319
+
320
+ /** `#{start_time}` of the server doctor reads, or null when it cannot be asked. */
321
+ function liveServerStartMs(): number | null {
322
+ try {
323
+ const server = doctorTmuxServer();
324
+ const seconds = Number(
325
+ execFileSync(resolveTmuxExecutable(), [...server, "display-message", "-p", "#{start_time}"], {
326
+ encoding: "utf8",
327
+ stdio: ["ignore", "pipe", "pipe"],
328
+ timeout: 3000,
329
+ }).trim(),
330
+ );
331
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null;
332
+ } catch {
333
+ return null;
334
+ }
335
+ }
336
+
294
337
  /** The sessions the snapshot should hold, on the server doctor reads; null when unreadable. */
295
338
  function liveListableSessions(): string[] | null {
296
339
  try {
297
- const socketPath = process.env[TMUX_SOCKET_PATH_ENV];
298
- const socketName = process.env.TMUX_IDE_TMUX_SOCKET_NAME;
299
- const server = socketPath ? ["-S", socketPath] : socketName ? ["-L", socketName] : [];
340
+ const server = doctorTmuxServer();
300
341
  return execFileSync(
301
342
  resolveTmuxExecutable(),
302
343
  [...server, "list-sessions", "-F", "#{session_name}"],
@@ -451,7 +492,7 @@ export async function doctor({
451
492
  // The tmux version row above already reports a missing executable.
452
493
  }
453
494
  checks.push(plainTmuxRow(firstOnPath("tmux"), safeBundledTmux()));
454
- checks.push(snapshotRow(readSnapshot(), liveListableSessions(), Date.now()));
495
+ checks.push(snapshotRow(readSnapshot(), liveListableSessions(), Date.now(), liveServerStartMs()));
455
496
 
456
497
  checks.push(nodeVersionRow(process.versions.node));
457
498
 
@@ -3,6 +3,7 @@ import {
3
3
  captureUnboundTmuxSelectorProof,
4
4
  type TmuxServerProof,
5
5
  } from "./tmux-server-proof.ts";
6
+ import { invocationDirectory } from "./invocation-directory.ts";
6
7
  import {
7
8
  createPinnedWorkspaceTmuxRunner,
8
9
  resolveWorkspacePaneTmuxAuthority,
@@ -282,6 +283,22 @@ async function replaceOlderCanonicalDaemon(
282
283
  );
283
284
  }
284
285
 
286
+ const DAEMON_PROOF_PENDING = Symbol("daemon-server-proof-pending");
287
+
288
+ /**
289
+ * The daemon supports server proofs, but its identity or this side's own probe
290
+ * has no proof yet: a generation that just started on a replaced tmux server,
291
+ * or a slow tmux answer. Waiting can resolve it; an unsupported proof or a
292
+ * positive mismatch cannot.
293
+ */
294
+ export function daemonServerProofPending(error: unknown): boolean {
295
+ return (
296
+ error instanceof DaemonBootstrapError &&
297
+ (error as DaemonBootstrapError & { [DAEMON_PROOF_PENDING]?: boolean })[DAEMON_PROOF_PENDING] ===
298
+ true
299
+ );
300
+ }
301
+
285
302
  async function assertServerIntent(
286
303
  deps: CanonicalDaemonBootstrapDependencies,
287
304
  info: CanonicalDaemonInfo,
@@ -320,10 +337,17 @@ async function assertServerIntent(
320
337
  }
321
338
  }
322
339
  if (info.tmuxServerProofVersion !== 1 || !identity.tmuxServerProof || !proof)
323
- throw new DaemonBootstrapError(
324
- "incompatible",
325
- `Cannot prove the requested tmux server for this daemon. Its server identity is unavailable or unsupported; the existing daemon was left running. Proof availability: capability=${info.tmuxServerProofVersion === 1}, daemon=${Boolean(identity.tmuxServerProof)}, client=${Boolean(proof)}.`,
326
- { reason: "tmux-server-unproven" },
340
+ throw Object.assign(
341
+ new DaemonBootstrapError<CanonicalDaemonBootstrapFailure>(
342
+ "incompatible",
343
+ `Cannot prove the requested tmux server for this daemon. Its server identity is unavailable or unsupported; the existing daemon was left running. Proof availability: capability=${info.tmuxServerProofVersion === 1}, daemon=${Boolean(identity.tmuxServerProof)}, client=${Boolean(proof)}.`,
344
+ { reason: "tmux-server-unproven" },
345
+ ),
346
+ {
347
+ // Either side's proof can be late (a slow tmux answer); only a daemon
348
+ // without the capability can never prove it.
349
+ [DAEMON_PROOF_PENDING]: info.tmuxServerProofVersion === 1,
350
+ },
327
351
  );
328
352
  if (
329
353
  identity.tmuxServerProof.kind !== proof.kind ||
@@ -460,7 +484,9 @@ export function createCanonicalDaemonBootstrapCoordinator(
460
484
  ? resolveTmuxServerIntent()
461
485
  : options.tmuxServerIntent,
462
486
  ),
463
- spawn: () => deps.spawnOwner(resolve(options.entryPath), resolve(options.cwd ?? process.cwd())),
487
+ // A deleted current directory starts the daemon from home (#585).
488
+ spawn: () =>
489
+ deps.spawnOwner(resolve(options.entryPath), resolve(options.cwd ?? invocationDirectory())),
464
490
  timeoutMs: options.timeoutMs,
465
491
  onPhaseChanged: options.onPhaseChanged,
466
492
  now: deps.now,
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The crash snapshot (`snapshot.json`, read by `tmux-ide restore`) written by
3
+ * the daemon for its default tmux server.
4
+ *
5
+ * The chrome updater writes that file, but it runs only while a session is
6
+ * adopted. A server started by plain `tmux` then has no snapshot, silently
7
+ * (#783). The daemon fills the gap: it writes the same file, with the same
8
+ * builder, whenever the updater's own session is not running. One writer at a
9
+ * time, so the two never rotate each other's generation away. Neither replaces
10
+ * a restore point: the snapshot of a server that is gone and whose sessions
11
+ * have not come back (`snapshotIsRestorePoint`).
12
+ */
13
+ import { UPDATER_SESSION } from "./chrome-front-door.ts";
14
+
15
+ /** How often the daemon looks. A new server has its snapshot within a minute. */
16
+ export const DAEMON_CRASH_SNAPSHOT_INTERVAL_MS = 30_000;
17
+
18
+ /** What the rule below needs to know of a snapshot. */
19
+ export interface CrashSnapshotSummary {
20
+ readonly savedAt: string;
21
+ readonly sessions: readonly { readonly name: string }[];
22
+ }
23
+
24
+ /**
25
+ * The snapshot file and its builder. They belong to the chrome adapter
26
+ * (tui/chrome/snapshot.ts, `fleetCrashSnapshotSource`), which the engine may
27
+ * not import; the process that owns the daemon passes them in.
28
+ */
29
+ export interface CrashSnapshotSource<S extends CrashSnapshotSummary = CrashSnapshotSummary> {
30
+ readonly sessionFormat: string;
31
+ readonly paneFormat: string;
32
+ /** Build a snapshot from `list-panes -a` and `list-sessions` rows; reads the process table. */
33
+ readonly build: (panes: string[], sessions: string[]) => Promise<S>;
34
+ readonly read: () => S | null;
35
+ // Method syntax on purpose: a source of a richer snapshot type is accepted
36
+ // where the daemon options name the summary type.
37
+ write(snapshot: S): void;
38
+ fingerprint(snapshot: S): string;
39
+ }
40
+
41
+ /**
42
+ * Is `existing` a restore point: the snapshot of a tmux server that is gone,
43
+ * naming at least one session the running server lacks? That file is what
44
+ * `tmux-ide restore` rebuilds from, so no writer may replace it. It stops
45
+ * being one when its sessions run again (after a restore) or the user deletes
46
+ * the file. A server's own snapshot is never one: it was saved after the
47
+ * server started.
48
+ */
49
+ export function snapshotIsRestorePoint(
50
+ existing: CrashSnapshotSummary | null,
51
+ live: { readonly serverStartMs: number; readonly sessions: readonly string[] },
52
+ ): boolean {
53
+ if (!existing || !(live.serverStartMs > Date.parse(existing.savedAt))) return false;
54
+ const running = new Set(live.sessions);
55
+ return existing.sessions.some((session) => !running.has(session.name));
56
+ }
57
+
58
+ export interface DaemonCrashSnapshotDeps<S extends CrashSnapshotSummary = CrashSnapshotSummary> {
59
+ /** A tmux client pinned to the daemon's default server. Throws when it cannot ask. */
60
+ readonly run: (args: readonly string[]) => Promise<string>;
61
+ readonly source: CrashSnapshotSource<S>;
62
+ }
63
+
64
+ export type DaemonCrashSnapshotPulse =
65
+ | "written"
66
+ | "unchanged"
67
+ | "updater-writes"
68
+ | "restore-point-kept"
69
+ | "tmux-unavailable";
70
+
71
+ export function createDaemonCrashSnapshot<S extends CrashSnapshotSummary>(
72
+ deps: DaemonCrashSnapshotDeps<S>,
73
+ ) {
74
+ const { source } = deps;
75
+ /** The tmux answers of the last pulse that built a snapshot. */
76
+ let seen: string | null = null;
77
+ return {
78
+ async pulse(): Promise<DaemonCrashSnapshotPulse> {
79
+ let sessions: string;
80
+ let panes: string;
81
+ let existing: S | null;
82
+ let serverStartMs = Number.NaN;
83
+ try {
84
+ sessions = await deps.run(["list-sessions", "-F", source.sessionFormat]);
85
+ if (sessions.split("\n").some((line) => line.split("\t")[0] === UPDATER_SESSION)) {
86
+ // The updater owns the file now; start over from the file when it stops.
87
+ seen = null;
88
+ return "updater-writes";
89
+ }
90
+ panes = await deps.run(["list-panes", "-a", "-F", source.paneFormat]);
91
+ if (`${sessions}\n\n${panes}` === seen) return "unchanged";
92
+ existing = source.read();
93
+ if (existing)
94
+ serverStartMs =
95
+ Number((await deps.run(["display-message", "-p", "#{start_time}"])).trim()) * 1000;
96
+ } catch {
97
+ // A server that is gone or unreachable must not replace the snapshot
98
+ // that restores it.
99
+ return "tmux-unavailable";
100
+ }
101
+ const running = sessions.split("\n").map((line) => line.split("\t")[0]!);
102
+ if (snapshotIsRestorePoint(existing, { serverStartMs, sessions: running })) {
103
+ // Look again next time: a restore or a deleted file changes no tmux
104
+ // answer this pulse could remember.
105
+ seen = null;
106
+ return "restore-point-kept";
107
+ }
108
+ const snapshot = await source.build(
109
+ panes.split("\n").filter(Boolean),
110
+ sessions.split("\n").filter(Boolean),
111
+ );
112
+ seen = `${sessions}\n\n${panes}`;
113
+ if (existing && source.fingerprint(existing) === source.fingerprint(snapshot))
114
+ return "unchanged";
115
+ source.write(snapshot);
116
+ return "written";
117
+ },
118
+ };
119
+ }
120
+
121
+ /**
122
+ * What a daemon generation passes to {@link startDaemonCrashSnapshot}: its
123
+ * launcher and the source its owner injected. A pure function so a test can pin
124
+ * that the source reaches the writer without starting a daemon.
125
+ */
126
+ export function daemonCrashSnapshotStart(
127
+ opts: {
128
+ readonly launcher?: "headless" | "embedded";
129
+ readonly crashSnapshotSource?: CrashSnapshotSource;
130
+ },
131
+ run: (args: readonly string[]) => Promise<string>,
132
+ retired: () => boolean,
133
+ ): Parameters<typeof startDaemonCrashSnapshot<CrashSnapshotSummary>>[0] {
134
+ return {
135
+ launcher: opts.launcher ?? "embedded",
136
+ source: opts.crashSnapshotSource,
137
+ run,
138
+ retired,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Pulse on a timer until `retired` says the daemon generation is gone; the
144
+ * timer then clears itself, so no stop step has to know about it. Returns a
145
+ * stop function for callers that have one. Only the background service
146
+ * ("headless") writes: a daemon embedded in an app lives only as long as its
147
+ * window, and gets null. So does a daemon started without a snapshot source.
148
+ */
149
+ export function startDaemonCrashSnapshot<S extends CrashSnapshotSummary>(
150
+ deps: Omit<DaemonCrashSnapshotDeps<S>, "source"> & {
151
+ readonly source: CrashSnapshotSource<S> | undefined;
152
+ readonly launcher: "headless" | "embedded";
153
+ readonly retired: () => boolean;
154
+ },
155
+ ): (() => void) | null {
156
+ if (deps.launcher !== "headless" || !deps.source) return null;
157
+ const snapshot = createDaemonCrashSnapshot({ run: deps.run, source: deps.source });
158
+ let busy = false;
159
+ const timer = setInterval(() => {
160
+ if (deps.retired()) {
161
+ clearInterval(timer);
162
+ return;
163
+ }
164
+ if (busy) return;
165
+ busy = true;
166
+ void snapshot
167
+ .pulse()
168
+ .catch(() => undefined)
169
+ .finally(() => {
170
+ busy = false;
171
+ });
172
+ }, DAEMON_CRASH_SNAPSHOT_INTERVAL_MS);
173
+ timer.unref?.();
174
+ return () => clearInterval(timer);
175
+ }
@@ -1,5 +1,10 @@
1
1
  import { createPaneReaderResolver } from "./tmux-pane-reader.ts";
2
2
  import { createNativeBrowserResolver } from "./tmux-native-browser.ts";
3
+ import {
4
+ daemonCrashSnapshotStart,
5
+ startDaemonCrashSnapshot,
6
+ type CrashSnapshotSource,
7
+ } from "./daemon-crash-snapshot.ts";
3
8
  import { createNativeSurfaceContextResolver } from "./native-surface-context.ts";
4
9
  import { NativeSurfaceProviderRegistry } from "../terminal/graphics/native-surface-provider.ts";
5
10
  import { TmuxServerVersionSchemaZ } from "@tmux-ide/contracts";
@@ -248,6 +253,12 @@ export interface EmbeddedDaemonOptions {
248
253
  * Stamped into the daemon record for triage; defaults to "embedded".
249
254
  */
250
255
  launcher?: "headless" | "embedded";
256
+ /**
257
+ * @internal The crash snapshot's file and builder (#783). They live in the
258
+ * chrome adapter, so the process that owns a headless daemon passes them in;
259
+ * without them the daemon writes no snapshot.
260
+ */
261
+ crashSnapshotSource?: CrashSnapshotSource;
251
262
  /** @internal Successful previous generation stop in this same process. */
252
263
  predecessor?: CanonicalDaemonPredecessor;
253
264
  /** @internal Let the foreground lifecycle owner serialize settings restarts. */
@@ -1840,6 +1851,17 @@ async function startEmbeddedDaemonGeneration(
1840
1851
  // publishing this daemon generation. This neutral cleanup does not
1841
1852
  // construct PTYs, attachment leases, or admission.
1842
1853
  await terminalInventoryRuntime.whenReady();
1854
+ // The background service keeps the crash snapshot for its default server
1855
+ // when no chrome updater does (#783). An app-embedded daemon does not: it
1856
+ // lives only as long as its window. The timer ends with this generation.
1857
+ const snapshotInventory = terminalInventoryRuntime;
1858
+ startDaemonCrashSnapshot(
1859
+ daemonCrashSnapshotStart(
1860
+ opts,
1861
+ (args) => fleetFactsTmuxRunner(args),
1862
+ () => ["disposed", "failed"].includes(snapshotInventory.lifecycleState()),
1863
+ ),
1864
+ );
1843
1865
  const getTerminalAttachmentRuntime = (): NativeTerminalAttachmentRuntime => {
1844
1866
  if (terminalAttachmentRuntime) return terminalAttachmentRuntime;
1845
1867
  terminalAttachmentRuntime = createNativeTerminalAttachmentRuntime({
@@ -1,4 +1,8 @@
1
- import { assertCanonicalDaemonServerIntent } from "./canonical-daemon-bootstrap.ts";
1
+ import {
2
+ assertCanonicalDaemonServerIntent,
3
+ daemonServerProofPending,
4
+ type CanonicalDaemonBootstrapDependencies,
5
+ } from "./canonical-daemon-bootstrap.ts";
2
6
  import { resolveTmuxServerIntent } from "./runtime-namespace.ts";
3
7
  import {
4
8
  canonicalDaemonUrl,
@@ -25,10 +29,12 @@ import {
25
29
  type EmbeddedDaemonHandle,
26
30
  type EmbeddedDaemonOptions,
27
31
  } from "./daemon-embed.ts";
32
+ import { DaemonBootstrapError } from "@tmux-ide/daemon-client/bootstrap-coordinator";
28
33
  import { DaemonStartupError, IdeError } from "./errors.ts";
29
34
  import { logger, reserveStdoutForProtocol } from "./log.ts";
30
35
  import { generateAuthToken } from "./auth-token.ts";
31
36
  import type { DaemonRestartRequest } from "./daemon-restart-request.ts";
37
+ import type { CrashSnapshotSource } from "./daemon-crash-snapshot.ts";
32
38
 
33
39
  export interface HeadlessDaemonOptions {
34
40
  readonly tmuxServerIntent?: ReturnType<typeof resolveTmuxServerIntent>;
@@ -41,6 +47,8 @@ export interface HeadlessDaemonOptions {
41
47
  readonly sessionName?: string;
42
48
  /** Product version is diagnostic only; protocol compatibility is authoritative. */
43
49
  readonly expectedVersion?: string;
50
+ /** The crash snapshot's file and builder, from the chrome adapter (#783). */
51
+ readonly crashSnapshotSource?: CrashSnapshotSource;
44
52
  }
45
53
 
46
54
  export interface HeadlessDaemonDependencies {
@@ -65,6 +73,12 @@ export interface HeadlessDaemonDependencies {
65
73
  readonly signalStopDeadlineMs?: number;
66
74
  /** How long a signalled stop may take in all. Defaults to SIGNAL_STOP_MAX_MS. */
67
75
  readonly signalStopMaxMs?: number;
76
+ /** This side's proof of the requested tmux server. Defaults to the bootstrap's own tmux read. */
77
+ readonly serverProof?: CanonicalDaemonBootstrapDependencies["serverProof"];
78
+ /** How long a just-published generation may take to become attachable. Defaults to 15 s. */
79
+ readonly attachabilityTimeoutMs?: number;
80
+ /** The pause before a generation that could not prove its server is started again. */
81
+ readonly delay?: (ms: number) => Promise<void>;
68
82
  }
69
83
 
70
84
  /**
@@ -89,6 +103,8 @@ interface HeadlessLifecycle {
89
103
  generations: number;
90
104
  /** Why the next generation starts: "initial", or what retired the previous one. */
91
105
  startReason: string;
106
+ /** Consecutive restarts of a generation that could not prove its own tmux server. */
107
+ ownServerProofRestarts?: number;
92
108
  /**
93
109
  * The port the previous generation served on. A restart in place keeps it
94
110
  * when it can, so a client reconnects where it was instead of having to
@@ -205,8 +221,18 @@ async function assertAttachableDaemon(
205
221
  );
206
222
  }
207
223
  assertIdentityMatches(info, identity);
224
+ // The first read is the one just made; the proof's own retries read again,
225
+ // or they would only ever see this identity without its proof.
226
+ let first = true;
208
227
  await assertCanonicalDaemonServerIntent(info, options.tmuxServerIntent ?? null, {
209
- identity: async () => identity,
228
+ ...(deps.serverProof ? { serverProof: deps.serverProof } : {}),
229
+ identity: async () => {
230
+ if (first) {
231
+ first = false;
232
+ return identity;
233
+ }
234
+ return deps.probeCanonicalDaemonIdentity(info, undefined, true);
235
+ },
210
236
  });
211
237
  const health = await deps.probeCanonicalDaemonHealth(info);
212
238
  if (!health) {
@@ -278,13 +304,44 @@ function delay(ms: number): Promise<void> {
278
304
  return new Promise((resolve) => setTimeout(resolve, ms));
279
305
  }
280
306
 
307
+ /** How often a restarted generation that cannot prove its own tmux server is started again. */
308
+ export const OWN_SERVER_PROOF_RESTARTS = 4;
309
+
310
+ /**
311
+ * A generation this daemon just started and published could not prove its
312
+ * own tmux server in the handshake: the proof timed out on a slow tmux, or was
313
+ * read while the server was being replaced (soak o3: the first generation of a
314
+ * restarted daemon; the kill-server harness: the first generation and restarts
315
+ * in place). That is not another daemon managing another server, so the
316
+ * process must not exit at once: the generation is started again after a
317
+ * short, growing pause, a bounded number of times. A server intent that is
318
+ * really wrong still ends the process, after the last try. A proof that names
319
+ * another server (mismatch) is not retried: it ends the process at once, as
320
+ * before.
321
+ */
322
+ export function ownServerProofRetry(
323
+ error: unknown,
324
+ state: { readonly startReason: string; readonly restarts: number },
325
+ ): { delayMs: number } | null {
326
+ if (
327
+ !(error instanceof DaemonBootstrapError) ||
328
+ error.reason !== "tmux-server-unproven" ||
329
+ state.restarts >= OWN_SERVER_PROOF_RESTARTS
330
+ )
331
+ return null;
332
+ return { delayMs: 250 * (state.restarts + 1) };
333
+ }
334
+
281
335
  const DAEMON_ATTACHABILITY_TIMEOUT_MS = 15_000;
282
336
  const DAEMON_ATTACHABILITY_POLL_MS = 25;
283
337
 
284
- function isTransientAttachabilityError(error: unknown): error is IdeError {
338
+ function isTransientAttachabilityError(error: unknown): boolean {
285
339
  return (
286
- error instanceof IdeError &&
287
- (error.code === "DAEMON_IDENTITY_UNAVAILABLE" || error.code === "DAEMON_UNHEALTHY")
340
+ (error instanceof IdeError &&
341
+ (error.code === "DAEMON_IDENTITY_UNAVAILABLE" || error.code === "DAEMON_UNHEALTHY")) ||
342
+ // A generation started on a replaced tmux server proves it a moment
343
+ // later (soak o3: the daemon exited at startup instead of waiting).
344
+ daemonServerProofPending(error)
288
345
  );
289
346
  }
290
347
 
@@ -512,6 +569,9 @@ async function runHeadlessDaemonGeneration(
512
569
  handle = await deps.startEmbeddedDaemon({
513
570
  launcher: "headless",
514
571
  plugins: true,
572
+ ...(options.crashSnapshotSource
573
+ ? { crashSnapshotSource: options.crashSnapshotSource }
574
+ : {}),
515
575
  ...(options.supervisionId
516
576
  ? { supervisionId: options.supervisionId, predecessor: lifecycle.predecessor }
517
577
  : {}),
@@ -653,7 +713,7 @@ async function runHeadlessDaemonGeneration(
653
713
  deps,
654
714
  info,
655
715
  options,
656
- DAEMON_ATTACHABILITY_TIMEOUT_MS,
716
+ deps.attachabilityTimeoutMs ?? DAEMON_ATTACHABILITY_TIMEOUT_MS,
657
717
  () => signalRequested,
658
718
  );
659
719
  options.onOwnedReady?.(info);
@@ -663,8 +723,29 @@ async function runHeadlessDaemonGeneration(
663
723
  if (stopFailure) throw stopFailure;
664
724
  return "stopped";
665
725
  }
666
- throw error;
726
+ const retry = ownServerProofRetry(error, {
727
+ startReason,
728
+ restarts: lifecycle.ownServerProofRestarts ?? 0,
729
+ });
730
+ if (!retry) throw error;
731
+ lifecycle.ownServerProofRestarts = (lifecycle.ownServerProofRestarts ?? 0) + 1;
732
+ logger.warn(
733
+ "daemon-lifecycle",
734
+ "generation could not prove its own tmux server; starting it again",
735
+ {
736
+ generation,
737
+ startReason,
738
+ reason: (error as DaemonBootstrapError).reason,
739
+ restart: lifecycle.ownServerProofRestarts,
740
+ delayMs: retry.delayMs,
741
+ },
742
+ );
743
+ await (deps.delay ?? delay)(retry.delayMs);
744
+ if (signalRequested) return "stopped";
745
+ lifecycle.startReason = "tmux-server-unproven";
746
+ return "restart";
667
747
  }
748
+ lifecycle.ownServerProofRestarts = 0;
668
749
 
669
750
  lifecycle.lastPort = info.port;
670
751
  emitStatus(deps, options.json === true, "ready", info);
@@ -0,0 +1,21 @@
1
+ import { homedir } from "node:os";
2
+
3
+ /**
4
+ * The directory the user started tmux-ide from, for prompts and new sessions.
5
+ * A shell can sit in a directory that was deleted after it entered it; then
6
+ * there is no current directory and `process.cwd()` throws ENOENT (#585). The
7
+ * user's home stands in for it there. Any other failure is not hidden.
8
+ */
9
+ export function invocationDirectory(
10
+ io: { readonly cwd: () => string; readonly home: () => string } = {
11
+ cwd: () => process.cwd(),
12
+ home: homedir,
13
+ },
14
+ ): string {
15
+ try {
16
+ return io.cwd();
17
+ } catch (error) {
18
+ if ((error as NodeJS.ErrnoException | null)?.code !== "ENOENT") throw error;
19
+ return io.home();
20
+ }
21
+ }
@@ -75,8 +75,8 @@ function nonEmpty(env: NodeJS.ProcessEnv, key: string): string | undefined {
75
75
  return value ? value : undefined;
76
76
  }
77
77
 
78
- function absolutePath(value: string, cwd: string, key: string): string {
79
- const path = isAbsolute(value) ? value : resolve(cwd, value);
78
+ function absolutePath(value: string, cwd: () => string, key: string): string {
79
+ const path = isAbsolute(value) ? value : resolve(cwd(), value);
80
80
  if (!isAbsolute(path)) throw new TypeError(`${key} must resolve to an absolute path`);
81
81
  return path;
82
82
  }
@@ -138,7 +138,18 @@ export function resolveRuntimeNamespace(
138
138
  const within = (path: string, parent: string) => isInsideOrEqual(path, parent, identity);
139
139
  const env = options.env ?? process.env;
140
140
  const userHome = options.userHome ?? homedir();
141
- const cwd = options.cwd ?? process.cwd();
141
+ // Read only for a relative setting (#585): `tmux-ide app` started from a
142
+ // deleted directory has no current directory, and needs none otherwise.
143
+ const cwd = (key: string) => (): string => {
144
+ if (options.cwd !== undefined) return options.cwd;
145
+ try {
146
+ return process.cwd();
147
+ } catch (error) {
148
+ throw new TypeError(`${key} is relative and the current directory no longer exists`, {
149
+ cause: error,
150
+ });
151
+ }
152
+ };
142
153
  const mode = runtimeMode(env);
143
154
  const isolated = ISOLATED_MODES.has(mode);
144
155
  const canonicalHome = join(userHome, ".tmux-ide");
@@ -184,10 +195,14 @@ export function resolveRuntimeNamespace(
184
195
  throw new TypeError(`${mode} runtime requires an explicit ${STATE_HOME_ENV}`);
185
196
  }
186
197
 
187
- const stateHome = absolutePath(configuredHome ?? canonicalHome, cwd, STATE_HOME_ENV);
198
+ const stateHome = absolutePath(
199
+ configuredHome ?? canonicalHome,
200
+ cwd(STATE_HOME_ENV),
201
+ STATE_HOME_ENV,
202
+ );
188
203
  const registryDir = absolutePath(
189
204
  nonEmpty(env, REGISTRY_DIR_ENV) ?? stateHome,
190
- cwd,
205
+ cwd(REGISTRY_DIR_ENV),
191
206
  REGISTRY_DIR_ENV,
192
207
  );
193
208
  const daemonInfoDir = absolutePath(
@@ -196,7 +211,7 @@ export function resolveRuntimeNamespace(
196
211
  // This also keeps an explicitly empty DAEMON_INFO_DIR equivalent to
197
212
  // "unset" instead of silently escaping a caller's isolated registry.
198
213
  nonEmpty(env, DAEMON_INFO_DIR_ENV) ?? registryDir,
199
- cwd,
214
+ cwd(DAEMON_INFO_DIR_ENV),
200
215
  DAEMON_INFO_DIR_ENV,
201
216
  );
202
217
  const tmuxSocketName = nonEmpty(env, TMUX_SOCKET_NAME_ENV);
@@ -212,7 +227,10 @@ export function resolveRuntimeNamespace(
212
227
  throw new TypeError(`${TMUX_SOCKET_NAME_ENV} is invalid`);
213
228
  }
214
229
  const tmuxSocket = tmuxSocketPath
215
- ? ({ kind: "path", path: absolutePath(tmuxSocketPath, cwd, TMUX_SOCKET_PATH_ENV) } as const)
230
+ ? ({
231
+ kind: "path",
232
+ path: absolutePath(tmuxSocketPath, cwd(TMUX_SOCKET_PATH_ENV), TMUX_SOCKET_PATH_ENV),
233
+ } as const)
216
234
  : ({ kind: "name", name: tmuxSocketName ?? "default" } as const);
217
235
  if (isolated && tmuxSocket.kind === "name" && tmuxSocket.name === "default") {
218
236
  throw new TypeError(`${mode} runtime requires a non-default ${TMUX_SOCKET_NAME_ENV}`);
@@ -151,11 +151,20 @@ export function resolveOrdinaryTmuxClient(
151
151
  }
152
152
  const candidates = configured
153
153
  ? [configured]
154
- : (environment.PATH ?? "/usr/bin:/bin")
155
- .split(delimiter)
156
- .map((entry) =>
157
- resolve(cwd instanceof URL ? fileURLToPath(cwd) : (cwd ?? process.cwd()), entry, "tmux"),
158
- );
154
+ : (environment.PATH ?? "/usr/bin:/bin").split(delimiter).map((entry) => {
155
+ if (isAbsolute(entry)) return resolve(entry, "tmux");
156
+ // A relative or empty entry needs the current directory; a deleted
157
+ // one (#585) skips it instead of failing every tmux call.
158
+ try {
159
+ return resolve(
160
+ cwd instanceof URL ? fileURLToPath(cwd) : (cwd ?? process.cwd()),
161
+ entry,
162
+ "tmux",
163
+ );
164
+ } catch {
165
+ return "";
166
+ }
167
+ });
159
168
  let executable: string | undefined;
160
169
  for (const candidate of candidates) {
161
170
  try {