tmux-ide 2.9.24 → 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 (56) hide show
  1. package/bin/cli.js +1352 -350
  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/doctor.js +46 -10
  7. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  8. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  9. package/packages/daemon/dist/lib/daemon-embed.js +6 -0
  10. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  11. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  12. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  13. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  14. package/packages/daemon/dist/lib/update-check.js +18 -0
  15. package/packages/daemon/dist/lib/update-daemon-outcome.js +31 -0
  16. package/packages/daemon/dist/lib/update.js +39 -14
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  21. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  22. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  23. package/packages/daemon/dist/terminal/mirror/session-channel.js +25 -1
  24. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +741 -208
  25. package/packages/daemon/dist/terminal/session-runtime/registry.js +24 -2
  26. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +77 -2
  27. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  28. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  29. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  30. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  31. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  32. package/packages/daemon/src/command-center/discovery.ts +24 -4
  33. package/packages/daemon/src/command-center/server.ts +67 -67
  34. package/packages/daemon/src/doctor.ts +50 -9
  35. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  36. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  37. package/packages/daemon/src/lib/daemon-embed.ts +22 -0
  38. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  39. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  40. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  41. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  42. package/packages/daemon/src/lib/update-check.ts +34 -0
  43. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  44. package/packages/daemon/src/lib/update.ts +58 -16
  45. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  46. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  47. package/packages/daemon/src/terminal/mirror/session-channel.ts +30 -1
  48. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +811 -223
  49. package/packages/daemon/src/terminal/session-runtime/registry.ts +35 -2
  50. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +74 -2
  51. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  52. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  53. package/packages/daemon/src/tui/chrome/snapshot.ts +47 -1
  54. package/packages/daemon/src/tui/chrome/statusline.ts +7 -4
  55. package/packages/daemon/src/tui/chrome/updater.ts +3 -0
  56. package/packages/daemon-client/src/pane-stream-client.ts +47 -5
@@ -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 {
@@ -237,6 +237,40 @@ export function getUpdateStatus({
237
237
  return deriveStatus(cache?.latest ?? null, currentVersion);
238
238
  }
239
239
 
240
+ /** Where a status came from: the registry just now, or the last answer on disk. */
241
+ export type UpdateStatusSource = "registry" | "cache";
242
+
243
+ /**
244
+ * io — the answer for a user who asked (`tmux-ide update`): fetch the registry
245
+ * now, with a short timeout, and store what it said. The cache alone can be
246
+ * weeks old on a machine that rarely runs the updater tick. Falls back to the
247
+ * cache when the registry cannot be reached, and says so in `source`.
248
+ */
249
+ export async function refreshUpdateStatus({
250
+ currentVersion = getCurrentVersion(),
251
+ now = Date.now(),
252
+ timeoutMs = 3000,
253
+ fetchLatest = fetchLatestVersion,
254
+ }: UpdateScope & {
255
+ now?: number;
256
+ timeoutMs?: number;
257
+ fetchLatest?: typeof fetchLatestVersion;
258
+ } = {}): Promise<UpdateStatus & { source: UpdateStatusSource }> {
259
+ const fetched = await fetchLatest(timeoutMs, updateChannel(currentVersion));
260
+ const cache = readUpdateCache({ currentVersion });
261
+ if (fetched === null)
262
+ return { ...deriveStatus(cache?.latest ?? null, currentVersion), source: "cache" };
263
+ writeUpdateCache(
264
+ {
265
+ lastCheckedAt: now,
266
+ latest: fetched,
267
+ ...(cache?.notified ? { notified: cache.notified } : {}),
268
+ },
269
+ { currentVersion },
270
+ );
271
+ return { ...deriveStatus(fetched, currentVersion), source: "registry" };
272
+ }
273
+
240
274
  /**
241
275
  * io — the throttled network refresh (called fire-and-forget from the updater
242
276
  * tick). Does nothing if the last check was inside {@link CHECK_INTERVAL_MS};
@@ -0,0 +1,42 @@
1
+ import { compareProductVersions } from "./semver.ts";
2
+
3
+ /**
4
+ * What `tmux-ide update --daemon` tells the user once a daemon is running.
5
+ *
6
+ * A CLI never replaces a NEWER daemon (canonical-daemon-bootstrap's
7
+ * needsReplacement): clients of the newer version may depend on it. That is
8
+ * by design. But after a rollback (a newer daemon, an older CLI) the command
9
+ * used to report "Daemon ready" for the newer daemon and nothing else, so it
10
+ * looked as if it had done nothing. It now says the daemon was left running
11
+ * and how to run this version's daemon instead.
12
+ */
13
+ export function daemonUpdateOutcome(
14
+ running: {
15
+ readonly productVersion: string;
16
+ readonly pid: number;
17
+ readonly supervised: boolean;
18
+ /** The daemon runs inside another tmux-ide process (an app or TUI), not on its own. */
19
+ readonly embedded?: boolean;
20
+ },
21
+ cliVersion: string,
22
+ ): { status: "ready" | "kept-newer"; message: string } {
23
+ if (compareProductVersions(running.productVersion, cliVersion) !== 1)
24
+ return { status: "ready", message: `Daemon ready: ${running.productVersion}` };
25
+ // A service restart runs the launcher the service was set up with, which need
26
+ // not be this CLI's installation: say what it does, not which version it loads.
27
+ const how = running.supervised
28
+ ? "restart its service with tmux-ide daemon service restart; the service starts " +
29
+ `the installation it was set up with, so if that is not v${cliVersion}, set the ` +
30
+ "service up from this installation first"
31
+ : running.embedded
32
+ ? `quit what it runs in: it runs inside another tmux-ide process (pid ${running.pid}), ` +
33
+ "such as an open app, then run tmux-ide update --daemon again"
34
+ : `stop it (pid ${running.pid}), then run tmux-ide update --daemon again`;
35
+ return {
36
+ status: "kept-newer",
37
+ message:
38
+ `The running daemon is v${running.productVersion}, newer than this CLI (v${cliVersion}). ` +
39
+ `It was left running: a CLI never replaces a newer daemon. ` +
40
+ `To run v${cliVersion}'s daemon instead, ${how}.`,
41
+ };
42
+ }
@@ -11,11 +11,15 @@ import { dirname, join } from "node:path";
11
11
  import { execFileSync } from "node:child_process";
12
12
  import {
13
13
  getCurrentVersion,
14
- getUpdateStatus,
14
+ refreshUpdateStatus,
15
15
  deriveStatus,
16
16
  updateChannel,
17
+ type fetchLatestVersion,
17
18
  type UpdateChannel,
19
+ type UpdateStatus,
20
+ type UpdateStatusSource,
18
21
  } from "./update-check.ts";
22
+ import { IdeError } from "./errors.ts";
19
23
  import {
20
24
  installOrigin,
21
25
  detectPackageManager,
@@ -99,14 +103,22 @@ export function planUpdate(input: {
99
103
  }
100
104
  export function renderPlan(
101
105
  plan: UpdatePlan,
102
- { current, latest, dryRun }: { current: string; latest: string | null; dryRun: boolean },
106
+ {
107
+ current,
108
+ latest,
109
+ dryRun,
110
+ source = "registry",
111
+ }: { current: string; latest: string | null; dryRun: boolean; source?: UpdateStatusSource },
103
112
  ): string {
113
+ // "Up to date" is the registry's word only; a cached answer can be weeks old.
104
114
  const status =
105
115
  latest && deriveStatus(latest, current).updateAvailable
106
116
  ? `tmux-ide v${current} → v${latest} available`
107
- : latest
108
- ? `tmux-ide v${current} is up to date (registry: v${latest})`
109
- : `tmux-ide v${current} (latest version unknown)`;
117
+ : source === "cache"
118
+ ? `tmux-ide v${current}: could not reach the npm registry (last known release: ${latest ? `v${latest}` : "unknown"})`
119
+ : latest
120
+ ? `tmux-ide v${current} is up to date (registry: v${latest})`
121
+ : `tmux-ide v${current} (latest version unknown)`;
110
122
  return [
111
123
  status,
112
124
  "",
@@ -118,21 +130,43 @@ export function renderPlan(
118
130
  "After updating, relaunch the app. Use tmux-ide update --daemon to replace a running daemon with installed code.",
119
131
  ].join("\n");
120
132
  }
133
+ /** The update command prints its own failure; ours is one line, never a stack trace. */
134
+ function updateFailure(what: string, error: unknown): IdeError {
135
+ const { status, signal, message } = error as { status?: unknown; signal?: unknown } & Error;
136
+ const how =
137
+ typeof status === "number"
138
+ ? `exited with status ${status}`
139
+ : typeof signal === "string"
140
+ ? `was stopped by ${signal}`
141
+ : `could not run (${String(message).split("\n")[0]})`;
142
+ return new IdeError(
143
+ `The update did not finish: ${what} ${how}. Its own message is above. Retry with: tmux-ide update`,
144
+ { code: "UPDATE_FAILED", cause: error instanceof Error ? error : undefined },
145
+ );
146
+ }
121
147
  /** Does not refresh skills: the installed package's postinstall owns that step. */
122
- export function runUpdate(
148
+ export async function runUpdate(
123
149
  { cliDir, dryRun, json = false }: { cliDir: string; dryRun: boolean; json?: boolean },
124
150
  dependencies: {
125
151
  execute?: typeof execFileSync;
126
152
  query?: (executable: string, args: string[]) => string;
127
153
  currentVersion?: () => string;
128
- status?: typeof getUpdateStatus;
154
+ status?: (scope: {
155
+ currentVersion: string;
156
+ }) =>
157
+ | (UpdateStatus & { source?: UpdateStatusSource })
158
+ | Promise<UpdateStatus & { source?: UpdateStatusSource }>;
159
+ fetchLatest?: typeof fetchLatestVersion;
129
160
  output?: (line: string) => void;
130
161
  } = {},
131
- ): UpdatePlan {
162
+ ): Promise<UpdatePlan> {
132
163
  if (resolveRuntimeNamespace().development)
133
164
  throw new Error("Development instances rebuild exact artifacts; package updates are disabled");
134
165
  const current = (dependencies.currentVersion ?? getCurrentVersion)();
135
- const { latest } = (dependencies.status ?? getUpdateStatus)({ currentVersion: current });
166
+ const { latest, source: latestSource = "registry" } = await (
167
+ dependencies.status ??
168
+ ((scope) => refreshUpdateStatus({ ...scope, fetchLatest: dependencies.fetchLatest }))
169
+ )({ currentVersion: current });
136
170
  const source = installOrigin(cliDir);
137
171
  let plan: UpdatePlan =
138
172
  source.origin === "unknown"
@@ -178,19 +212,27 @@ export function runUpdate(
178
212
  }
179
213
  }
180
214
  const output = dependencies.output ?? console.log;
181
- if (!json) output(renderPlan(plan, { current, latest, dryRun }));
215
+ if (!json) output(renderPlan(plan, { current, latest, dryRun, source: latestSource }));
182
216
  let executed = false;
183
217
  if (!dryRun && plan.executable && plan.args) {
184
- // argv only: paths and version metadata never become shell source.
185
- (dependencies.execute ?? execFileSync)(plan.executable, plan.args, {
186
- stdio: json ? ["ignore", 2, 2] : "inherit",
187
- });
218
+ try {
219
+ // argv only: paths and version metadata never become shell source.
220
+ (dependencies.execute ?? execFileSync)(plan.executable, plan.args, {
221
+ stdio: json ? ["ignore", 2, 2] : "inherit",
222
+ });
223
+ } catch (error) {
224
+ throw updateFailure([plan.executable, ...plan.args].join(" "), error);
225
+ }
188
226
  executed = true;
189
227
  }
190
228
  if (!dryRun && plan.installerPrefix && plan.channel) {
191
- runManagedInstallerUpdate(plan.installerPrefix, plan.channel, json, dependencies.execute);
229
+ try {
230
+ runManagedInstallerUpdate(plan.installerPrefix, plan.channel, json, dependencies.execute);
231
+ } catch (error) {
232
+ throw updateFailure("the installer", error);
233
+ }
192
234
  executed = true;
193
235
  }
194
- if (json) output(JSON.stringify({ ...plan, current, latest, dryRun, executed }));
236
+ if (json) output(JSON.stringify({ ...plan, current, latest, latestSource, dryRun, executed }));
195
237
  return plan;
196
238
  }
@@ -367,18 +367,30 @@ export class KittyImageStore {
367
367
  null;
368
368
  #nextAnonymous = 0x7f000000;
369
369
  #bytes = 0;
370
- readonly #cellWidth: number;
371
- readonly #cellHeight: number;
370
+ /** Cell size in thousandths of a device pixel. */
371
+ #cellWidth: number;
372
+ #cellHeight: number;
372
373
  readonly #budget: KittyImageBudget;
373
374
  #revision = 0;
374
375
 
375
376
  constructor(options: KittyImageStoreOptions = {}) {
376
- this.#cellWidth = options.cellWidthPx ?? 10;
377
- this.#cellHeight = options.cellHeightPx ?? 20;
377
+ this.#cellWidth = (options.cellWidthPx ?? 10) * 1000;
378
+ this.#cellHeight = (options.cellHeightPx ?? 20) * 1000;
378
379
  this.#budget = options.budget ?? DEFAULT_KITTY_IMAGE_BUDGET;
379
380
  this.#budget.register(this);
380
381
  }
381
382
 
383
+ /**
384
+ * The renderer's cell size in device pixels, with thousandths when it reports
385
+ * them (capability 103/104). Placements made from now on that give no `c`/`r`
386
+ * cover the image at this size; earlier ones keep their grid.
387
+ */
388
+ setCellPixels(width: number, height: number, precise?: { width: number; height: number }): void {
389
+ if (!(width > 0 && height > 0)) return;
390
+ this.#cellWidth = precise && precise.width > 0 ? precise.width : width * 1000;
391
+ this.#cellHeight = precise && precise.height > 0 ? precise.height : height * 1000;
392
+ }
393
+
382
394
  /** Bumps whenever images or placements change. */
383
395
  get revision(): number {
384
396
  return this.#revision;
@@ -511,8 +523,12 @@ export class KittyImageStore {
511
523
  const image = this.#images.get(imageId);
512
524
  if (!image) return;
513
525
  this.#used.set(imageId, this.#budget.nextTick());
514
- const columns = clampCells(int(control, "c") || Math.ceil(image.width / this.#cellWidth));
515
- const rows = clampCells(int(control, "r") || Math.ceil(image.height / this.#cellHeight));
526
+ const columns = clampCells(
527
+ int(control, "c") || Math.ceil((image.width * 1000) / this.#cellWidth),
528
+ );
529
+ const rows = clampCells(
530
+ int(control, "r") || Math.ceil((image.height * 1000) / this.#cellHeight),
531
+ );
516
532
  const placementId = int(control, "p");
517
533
  if (control.get("U") === "1") {
518
534
  const placements = this.#virtual.get(imageId) ?? new Map();
@@ -214,6 +214,28 @@ export class MirrorService {
214
214
  wasPending: this.registeredWindows?.pending() ?? null,
215
215
  });
216
216
  this.registeredWindows?.invalidate();
217
+ this.scheduleOwnershipVerify();
218
+ }
219
+
220
+ /**
221
+ * Until a read proves ownership again, every retained session refuses input
222
+ * and geometry. A workspace added or removed (another session created or
223
+ * killed) invalidates without any channel resyncing, and nothing else read
224
+ * again until the next stream was issued: the next keystroke closed the
225
+ * stream. Read again at once (coalesced) while a channel is retained; a
226
+ * failed read takes the #764 retry path.
227
+ */
228
+ private ownershipVerifyScheduled = false;
229
+ private scheduleOwnershipVerify(): void {
230
+ if (this.ownershipVerifyScheduled || this.disposed) return;
231
+ this.ownershipVerifyScheduled = true;
232
+ const timer = setTimeout(() => {
233
+ this.ownershipVerifyScheduled = false;
234
+ if (this.disposed || this.channelSessions.size === 0 || !this.registeredWindows?.pending())
235
+ return;
236
+ void this.verifyRegisteredWindows().catch(() => {});
237
+ }, 0);
238
+ timer.unref?.();
217
239
  }
218
240
 
219
241
  /**
@@ -633,6 +655,11 @@ export class MirrorService {
633
655
  if (message) throw new Error(message);
634
656
  }
635
657
 
658
+ /** Registered-window ownership is being read again; input waits for it. */
659
+ windowOwnershipPending(): boolean {
660
+ return this.registeredWindows?.pending() ?? false;
661
+ }
662
+
636
663
  windowOwnershipMessage(session: string): string | null {
637
664
  if (this.registeredWindows?.pending())
638
665
  return "Window ownership is being verified. Retry after session discovery completes.";