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,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";
@@ -139,6 +144,7 @@ import { FleetLifecycleAuthority } from "./fleet-lifecycle-authority.ts";
139
144
  import { AppWindowMutationAuthority } from "./app-window-mutation.ts";
140
145
  import { WorkspaceMultiplexerAuthority } from "./workspace-multiplexer-verbs.ts";
141
146
  import { TmuxExternalInteractionObserver } from "./tmux-external-interaction-observer.ts";
147
+ import { createOrphanedControlClientWatch } from "./orphaned-control-clients.ts";
142
148
  import {
143
149
  createTmuxInteractionObservationHandler,
144
150
  externalTmuxInteractionDraft,
@@ -247,6 +253,12 @@ export interface EmbeddedDaemonOptions {
247
253
  * Stamped into the daemon record for triage; defaults to "embedded".
248
254
  */
249
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;
250
262
  /** @internal Successful previous generation stop in this same process. */
251
263
  predecessor?: CanonicalDaemonPredecessor;
252
264
  /** @internal Let the foreground lifecycle owner serialize settings restarts. */
@@ -1233,6 +1245,13 @@ async function startEmbeddedDaemonGeneration(
1233
1245
  const fleetFactsTmuxRunner = initialNativeServerIdentity
1234
1246
  ? createServerGenerationFencedTmuxAsyncRunner(tmuxAuthority, initialNativeServerIdentity)
1235
1247
  : createPinnedWorkspaceTmuxAsyncRunner(tmuxAuthority);
1248
+ // The daemon's own server: a predecessor killed without a stop may have
1249
+ // left control clients attached to it.
1250
+ const defaultServerOrphanWatch = createOrphanedControlClientWatch({
1251
+ selector: tmuxAuthority.socketSelector,
1252
+ serverId: null,
1253
+ });
1254
+ void defaultServerOrphanWatch.onOwnership();
1236
1255
  const tmuxAuthorityReplaced = createTmuxAuthorityReplacementProbe(
1237
1256
  tmuxAuthority,
1238
1257
  catalogTmuxRunner,
@@ -1832,6 +1851,17 @@ async function startEmbeddedDaemonGeneration(
1832
1851
  // publishing this daemon generation. This neutral cleanup does not
1833
1852
  // construct PTYs, attachment leases, or admission.
1834
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
+ );
1835
1865
  const getTerminalAttachmentRuntime = (): NativeTerminalAttachmentRuntime => {
1836
1866
  if (terminalAttachmentRuntime) return terminalAttachmentRuntime;
1837
1867
  terminalAttachmentRuntime = createNativeTerminalAttachmentRuntime({
@@ -2004,7 +2034,12 @@ async function startEmbeddedDaemonGeneration(
2004
2034
  resolveNativeSurfaceContext: createNativeSurfaceContextResolver({
2005
2035
  generation: instanceId,
2006
2036
  registry: workspaceRegistry,
2007
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
2037
+ catalog: createNativeTmuxServerCatalog(
2038
+ workspaceRegistry,
2039
+ fleetFactsTmuxRunner,
2040
+ undefined,
2041
+ defaultServerOrphanWatch.onTrouble,
2042
+ ),
2008
2043
  inventory: terminalInventoryRuntime,
2009
2044
  run: (args, signal) => fleetFactsTmuxRunner(args, signal),
2010
2045
  assertOpen: () => {
@@ -2020,7 +2055,12 @@ async function startEmbeddedDaemonGeneration(
2020
2055
  resolvePaneEditorContext: createPaneEditorContextResolver({
2021
2056
  generation: instanceId,
2022
2057
  registry: workspaceRegistry,
2023
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
2058
+ catalog: createNativeTmuxServerCatalog(
2059
+ workspaceRegistry,
2060
+ fleetFactsTmuxRunner,
2061
+ undefined,
2062
+ defaultServerOrphanWatch.onTrouble,
2063
+ ),
2024
2064
  inventory: terminalInventoryRuntime,
2025
2065
  assertOpen: () => {
2026
2066
  if (
@@ -2036,7 +2076,12 @@ async function startEmbeddedDaemonGeneration(
2036
2076
  generation: instanceId,
2037
2077
  run: fleetFactsTmuxRunner,
2038
2078
  registry: workspaceRegistry,
2039
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
2079
+ catalog: createNativeTmuxServerCatalog(
2080
+ workspaceRegistry,
2081
+ fleetFactsTmuxRunner,
2082
+ undefined,
2083
+ defaultServerOrphanWatch.onTrouble,
2084
+ ),
2040
2085
  inventory: terminalInventoryRuntime,
2041
2086
  assertOpen: () => {
2042
2087
  if (
@@ -2052,7 +2097,12 @@ async function startEmbeddedDaemonGeneration(
2052
2097
  generation: instanceId,
2053
2098
  run: fleetFactsTmuxRunner,
2054
2099
  registry: workspaceRegistry,
2055
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
2100
+ catalog: createNativeTmuxServerCatalog(
2101
+ workspaceRegistry,
2102
+ fleetFactsTmuxRunner,
2103
+ undefined,
2104
+ defaultServerOrphanWatch.onTrouble,
2105
+ ),
2056
2106
  inventory: terminalInventoryRuntime,
2057
2107
  assertOpen: () => {
2058
2108
  if (
@@ -2064,12 +2114,19 @@ async function startEmbeddedDaemonGeneration(
2064
2114
  throw new Error("Default reader owner is unavailable");
2065
2115
  },
2066
2116
  }),
2067
- catalog: createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner),
2117
+ catalog: createNativeTmuxServerCatalog(
2118
+ workspaceRegistry,
2119
+ fleetFactsTmuxRunner,
2120
+ undefined,
2121
+ defaultServerOrphanWatch.onTrouble,
2122
+ ),
2068
2123
  readWindowSplitLayout: async (workspaceName, input) => {
2069
2124
  const target = WindowLinkTargetSchemaZ.parse(input);
2070
2125
  const sessions = await createNativeTmuxServerCatalog(
2071
2126
  workspaceRegistry,
2072
2127
  fleetFactsTmuxRunner,
2128
+ undefined,
2129
+ defaultServerOrphanWatch.onTrouble,
2073
2130
  )();
2074
2131
  const sessionName = workspaceRegistry.get(workspaceName)?.sessionName;
2075
2132
  if (
@@ -2085,7 +2142,12 @@ async function startEmbeddedDaemonGeneration(
2085
2142
  },
2086
2143
  openAgent: async (liveSessionId, observed) => {
2087
2144
  const target = observedAgentSchema.parse(observed);
2088
- await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner)();
2145
+ await createNativeTmuxServerCatalog(
2146
+ workspaceRegistry,
2147
+ fleetFactsTmuxRunner,
2148
+ undefined,
2149
+ defaultServerOrphanWatch.onTrouble,
2150
+ )();
2089
2151
  try {
2090
2152
  return await defaultSessionOpener.openAgent(liveSessionId, target);
2091
2153
  } finally {
@@ -2093,7 +2155,12 @@ async function startEmbeddedDaemonGeneration(
2093
2155
  }
2094
2156
  },
2095
2157
  openSession: async (liveSessionId) => {
2096
- await createNativeTmuxServerCatalog(workspaceRegistry, fleetFactsTmuxRunner)();
2158
+ await createNativeTmuxServerCatalog(
2159
+ workspaceRegistry,
2160
+ fleetFactsTmuxRunner,
2161
+ undefined,
2162
+ defaultServerOrphanWatch.onTrouble,
2163
+ )();
2097
2164
  const result = await defaultSessionOpener.openSession(liveSessionId);
2098
2165
  terminalInventoryRuntime!.invalidate();
2099
2166
  return result;
@@ -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);
@@ -375,3 +375,56 @@ export function createHomeAgentObserver(deps: HomeAgentDependencies): HomeAgentO
375
375
  },
376
376
  };
377
377
  }
378
+
379
+ /**
380
+ * A roster answers "is this row current" with no while it re-reads the row's
381
+ * session, and it re-reads whenever an agent appears or changes: the moment a
382
+ * row gets clicked. This waits for that re-read to finish instead of taking
383
+ * the no for an answer.
384
+ */
385
+ export const ROSTER_SETTLE_MS = 3_000;
386
+
387
+ /**
388
+ * Resolves true as soon as the target is current, false as soon as the roster
389
+ * is not re-reading and the target still is not current, and whatever holds at
390
+ * the bound or when `signal` aborts (aborted: false).
391
+ */
392
+ export function waitForRosterTarget(options: {
393
+ readonly isCurrent: () => boolean;
394
+ readonly refreshing: () => boolean;
395
+ /** Called on every roster publication; may deliver one synchronously. */
396
+ readonly subscribe: (listener: () => void) => () => void;
397
+ readonly signal: AbortSignal;
398
+ readonly boundMs?: number;
399
+ }): Promise<boolean> {
400
+ if (options.signal.aborted) return Promise.resolve(false);
401
+ if (options.isCurrent()) return Promise.resolve(true);
402
+ if (!options.refreshing()) return Promise.resolve(false);
403
+ return new Promise((resolve) => {
404
+ let settled = false;
405
+ let stop: (() => void) | null = null;
406
+ const finish = (value: boolean): void => {
407
+ if (settled) return;
408
+ settled = true;
409
+ clearTimeout(timer);
410
+ options.signal.removeEventListener("abort", abort);
411
+ stop?.();
412
+ resolve(value);
413
+ };
414
+ const abort = (): void => finish(false);
415
+ const check = (): void => {
416
+ if (settled) return;
417
+ if (options.isCurrent()) finish(true);
418
+ else if (!options.refreshing()) finish(false);
419
+ };
420
+ const timer = setTimeout(
421
+ () => finish(options.isCurrent()),
422
+ options.boundMs ?? ROSTER_SETTLE_MS,
423
+ );
424
+ (timer as { unref?: () => void }).unref?.();
425
+ options.signal.addEventListener("abort", abort, { once: true });
426
+ const unsubscribe = options.subscribe(check);
427
+ if (settled) unsubscribe();
428
+ else stop = unsubscribe;
429
+ });
430
+ }
@@ -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
+ }
@@ -5,7 +5,11 @@ import {
5
5
  type MachineConnectionManager,
6
6
  } from "./machine-connection-manager.ts";
7
7
  import type { MachineCatalogSnapshot } from "./machine-catalog.ts";
8
- import { createHomeAgentObserver, type HomeAgentObserver } from "./home-agent-observer.ts";
8
+ import {
9
+ createHomeAgentObserver,
10
+ waitForRosterTarget,
11
+ type HomeAgentObserver,
12
+ } from "./home-agent-observer.ts";
9
13
  import { createHomeAgentTransport } from "./home-agent-transport.ts";
10
14
  import type { HomeAgentRow, HomeAgentSnapshot } from "@tmux-ide/presentation/home-agent-roster";
11
15
 
@@ -185,6 +189,26 @@ export function createMachineAgents(options: {
185
189
  !!entry.observer?.isCurrentTarget(row)
186
190
  );
187
191
  },
192
+ /** The machine's roster is re-reading a session right now. */
193
+ isRefreshing(machineId: string): boolean {
194
+ const observed = entries.get(machineId)?.observer?.getSnapshot();
195
+ return (
196
+ !!observed && (observed.refreshingSessionKeys.length > 0 || observed.loadingSessions > 0)
197
+ );
198
+ },
199
+ /**
200
+ * `isCurrentTarget` once the machine's roster has finished re-reading:
201
+ * a row is not current during the read, and a click should wait for it.
202
+ */
203
+ whenCurrentTarget(machineId: string, row: HomeAgentRow, signal: AbortSignal): Promise<boolean> {
204
+ return waitForRosterTarget({
205
+ isCurrent: () => this.isCurrentTarget(machineId, row),
206
+ refreshing: () => this.isRefreshing(machineId),
207
+ subscribe: (listener) =>
208
+ entries.get(machineId)?.observer?.subscribe(() => listener()) ?? (() => undefined),
209
+ signal,
210
+ });
211
+ },
188
212
  retry() {
189
213
  for (const entry of entries.values()) entry.observer?.retry();
190
214
  },