tmux-ide 2.9.23 → 2.9.25

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 (83) hide show
  1. package/bin/cli.js +1636 -385
  2. package/package.json +4 -2
  3. package/packages/contracts/src/pane-stream.ts +53 -0
  4. package/packages/daemon/dist/command-center/discovery.js +24 -5
  5. package/packages/daemon/dist/command-center/server.js +81 -75
  6. package/packages/daemon/dist/command-center/tmux-servers.js +11 -0
  7. package/packages/daemon/dist/doctor.js +46 -10
  8. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  9. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  10. package/packages/daemon/dist/lib/daemon-embed.js +22 -8
  11. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  12. package/packages/daemon/dist/lib/home-agent-observer.js +50 -0
  13. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  14. package/packages/daemon/dist/lib/machine-agents.js +18 -1
  15. package/packages/daemon/dist/lib/orphaned-control-clients.js +162 -0
  16. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  17. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  18. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +32 -9
  19. package/packages/daemon/dist/lib/tmux-server-owner.js +26 -4
  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/lib/workspace-promotion.js +24 -3
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  27. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  28. package/packages/daemon/dist/terminal/attachments/native-runtime.js +17 -2
  29. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  30. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  31. package/packages/daemon/dist/terminal/mirror/session-channel.js +27 -2
  32. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +749 -208
  33. package/packages/daemon/dist/terminal/session-runtime/registry.js +24 -2
  34. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +77 -2
  35. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  36. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  37. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  38. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  39. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  40. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +57 -4
  41. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +18 -7
  42. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +17 -0
  43. package/packages/daemon/dist/tui/mirror/runtime/application-machine-navigation.js +4 -2
  44. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +55 -14
  45. package/packages/daemon/src/command-center/discovery.ts +24 -4
  46. package/packages/daemon/src/command-center/server.ts +67 -67
  47. package/packages/daemon/src/command-center/tmux-servers.ts +11 -0
  48. package/packages/daemon/src/doctor.ts +50 -9
  49. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  50. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  51. package/packages/daemon/src/lib/daemon-embed.ts +74 -7
  52. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  53. package/packages/daemon/src/lib/home-agent-observer.ts +53 -0
  54. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  55. package/packages/daemon/src/lib/machine-agents.ts +25 -1
  56. package/packages/daemon/src/lib/orphaned-control-clients.ts +215 -0
  57. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  58. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  59. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +32 -8
  60. package/packages/daemon/src/lib/tmux-server-owner.ts +28 -3
  61. package/packages/daemon/src/lib/update-check.ts +34 -0
  62. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  63. package/packages/daemon/src/lib/update.ts +58 -16
  64. package/packages/daemon/src/lib/workspace-promotion.ts +26 -3
  65. package/packages/daemon/src/terminal/attachments/native-runtime.ts +21 -2
  66. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  67. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  68. package/packages/daemon/src/terminal/mirror/session-channel.ts +32 -2
  69. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +819 -223
  70. package/packages/daemon/src/terminal/session-runtime/registry.ts +35 -2
  71. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +74 -2
  72. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  73. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  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/src/tui/mirror/runtime/application-home-agent-navigation.ts +69 -4
  78. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +30 -13
  79. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +38 -1
  80. package/packages/daemon/src/tui/mirror/runtime/application-machine-navigation.ts +7 -2
  81. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +4 -4
  82. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +71 -17
  83. package/packages/daemon-client/src/pane-stream-client.ts +47 -5
@@ -0,0 +1,118 @@
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.js";
14
+ /** How often the daemon looks. A new server has its snapshot within a minute. */
15
+ export const DAEMON_CRASH_SNAPSHOT_INTERVAL_MS = 30_000;
16
+ /**
17
+ * Is `existing` a restore point: the snapshot of a tmux server that is gone,
18
+ * naming at least one session the running server lacks? That file is what
19
+ * `tmux-ide restore` rebuilds from, so no writer may replace it. It stops
20
+ * being one when its sessions run again (after a restore) or the user deletes
21
+ * the file. A server's own snapshot is never one: it was saved after the
22
+ * server started.
23
+ */
24
+ export function snapshotIsRestorePoint(existing, live) {
25
+ if (!existing || !(live.serverStartMs > Date.parse(existing.savedAt)))
26
+ return false;
27
+ const running = new Set(live.sessions);
28
+ return existing.sessions.some((session) => !running.has(session.name));
29
+ }
30
+ export function createDaemonCrashSnapshot(deps) {
31
+ const { source } = deps;
32
+ /** The tmux answers of the last pulse that built a snapshot. */
33
+ let seen = null;
34
+ return {
35
+ async pulse() {
36
+ let sessions;
37
+ let panes;
38
+ let existing;
39
+ let serverStartMs = Number.NaN;
40
+ try {
41
+ sessions = await deps.run(["list-sessions", "-F", source.sessionFormat]);
42
+ if (sessions.split("\n").some((line) => line.split("\t")[0] === UPDATER_SESSION)) {
43
+ // The updater owns the file now; start over from the file when it stops.
44
+ seen = null;
45
+ return "updater-writes";
46
+ }
47
+ panes = await deps.run(["list-panes", "-a", "-F", source.paneFormat]);
48
+ if (`${sessions}\n\n${panes}` === seen)
49
+ return "unchanged";
50
+ existing = source.read();
51
+ if (existing)
52
+ serverStartMs =
53
+ Number((await deps.run(["display-message", "-p", "#{start_time}"])).trim()) * 1000;
54
+ }
55
+ catch {
56
+ // A server that is gone or unreachable must not replace the snapshot
57
+ // that restores it.
58
+ return "tmux-unavailable";
59
+ }
60
+ const running = sessions.split("\n").map((line) => line.split("\t")[0]);
61
+ if (snapshotIsRestorePoint(existing, { serverStartMs, sessions: running })) {
62
+ // Look again next time: a restore or a deleted file changes no tmux
63
+ // answer this pulse could remember.
64
+ seen = null;
65
+ return "restore-point-kept";
66
+ }
67
+ const snapshot = await source.build(panes.split("\n").filter(Boolean), sessions.split("\n").filter(Boolean));
68
+ seen = `${sessions}\n\n${panes}`;
69
+ if (existing && source.fingerprint(existing) === source.fingerprint(snapshot))
70
+ return "unchanged";
71
+ source.write(snapshot);
72
+ return "written";
73
+ },
74
+ };
75
+ }
76
+ /**
77
+ * What a daemon generation passes to {@link startDaemonCrashSnapshot}: its
78
+ * launcher and the source its owner injected. A pure function so a test can pin
79
+ * that the source reaches the writer without starting a daemon.
80
+ */
81
+ export function daemonCrashSnapshotStart(opts, run, retired) {
82
+ return {
83
+ launcher: opts.launcher ?? "embedded",
84
+ source: opts.crashSnapshotSource,
85
+ run,
86
+ retired,
87
+ };
88
+ }
89
+ /**
90
+ * Pulse on a timer until `retired` says the daemon generation is gone; the
91
+ * timer then clears itself, so no stop step has to know about it. Returns a
92
+ * stop function for callers that have one. Only the background service
93
+ * ("headless") writes: a daemon embedded in an app lives only as long as its
94
+ * window, and gets null. So does a daemon started without a snapshot source.
95
+ */
96
+ export function startDaemonCrashSnapshot(deps) {
97
+ if (deps.launcher !== "headless" || !deps.source)
98
+ return null;
99
+ const snapshot = createDaemonCrashSnapshot({ run: deps.run, source: deps.source });
100
+ let busy = false;
101
+ const timer = setInterval(() => {
102
+ if (deps.retired()) {
103
+ clearInterval(timer);
104
+ return;
105
+ }
106
+ if (busy)
107
+ return;
108
+ busy = true;
109
+ void snapshot
110
+ .pulse()
111
+ .catch(() => undefined)
112
+ .finally(() => {
113
+ busy = false;
114
+ });
115
+ }, DAEMON_CRASH_SNAPSHOT_INTERVAL_MS);
116
+ timer.unref?.();
117
+ return () => clearInterval(timer);
118
+ }
@@ -8,6 +8,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
8
8
  };
9
9
  import { createPaneReaderResolver } from "./tmux-pane-reader.js";
10
10
  import { createNativeBrowserResolver } from "./tmux-native-browser.js";
11
+ import { daemonCrashSnapshotStart, startDaemonCrashSnapshot, } from "./daemon-crash-snapshot.js";
11
12
  import { createNativeSurfaceContextResolver } from "./native-surface-context.js";
12
13
  import { NativeSurfaceProviderRegistry } from "../terminal/graphics/native-surface-provider.js";
13
14
  import { TmuxServerVersionSchemaZ } from "@tmux-ide/contracts";
@@ -79,6 +80,7 @@ import { FleetLifecycleAuthority } from "./fleet-lifecycle-authority.js";
79
80
  import { AppWindowMutationAuthority } from "./app-window-mutation.js";
80
81
  import { WorkspaceMultiplexerAuthority } from "./workspace-multiplexer-verbs.js";
81
82
  import { TmuxExternalInteractionObserver } from "./tmux-external-interaction-observer.js";
83
+ import { createOrphanedControlClientWatch } from "./orphaned-control-clients.js";
82
84
  import { createTmuxInteractionObservationHandler, externalTmuxInteractionDraft, } from "./tmux-interaction-observation-handler.js";
83
85
  import { InteractionReceiptJournal } from "./interaction-receipt-journal.js";
84
86
  import { InteractionObservationStatusStore } from "./interaction-observation-status.js";
@@ -764,6 +766,13 @@ async function startEmbeddedDaemonGeneration(opts) {
764
766
  const fleetFactsTmuxRunner = initialNativeServerIdentity
765
767
  ? createServerGenerationFencedTmuxAsyncRunner(tmuxAuthority, initialNativeServerIdentity)
766
768
  : createPinnedWorkspaceTmuxAsyncRunner(tmuxAuthority);
769
+ // The daemon's own server: a predecessor killed without a stop may have
770
+ // left control clients attached to it.
771
+ const defaultServerOrphanWatch = createOrphanedControlClientWatch({
772
+ selector: tmuxAuthority.socketSelector,
773
+ serverId: null,
774
+ });
775
+ void defaultServerOrphanWatch.onOwnership();
767
776
  const tmuxAuthorityReplaced = createTmuxAuthorityReplacementProbe(tmuxAuthority, catalogTmuxRunner);
768
777
  const registryTmuxRunner = createPinnedWorkspaceTmuxRunner(tmuxAuthority, {
769
778
  timeoutMs: WORKSPACE_REGISTRY_TMUX_TIMEOUT_MS,
@@ -1266,6 +1275,11 @@ async function startEmbeddedDaemonGeneration(opts) {
1266
1275
  // publishing this daemon generation. This neutral cleanup does not
1267
1276
  // construct PTYs, attachment leases, or admission.
1268
1277
  await terminalInventoryRuntime.whenReady();
1278
+ // The background service keeps the crash snapshot for its default server
1279
+ // when no chrome updater does (#783). An app-embedded daemon does not: it
1280
+ // lives only as long as its window. The timer ends with this generation.
1281
+ const snapshotInventory = terminalInventoryRuntime;
1282
+ startDaemonCrashSnapshot(daemonCrashSnapshotStart(opts, (args) => fleetFactsTmuxRunner(args), () => ["disposed", "failed"].includes(snapshotInventory.lifecycleState())));
1269
1283
  const getTerminalAttachmentRuntime = () => {
1270
1284
  if (terminalAttachmentRuntime)
1271
1285
  return terminalAttachmentRuntime;
@@ -1422,7 +1436,7 @@ async function startEmbeddedDaemonGeneration(opts) {
1422
1436
  resolveNativeSurfaceContext: createNativeSurfaceContextResolver({
1423
1437
  generation: instanceId,
1424
1438
  registry: workspaceRegistry,
1425
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
1439
+ catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble),
1426
1440
  inventory: terminalInventoryRuntime,
1427
1441
  run: (args, signal) => fleetFactsTmuxRunner(args, signal),
1428
1442
  assertOpen: () => {
@@ -1436,7 +1450,7 @@ async function startEmbeddedDaemonGeneration(opts) {
1436
1450
  resolvePaneEditorContext: createPaneEditorContextResolver({
1437
1451
  generation: instanceId,
1438
1452
  registry: workspaceRegistry,
1439
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
1453
+ catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble),
1440
1454
  inventory: terminalInventoryRuntime,
1441
1455
  assertOpen: () => {
1442
1456
  if (defaultEditorContextRetired ||
@@ -1450,7 +1464,7 @@ async function startEmbeddedDaemonGeneration(opts) {
1450
1464
  generation: instanceId,
1451
1465
  run: fleetFactsTmuxRunner,
1452
1466
  registry: workspaceRegistry,
1453
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
1467
+ catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble),
1454
1468
  inventory: terminalInventoryRuntime,
1455
1469
  assertOpen: () => {
1456
1470
  if (defaultEditorContextRetired ||
@@ -1464,7 +1478,7 @@ async function startEmbeddedDaemonGeneration(opts) {
1464
1478
  generation: instanceId,
1465
1479
  run: fleetFactsTmuxRunner,
1466
1480
  registry: workspaceRegistry,
1467
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
1481
+ catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble),
1468
1482
  inventory: terminalInventoryRuntime,
1469
1483
  assertOpen: () => {
1470
1484
  if (defaultEditorContextRetired ||
@@ -1474,10 +1488,10 @@ async function startEmbeddedDaemonGeneration(opts) {
1474
1488
  throw new Error("Default reader owner is unavailable");
1475
1489
  },
1476
1490
  }),
1477
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
1491
+ catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble),
1478
1492
  readWindowSplitLayout: async (workspaceName, input) => {
1479
1493
  const target = WindowLinkTargetSchemaZ.parse(input);
1480
- const sessions = await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner)();
1494
+ const sessions = await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble)();
1481
1495
  const sessionName = workspaceRegistry.get(workspaceName)?.sessionName;
1482
1496
  if (!sessionName ||
1483
1497
  !sessions.some((row) => row.sessionName === sessionName && row.liveSessionId === target.liveSessionId))
@@ -1488,7 +1502,7 @@ async function startEmbeddedDaemonGeneration(opts) {
1488
1502
  },
1489
1503
  openAgent: async (liveSessionId, observed) => {
1490
1504
  const target = observedAgentSchema.parse(observed);
1491
- await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner)();
1505
+ await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble)();
1492
1506
  try {
1493
1507
  return await defaultSessionOpener.openAgent(liveSessionId, target);
1494
1508
  }
@@ -1497,7 +1511,7 @@ async function startEmbeddedDaemonGeneration(opts) {
1497
1511
  }
1498
1512
  },
1499
1513
  openSession: async (liveSessionId) => {
1500
- await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner)();
1514
+ await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner, undefined, defaultServerOrphanWatch.onTrouble)();
1501
1515
  const result = await defaultSessionOpener.openSession(liveSessionId);
1502
1516
  terminalInventoryRuntime.invalidate();
1503
1517
  return result;
@@ -1,8 +1,9 @@
1
- import { assertCanonicalDaemonServerIntent } from "./canonical-daemon-bootstrap.js";
1
+ import { assertCanonicalDaemonServerIntent, daemonServerProofPending, } from "./canonical-daemon-bootstrap.js";
2
2
  import { resolveTmuxServerIntent } from "./runtime-namespace.js";
3
3
  import { canonicalDaemonUrl, matchesCanonicalDaemonPredecessor, getCanonicalDaemonInfoPath, prepareCanonicalDaemonInfoForBootstrap, isCanonicalDaemonAlive, isCanonicalDaemonRecordOwnerProvenDead, probeCanonicalDaemonHealth, probeCanonicalDaemonIdentity, warnOnDaemonVersionSkew, } from "./canonical-daemon.js";
4
4
  import { DAEMON_WIRE_PROTOCOL_VERSION, isDaemonWireProtocolCompatible, } from "@tmux-ide/contracts";
5
5
  import { startEmbeddedDaemon, } from "./daemon-embed.js";
6
+ import { DaemonBootstrapError } from "@tmux-ide/daemon-client/bootstrap-coordinator";
6
7
  import { DaemonStartupError, IdeError } from "./errors.js";
7
8
  import { logger, reserveStdoutForProtocol } from "./log.js";
8
9
  import { generateAuthToken } from "./auth-token.js";
@@ -98,8 +99,18 @@ async function assertAttachableDaemon(deps, info, options) {
98
99
  "Refusing takeover.", { code: "DAEMON_IDENTITY_UNAVAILABLE", exitCode: 1 });
99
100
  }
100
101
  assertIdentityMatches(info, identity);
102
+ // The first read is the one just made; the proof's own retries read again,
103
+ // or they would only ever see this identity without its proof.
104
+ let first = true;
101
105
  await assertCanonicalDaemonServerIntent(info, options.tmuxServerIntent ?? null, {
102
- identity: async () => identity,
106
+ ...(deps.serverProof ? { serverProof: deps.serverProof } : {}),
107
+ identity: async () => {
108
+ if (first) {
109
+ first = false;
110
+ return identity;
111
+ }
112
+ return deps.probeCanonicalDaemonIdentity(info, undefined, true);
113
+ },
103
114
  });
104
115
  const health = await deps.probeCanonicalDaemonHealth(info);
105
116
  if (!health) {
@@ -155,11 +166,35 @@ async function findLiveCanonicalDaemon(deps, options, predecessor) {
155
166
  function delay(ms) {
156
167
  return new Promise((resolve) => setTimeout(resolve, ms));
157
168
  }
169
+ /** How often a restarted generation that cannot prove its own tmux server is started again. */
170
+ export const OWN_SERVER_PROOF_RESTARTS = 4;
171
+ /**
172
+ * A generation this daemon just started and published could not prove its
173
+ * own tmux server in the handshake: the proof timed out on a slow tmux, or was
174
+ * read while the server was being replaced (soak o3: the first generation of a
175
+ * restarted daemon; the kill-server harness: the first generation and restarts
176
+ * in place). That is not another daemon managing another server, so the
177
+ * process must not exit at once: the generation is started again after a
178
+ * short, growing pause, a bounded number of times. A server intent that is
179
+ * really wrong still ends the process, after the last try. A proof that names
180
+ * another server (mismatch) is not retried: it ends the process at once, as
181
+ * before.
182
+ */
183
+ export function ownServerProofRetry(error, state) {
184
+ if (!(error instanceof DaemonBootstrapError) ||
185
+ error.reason !== "tmux-server-unproven" ||
186
+ state.restarts >= OWN_SERVER_PROOF_RESTARTS)
187
+ return null;
188
+ return { delayMs: 250 * (state.restarts + 1) };
189
+ }
158
190
  const DAEMON_ATTACHABILITY_TIMEOUT_MS = 15_000;
159
191
  const DAEMON_ATTACHABILITY_POLL_MS = 25;
160
192
  function isTransientAttachabilityError(error) {
161
- return (error instanceof IdeError &&
162
- (error.code === "DAEMON_IDENTITY_UNAVAILABLE" || error.code === "DAEMON_UNHEALTHY"));
193
+ return ((error instanceof IdeError &&
194
+ (error.code === "DAEMON_IDENTITY_UNAVAILABLE" || error.code === "DAEMON_UNHEALTHY")) ||
195
+ // A generation started on a replaced tmux server proves it a moment
196
+ // later (soak o3: the daemon exited at startup instead of waiting).
197
+ daemonServerProofPending(error));
163
198
  }
164
199
  async function waitForAttachableDaemon(deps, info, options, timeoutMs = DAEMON_ATTACHABILITY_TIMEOUT_MS, shouldAbort = () => false) {
165
200
  const deadline = Date.now() + timeoutMs;
@@ -365,6 +400,9 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
365
400
  handle = await deps.startEmbeddedDaemon({
366
401
  launcher: "headless",
367
402
  plugins: true,
403
+ ...(options.crashSnapshotSource
404
+ ? { crashSnapshotSource: options.crashSnapshotSource }
405
+ : {}),
368
406
  ...(options.supervisionId
369
407
  ? { supervisionId: options.supervisionId, predecessor: lifecycle.predecessor }
370
408
  : {}),
@@ -495,7 +533,7 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
495
533
  // Publication precedes the external handshake. Under CPU or module-load
496
534
  // contention, one 750ms loopback probe is not a sound reason for the
497
535
  // elected owner to tear itself down and trigger generation churn.
498
- await waitForAttachableDaemon(deps, info, options, DAEMON_ATTACHABILITY_TIMEOUT_MS, () => signalRequested);
536
+ await waitForAttachableDaemon(deps, info, options, deps.attachabilityTimeoutMs ?? DAEMON_ATTACHABILITY_TIMEOUT_MS, () => signalRequested);
499
537
  options.onOwnedReady?.(info);
500
538
  }
501
539
  catch (error) {
@@ -505,8 +543,27 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
505
543
  throw stopFailure;
506
544
  return "stopped";
507
545
  }
508
- throw error;
546
+ const retry = ownServerProofRetry(error, {
547
+ startReason,
548
+ restarts: lifecycle.ownServerProofRestarts ?? 0,
549
+ });
550
+ if (!retry)
551
+ throw error;
552
+ lifecycle.ownServerProofRestarts = (lifecycle.ownServerProofRestarts ?? 0) + 1;
553
+ logger.warn("daemon-lifecycle", "generation could not prove its own tmux server; starting it again", {
554
+ generation,
555
+ startReason,
556
+ reason: error.reason,
557
+ restart: lifecycle.ownServerProofRestarts,
558
+ delayMs: retry.delayMs,
559
+ });
560
+ await (deps.delay ?? delay)(retry.delayMs);
561
+ if (signalRequested)
562
+ return "stopped";
563
+ lifecycle.startReason = "tmux-server-unproven";
564
+ return "restart";
509
565
  }
566
+ lifecycle.ownServerProofRestarts = 0;
510
567
  lifecycle.lastPort = info.port;
511
568
  emitStatus(deps, options.json === true, "ready", info);
512
569
  // The first generation already says so with its status line on stdout.
@@ -319,3 +319,53 @@ export function createHomeAgentObserver(deps) {
319
319
  },
320
320
  };
321
321
  }
322
+ /**
323
+ * A roster answers "is this row current" with no while it re-reads the row's
324
+ * session, and it re-reads whenever an agent appears or changes: the moment a
325
+ * row gets clicked. This waits for that re-read to finish instead of taking
326
+ * the no for an answer.
327
+ */
328
+ export const ROSTER_SETTLE_MS = 3_000;
329
+ /**
330
+ * Resolves true as soon as the target is current, false as soon as the roster
331
+ * is not re-reading and the target still is not current, and whatever holds at
332
+ * the bound or when `signal` aborts (aborted: false).
333
+ */
334
+ export function waitForRosterTarget(options) {
335
+ if (options.signal.aborted)
336
+ return Promise.resolve(false);
337
+ if (options.isCurrent())
338
+ return Promise.resolve(true);
339
+ if (!options.refreshing())
340
+ return Promise.resolve(false);
341
+ return new Promise((resolve) => {
342
+ let settled = false;
343
+ let stop = null;
344
+ const finish = (value) => {
345
+ if (settled)
346
+ return;
347
+ settled = true;
348
+ clearTimeout(timer);
349
+ options.signal.removeEventListener("abort", abort);
350
+ stop?.();
351
+ resolve(value);
352
+ };
353
+ const abort = () => finish(false);
354
+ const check = () => {
355
+ if (settled)
356
+ return;
357
+ if (options.isCurrent())
358
+ finish(true);
359
+ else if (!options.refreshing())
360
+ finish(false);
361
+ };
362
+ const timer = setTimeout(() => finish(options.isCurrent()), options.boundMs ?? ROSTER_SETTLE_MS);
363
+ timer.unref?.();
364
+ options.signal.addEventListener("abort", abort, { once: true });
365
+ const unsubscribe = options.subscribe(check);
366
+ if (settled)
367
+ unsubscribe();
368
+ else
369
+ stop = unsubscribe;
370
+ });
371
+ }
@@ -0,0 +1,20 @@
1
+ import { homedir } from "node:os";
2
+ /**
3
+ * The directory the user started tmux-ide from, for prompts and new sessions.
4
+ * A shell can sit in a directory that was deleted after it entered it; then
5
+ * there is no current directory and `process.cwd()` throws ENOENT (#585). The
6
+ * user's home stands in for it there. Any other failure is not hidden.
7
+ */
8
+ export function invocationDirectory(io = {
9
+ cwd: () => process.cwd(),
10
+ home: homedir,
11
+ }) {
12
+ try {
13
+ return io.cwd();
14
+ }
15
+ catch (error) {
16
+ if (error?.code !== "ENOENT")
17
+ throw error;
18
+ return io.home();
19
+ }
20
+ }
@@ -1,6 +1,6 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import { machineResourceKey } from "@tmux-ide/core";
3
- import { createHomeAgentObserver } from "./home-agent-observer.js";
3
+ import { createHomeAgentObserver, waitForRosterTarget, } from "./home-agent-observer.js";
4
4
  import { createHomeAgentTransport } from "./home-agent-transport.js";
5
5
  function bindingFor(handle) {
6
6
  const daemon = handle.read();
@@ -145,6 +145,23 @@ export function createMachineAgents(options) {
145
145
  entry.binding === bindingFor(entry.handle) &&
146
146
  !!entry.observer?.isCurrentTarget(row));
147
147
  },
148
+ /** The machine's roster is re-reading a session right now. */
149
+ isRefreshing(machineId) {
150
+ const observed = entries.get(machineId)?.observer?.getSnapshot();
151
+ return (!!observed && (observed.refreshingSessionKeys.length > 0 || observed.loadingSessions > 0));
152
+ },
153
+ /**
154
+ * `isCurrentTarget` once the machine's roster has finished re-reading:
155
+ * a row is not current during the read, and a click should wait for it.
156
+ */
157
+ whenCurrentTarget(machineId, row, signal) {
158
+ return waitForRosterTarget({
159
+ isCurrent: () => this.isCurrentTarget(machineId, row),
160
+ refreshing: () => this.isRefreshing(machineId),
161
+ subscribe: (listener) => entries.get(machineId)?.observer?.subscribe(() => listener()) ?? (() => undefined),
162
+ signal,
163
+ });
164
+ },
148
165
  retry() {
149
166
  for (const entry of entries.values())
150
167
  entry.observer?.retry();
@@ -0,0 +1,162 @@
1
+ import { execFile } from "node:child_process";
2
+ import { logger } from "./log.js";
3
+ export const ORPHAN_KILL_GRACE_MS = 500;
4
+ /** PURE. `ps -o pid=,ppid=,command=` output, one process per line. */
5
+ export function parseProcessTable(text) {
6
+ const rows = [];
7
+ for (const line of text.split("\n")) {
8
+ const match = /^\s*([0-9]+)\s+([0-9]+)\s+(.+)$/u.exec(line);
9
+ if (match)
10
+ rows.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] });
11
+ }
12
+ return rows;
13
+ }
14
+ /** The attach flags only this daemon's control client uses (mirrorControlAttachArgs). */
15
+ export function isTmuxIdeControlClientCommand(command) {
16
+ return (/(?:^|\s)-C(?:\s|$)/u.test(command) &&
17
+ /ignore-size,pause-after=[0-9]+,active-pane/u.test(command));
18
+ }
19
+ const withoutPrivate = (path) => path.replace(/^\/private(?=\/)/u, "");
20
+ /** PURE. Does this tmux command line address the given server? */
21
+ export function commandTargetsServer(command, selector) {
22
+ const words = command.split(/\s+/u);
23
+ for (let index = 0; index < words.length; index += 1) {
24
+ const word = words[index];
25
+ if (word === "-C")
26
+ return false;
27
+ const flag = selector.kind === "path" ? "-S" : "-L";
28
+ const value = word === flag ? words[index + 1] : word.startsWith(flag) ? word.slice(2) : null;
29
+ if (value === null || value === undefined || value === "")
30
+ continue;
31
+ return selector.kind === "path"
32
+ ? withoutPrivate(value) === withoutPrivate(selector.path)
33
+ : value === selector.name;
34
+ }
35
+ return false;
36
+ }
37
+ /** init, or a service manager that adopts orphans in its place. */
38
+ function adoptsOrphans(pid, command) {
39
+ if (pid === 1)
40
+ return true;
41
+ // The command's own name (its first word, with or without a path), never a
42
+ // word further on: a daemon run as `… --supervised launchd-user` is no manager.
43
+ return command !== null && /^(?:\S*\/)?(?:systemd|launchd|init)(?:\s|$)/u.test(command);
44
+ }
45
+ /**
46
+ * Ends tmux-ide control clients of this server whose daemon is gone. Never
47
+ * this daemon's own clients, another live daemon's, another server's, or any
48
+ * other program's. Returns the pids it ended. Failures end the pass; they
49
+ * never throw.
50
+ */
51
+ export async function evictOrphanedControlClients(io, ownPid, selector) {
52
+ let processes;
53
+ try {
54
+ processes = await io.listProcesses();
55
+ }
56
+ catch {
57
+ return [];
58
+ }
59
+ const byPid = new Map(processes.map((row) => [row.pid, row]));
60
+ const evicted = [];
61
+ for (const client of processes) {
62
+ if (client.pid <= 1 ||
63
+ client.pid === ownPid ||
64
+ client.ppid === ownPid ||
65
+ !isTmuxIdeControlClientCommand(client.command) ||
66
+ !commandTargetsServer(client.command, selector) ||
67
+ !adoptsOrphans(client.ppid, byPid.get(client.ppid)?.command ?? null))
68
+ continue;
69
+ try {
70
+ io.kill(client.pid, "SIGTERM");
71
+ await io.delay(ORPHAN_KILL_GRACE_MS);
72
+ if (io.isAlive(client.pid))
73
+ io.kill(client.pid, "SIGKILL");
74
+ evicted.push(client.pid);
75
+ }
76
+ catch {
77
+ // One client that cannot be signalled does not stop the pass.
78
+ }
79
+ }
80
+ return evicted;
81
+ }
82
+ /** The real process table and signals. */
83
+ export function orphanedControlClientIo() {
84
+ return {
85
+ listProcesses: () => new Promise((resolve, reject) => {
86
+ execFile("/bin/ps", ["-xww", "-o", "pid=,ppid=,command="], {
87
+ encoding: "utf8",
88
+ timeout: 3_000,
89
+ maxBuffer: 16 * 1024 * 1024,
90
+ env: { LC_ALL: "C", PATH: "/usr/bin:/bin" },
91
+ }, (error, stdout) => (error ? reject(error) : resolve(parseProcessTable(stdout))));
92
+ }),
93
+ kill: (pid, signal) => {
94
+ process.kill(pid, signal);
95
+ },
96
+ isAlive: (pid) => {
97
+ try {
98
+ process.kill(pid, 0);
99
+ return true;
100
+ }
101
+ catch (error) {
102
+ return error.code === "EPERM";
103
+ }
104
+ },
105
+ delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
106
+ };
107
+ }
108
+ export const EMPTY_SERVER_PASS_INTERVAL_MS = 10_000;
109
+ export const EMPTY_SERVER_LOG_INTERVAL_MS = 60_000;
110
+ /**
111
+ * One per owned server. Neither call is awaited by the owner, delays it or
112
+ * fails it.
113
+ * - `onOwnership`: one pass when the daemon takes the server.
114
+ * - `onTrouble`: a catalog read found the server with no sessions, or got no
115
+ * answer from a server whose socket is still there. A tmux server normally
116
+ * exits with its last session, so either it is configured to stay or it
117
+ * cannot exit. At most one pass per 10 s, and one warning per minute that
118
+ * names the state: scoped reads fail in it, and nothing else says why.
119
+ */
120
+ export function createOrphanedControlClientWatch(options) {
121
+ const io = options.io ?? orphanedControlClientIo();
122
+ const now = options.now ?? Date.now;
123
+ const fields = options.serverId ? { serverId: options.serverId } : {};
124
+ let lastPassAt = Number.NEGATIVE_INFINITY;
125
+ let lastLogAt = Number.NEGATIVE_INFINITY;
126
+ let running = null;
127
+ const pass = () => {
128
+ if (running)
129
+ return running;
130
+ lastPassAt = now();
131
+ const current = evictOrphanedControlClients(io, process.pid, options.selector)
132
+ .catch(() => [])
133
+ .then((pids) => {
134
+ if (pids.length > 0)
135
+ logger.warn("tmux-server-owners", "ended control clients a dead daemon left attached", {
136
+ ...fields,
137
+ pids,
138
+ });
139
+ return pids;
140
+ })
141
+ .finally(() => {
142
+ if (running === current)
143
+ running = null;
144
+ });
145
+ running = current;
146
+ return current;
147
+ };
148
+ return {
149
+ onOwnership: () => pass().then(() => undefined),
150
+ async onTrouble(kind) {
151
+ if (now() - lastPassAt < EMPTY_SERVER_PASS_INTERVAL_MS)
152
+ return;
153
+ const pids = await pass();
154
+ if (now() - lastLogAt < EMPTY_SERVER_LOG_INTERVAL_MS)
155
+ return;
156
+ lastLogAt = now();
157
+ logger.warn("tmux-server-owners", kind === "no-sessions"
158
+ ? "tmux server answers with no sessions"
159
+ : "tmux server does not answer its catalog", { ...fields, endedControlClients: pids.length });
160
+ },
161
+ };
162
+ }