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
@@ -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";
@@ -1274,6 +1275,11 @@ async function startEmbeddedDaemonGeneration(opts) {
1274
1275
  // publishing this daemon generation. This neutral cleanup does not
1275
1276
  // construct PTYs, attachment leases, or admission.
1276
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())));
1277
1283
  const getTerminalAttachmentRuntime = () => {
1278
1284
  if (terminalAttachmentRuntime)
1279
1285
  return terminalAttachmentRuntime;
@@ -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.
@@ -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
+ }
@@ -32,7 +32,7 @@ function nonEmpty(env, key) {
32
32
  return value ? value : undefined;
33
33
  }
34
34
  function absolutePath(value, cwd, key) {
35
- const path = isAbsolute(value) ? value : resolve(cwd, value);
35
+ const path = isAbsolute(value) ? value : resolve(cwd(), value);
36
36
  if (!isAbsolute(path))
37
37
  throw new TypeError(`${key} must resolve to an absolute path`);
38
38
  return path;
@@ -92,7 +92,20 @@ export function resolveRuntimeNamespace(options = {}) {
92
92
  const within = (path, parent) => isInsideOrEqual(path, parent, identity);
93
93
  const env = options.env ?? process.env;
94
94
  const userHome = options.userHome ?? homedir();
95
- const cwd = options.cwd ?? process.cwd();
95
+ // Read only for a relative setting (#585): `tmux-ide app` started from a
96
+ // deleted directory has no current directory, and needs none otherwise.
97
+ const cwd = (key) => () => {
98
+ if (options.cwd !== undefined)
99
+ return options.cwd;
100
+ try {
101
+ return process.cwd();
102
+ }
103
+ catch (error) {
104
+ throw new TypeError(`${key} is relative and the current directory no longer exists`, {
105
+ cause: error,
106
+ });
107
+ }
108
+ };
96
109
  const mode = runtimeMode(env);
97
110
  const isolated = ISOLATED_MODES.has(mode);
98
111
  const canonicalHome = join(userHome, ".tmux-ide");
@@ -131,14 +144,14 @@ export function resolveRuntimeNamespace(options = {}) {
131
144
  if (isolated && !configuredHome) {
132
145
  throw new TypeError(`${mode} runtime requires an explicit ${STATE_HOME_ENV}`);
133
146
  }
134
- const stateHome = absolutePath(configuredHome ?? canonicalHome, cwd, STATE_HOME_ENV);
135
- const registryDir = absolutePath(nonEmpty(env, REGISTRY_DIR_ENV) ?? stateHome, cwd, REGISTRY_DIR_ENV);
147
+ const stateHome = absolutePath(configuredHome ?? canonicalHome, cwd(STATE_HOME_ENV), STATE_HOME_ENV);
148
+ const registryDir = absolutePath(nonEmpty(env, REGISTRY_DIR_ENV) ?? stateHome, cwd(REGISTRY_DIR_ENV), REGISTRY_DIR_ENV);
136
149
  const daemonInfoDir = absolutePath(
137
150
  // Preserve the long-standing registry override as the compatibility
138
151
  // authority for daemon publication when no dedicated directory is set.
139
152
  // This also keeps an explicitly empty DAEMON_INFO_DIR equivalent to
140
153
  // "unset" instead of silently escaping a caller's isolated registry.
141
- nonEmpty(env, DAEMON_INFO_DIR_ENV) ?? registryDir, cwd, DAEMON_INFO_DIR_ENV);
154
+ nonEmpty(env, DAEMON_INFO_DIR_ENV) ?? registryDir, cwd(DAEMON_INFO_DIR_ENV), DAEMON_INFO_DIR_ENV);
142
155
  const tmuxSocketName = nonEmpty(env, TMUX_SOCKET_NAME_ENV);
143
156
  const tmuxSocketPath = nonEmpty(env, TMUX_SOCKET_PATH_ENV);
144
157
  const cleanupToken = nonEmpty(env, CLEANUP_TOKEN_ENV) ?? null;
@@ -149,7 +162,10 @@ export function resolveRuntimeNamespace(options = {}) {
149
162
  throw new TypeError(`${TMUX_SOCKET_NAME_ENV} is invalid`);
150
163
  }
151
164
  const tmuxSocket = tmuxSocketPath
152
- ? { kind: "path", path: absolutePath(tmuxSocketPath, cwd, TMUX_SOCKET_PATH_ENV) }
165
+ ? {
166
+ kind: "path",
167
+ path: absolutePath(tmuxSocketPath, cwd(TMUX_SOCKET_PATH_ENV), TMUX_SOCKET_PATH_ENV),
168
+ }
153
169
  : { kind: "name", name: tmuxSocketName ?? "default" };
154
170
  if (isolated && tmuxSocket.kind === "name" && tmuxSocket.name === "default") {
155
171
  throw new TypeError(`${mode} runtime requires a non-default ${TMUX_SOCKET_NAME_ENV}`);
@@ -133,9 +133,18 @@ export function resolveOrdinaryTmuxClient(environment, cwd, options = {}) {
133
133
  }
134
134
  const candidates = configured
135
135
  ? [configured]
136
- : (environment.PATH ?? "/usr/bin:/bin")
137
- .split(delimiter)
138
- .map((entry) => resolve(cwd instanceof URL ? fileURLToPath(cwd) : (cwd ?? process.cwd()), entry, "tmux"));
136
+ : (environment.PATH ?? "/usr/bin:/bin").split(delimiter).map((entry) => {
137
+ if (isAbsolute(entry))
138
+ return resolve(entry, "tmux");
139
+ // A relative or empty entry needs the current directory; a deleted
140
+ // one (#585) skips it instead of failing every tmux call.
141
+ try {
142
+ return resolve(cwd instanceof URL ? fileURLToPath(cwd) : (cwd ?? process.cwd()), entry, "tmux");
143
+ }
144
+ catch {
145
+ return "";
146
+ }
147
+ });
139
148
  let executable;
140
149
  for (const candidate of candidates) {
141
150
  try {
@@ -186,6 +186,24 @@ export function getUpdateStatus({ currentVersion = getCurrentVersion(), } = {})
186
186
  const cache = readUpdateCache({ currentVersion });
187
187
  return deriveStatus(cache?.latest ?? null, currentVersion);
188
188
  }
189
+ /**
190
+ * io — the answer for a user who asked (`tmux-ide update`): fetch the registry
191
+ * now, with a short timeout, and store what it said. The cache alone can be
192
+ * weeks old on a machine that rarely runs the updater tick. Falls back to the
193
+ * cache when the registry cannot be reached, and says so in `source`.
194
+ */
195
+ export async function refreshUpdateStatus({ currentVersion = getCurrentVersion(), now = Date.now(), timeoutMs = 3000, fetchLatest = fetchLatestVersion, } = {}) {
196
+ const fetched = await fetchLatest(timeoutMs, updateChannel(currentVersion));
197
+ const cache = readUpdateCache({ currentVersion });
198
+ if (fetched === null)
199
+ return { ...deriveStatus(cache?.latest ?? null, currentVersion), source: "cache" };
200
+ writeUpdateCache({
201
+ lastCheckedAt: now,
202
+ latest: fetched,
203
+ ...(cache?.notified ? { notified: cache.notified } : {}),
204
+ }, { currentVersion });
205
+ return { ...deriveStatus(fetched, currentVersion), source: "registry" };
206
+ }
189
207
  /**
190
208
  * io — the throttled network refresh (called fire-and-forget from the updater
191
209
  * tick). Does nothing if the last check was inside {@link CHECK_INTERVAL_MS};
@@ -0,0 +1,31 @@
1
+ import { compareProductVersions } from "./semver.js";
2
+ /**
3
+ * What `tmux-ide update --daemon` tells the user once a daemon is running.
4
+ *
5
+ * A CLI never replaces a NEWER daemon (canonical-daemon-bootstrap's
6
+ * needsReplacement): clients of the newer version may depend on it. That is
7
+ * by design. But after a rollback (a newer daemon, an older CLI) the command
8
+ * used to report "Daemon ready" for the newer daemon and nothing else, so it
9
+ * looked as if it had done nothing. It now says the daemon was left running
10
+ * and how to run this version's daemon instead.
11
+ */
12
+ export function daemonUpdateOutcome(running, cliVersion) {
13
+ if (compareProductVersions(running.productVersion, cliVersion) !== 1)
14
+ return { status: "ready", message: `Daemon ready: ${running.productVersion}` };
15
+ // A service restart runs the launcher the service was set up with, which need
16
+ // not be this CLI's installation: say what it does, not which version it loads.
17
+ const how = running.supervised
18
+ ? "restart its service with tmux-ide daemon service restart; the service starts " +
19
+ `the installation it was set up with, so if that is not v${cliVersion}, set the ` +
20
+ "service up from this installation first"
21
+ : running.embedded
22
+ ? `quit what it runs in: it runs inside another tmux-ide process (pid ${running.pid}), ` +
23
+ "such as an open app, then run tmux-ide update --daemon again"
24
+ : `stop it (pid ${running.pid}), then run tmux-ide update --daemon again`;
25
+ return {
26
+ status: "kept-newer",
27
+ message: `The running daemon is v${running.productVersion}, newer than this CLI (v${cliVersion}). ` +
28
+ `It was left running: a CLI never replaces a newer daemon. ` +
29
+ `To run v${cliVersion}'s daemon instead, ${how}.`,
30
+ };
31
+ }
@@ -5,7 +5,8 @@ import { parseStrictSemver } from "./semver.js";
5
5
  import { realpathSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import { getCurrentVersion, getUpdateStatus, deriveStatus, updateChannel, } from "./update-check.js";
8
+ import { getCurrentVersion, refreshUpdateStatus, deriveStatus, updateChannel, } from "./update-check.js";
9
+ import { IdeError } from "./errors.js";
9
10
  import { installOrigin, detectPackageManager, findGitCheckoutRoot, } from "./install-origin.js";
10
11
  export { detectPackageManager, findGitCheckoutRoot };
11
12
  export const UPDATE_COMMANDS = {
@@ -64,12 +65,15 @@ export function planUpdate(input) {
64
65
  guidance: guidance[method],
65
66
  };
66
67
  }
67
- export function renderPlan(plan, { current, latest, dryRun }) {
68
+ export function renderPlan(plan, { current, latest, dryRun, source = "registry", }) {
69
+ // "Up to date" is the registry's word only; a cached answer can be weeks old.
68
70
  const status = latest && deriveStatus(latest, current).updateAvailable
69
71
  ? `tmux-ide v${current} → v${latest} available`
70
- : latest
71
- ? `tmux-ide v${current} is up to date (registry: v${latest})`
72
- : `tmux-ide v${current} (latest version unknown)`;
72
+ : source === "cache"
73
+ ? `tmux-ide v${current}: could not reach the npm registry (last known release: ${latest ? `v${latest}` : "unknown"})`
74
+ : latest
75
+ ? `tmux-ide v${current} is up to date (registry: v${latest})`
76
+ : `tmux-ide v${current} (latest version unknown)`;
73
77
  return [
74
78
  status,
75
79
  "",
@@ -81,12 +85,23 @@ export function renderPlan(plan, { current, latest, dryRun }) {
81
85
  "After updating, relaunch the app. Use tmux-ide update --daemon to replace a running daemon with installed code.",
82
86
  ].join("\n");
83
87
  }
88
+ /** The update command prints its own failure; ours is one line, never a stack trace. */
89
+ function updateFailure(what, error) {
90
+ const { status, signal, message } = error;
91
+ const how = typeof status === "number"
92
+ ? `exited with status ${status}`
93
+ : typeof signal === "string"
94
+ ? `was stopped by ${signal}`
95
+ : `could not run (${String(message).split("\n")[0]})`;
96
+ return new IdeError(`The update did not finish: ${what} ${how}. Its own message is above. Retry with: tmux-ide update`, { code: "UPDATE_FAILED", cause: error instanceof Error ? error : undefined });
97
+ }
84
98
  /** Does not refresh skills: the installed package's postinstall owns that step. */
85
- export function runUpdate({ cliDir, dryRun, json = false }, dependencies = {}) {
99
+ export async function runUpdate({ cliDir, dryRun, json = false }, dependencies = {}) {
86
100
  if (resolveRuntimeNamespace().development)
87
101
  throw new Error("Development instances rebuild exact artifacts; package updates are disabled");
88
102
  const current = (dependencies.currentVersion ?? getCurrentVersion)();
89
- const { latest } = (dependencies.status ?? getUpdateStatus)({ currentVersion: current });
103
+ const { latest, source: latestSource = "registry" } = await (dependencies.status ??
104
+ ((scope) => refreshUpdateStatus({ ...scope, fetchLatest: dependencies.fetchLatest })))({ currentVersion: current });
90
105
  const source = installOrigin(cliDir);
91
106
  let plan = source.origin === "unknown"
92
107
  ? {
@@ -128,20 +143,30 @@ export function runUpdate({ cliDir, dryRun, json = false }, dependencies = {}) {
128
143
  }
129
144
  const output = dependencies.output ?? console.log;
130
145
  if (!json)
131
- output(renderPlan(plan, { current, latest, dryRun }));
146
+ output(renderPlan(plan, { current, latest, dryRun, source: latestSource }));
132
147
  let executed = false;
133
148
  if (!dryRun && plan.executable && plan.args) {
134
- // argv only: paths and version metadata never become shell source.
135
- (dependencies.execute ?? execFileSync)(plan.executable, plan.args, {
136
- stdio: json ? ["ignore", 2, 2] : "inherit",
137
- });
149
+ try {
150
+ // argv only: paths and version metadata never become shell source.
151
+ (dependencies.execute ?? execFileSync)(plan.executable, plan.args, {
152
+ stdio: json ? ["ignore", 2, 2] : "inherit",
153
+ });
154
+ }
155
+ catch (error) {
156
+ throw updateFailure([plan.executable, ...plan.args].join(" "), error);
157
+ }
138
158
  executed = true;
139
159
  }
140
160
  if (!dryRun && plan.installerPrefix && plan.channel) {
141
- runManagedInstallerUpdate(plan.installerPrefix, plan.channel, json, dependencies.execute);
161
+ try {
162
+ runManagedInstallerUpdate(plan.installerPrefix, plan.channel, json, dependencies.execute);
163
+ }
164
+ catch (error) {
165
+ throw updateFailure("the installer", error);
166
+ }
142
167
  executed = true;
143
168
  }
144
169
  if (json)
145
- output(JSON.stringify({ ...plan, current, latest, dryRun, executed }));
170
+ output(JSON.stringify({ ...plan, current, latest, latestSource, dryRun, executed }));
146
171
  return plan;
147
172
  }
@@ -21,9 +21,9 @@
21
21
  <key>CFBundlePackageType</key>
22
22
  <string>APPL</string>
23
23
  <key>CFBundleShortVersionString</key>
24
- <string>2.9.24</string>
24
+ <string>2.9.25</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.24</string>
26
+ <string>2.9.25</string>
27
27
  <key>LSMinimumSystemVersion</key>
28
28
  <string>11.0</string>
29
29
  <key>LSUIElement</key>
@@ -10,7 +10,7 @@
10
10
  </data>
11
11
  <key>Resources/Assets.car</key>
12
12
  <data>
13
- GCWmy3k4L/Ut1Iml1My4dWKAUXA=
13
+ 7L0fXtCk10AeTcenMDtoPnTE9Qo=
14
14
  </data>
15
15
  </dict>
16
16
  <key>files2</key>
@@ -26,7 +26,7 @@
26
26
  <dict>
27
27
  <key>hash2</key>
28
28
  <data>
29
- mxm/LqezJ+GdXPR4Ujh+KGO7Z0Fod7ULKDxJsNy91/A=
29
+ DHqrNoKM8WzcXeuCicvLfyxe5ANT6B5xPmqAVvoF3zs=
30
30
  </data>
31
31
  </dict>
32
32
  </dict>
@@ -306,16 +306,28 @@ export class KittyImageStore {
306
306
  #pending = null;
307
307
  #nextAnonymous = 0x7f000000;
308
308
  #bytes = 0;
309
+ /** Cell size in thousandths of a device pixel. */
309
310
  #cellWidth;
310
311
  #cellHeight;
311
312
  #budget;
312
313
  #revision = 0;
313
314
  constructor(options = {}) {
314
- this.#cellWidth = options.cellWidthPx ?? 10;
315
- this.#cellHeight = options.cellHeightPx ?? 20;
315
+ this.#cellWidth = (options.cellWidthPx ?? 10) * 1000;
316
+ this.#cellHeight = (options.cellHeightPx ?? 20) * 1000;
316
317
  this.#budget = options.budget ?? DEFAULT_KITTY_IMAGE_BUDGET;
317
318
  this.#budget.register(this);
318
319
  }
320
+ /**
321
+ * The renderer's cell size in device pixels, with thousandths when it reports
322
+ * them (capability 103/104). Placements made from now on that give no `c`/`r`
323
+ * cover the image at this size; earlier ones keep their grid.
324
+ */
325
+ setCellPixels(width, height, precise) {
326
+ if (!(width > 0 && height > 0))
327
+ return;
328
+ this.#cellWidth = precise && precise.width > 0 ? precise.width : width * 1000;
329
+ this.#cellHeight = precise && precise.height > 0 ? precise.height : height * 1000;
330
+ }
319
331
  /** Bumps whenever images or placements change. */
320
332
  get revision() {
321
333
  return this.#revision;
@@ -449,8 +461,8 @@ export class KittyImageStore {
449
461
  if (!image)
450
462
  return;
451
463
  this.#used.set(imageId, this.#budget.nextTick());
452
- const columns = clampCells(int(control, "c") || Math.ceil(image.width / this.#cellWidth));
453
- const rows = clampCells(int(control, "r") || Math.ceil(image.height / this.#cellHeight));
464
+ const columns = clampCells(int(control, "c") || Math.ceil((image.width * 1000) / this.#cellWidth));
465
+ const rows = clampCells(int(control, "r") || Math.ceil((image.height * 1000) / this.#cellHeight));
454
466
  const placementId = int(control, "p");
455
467
  if (control.get("U") === "1") {
456
468
  const placements = this.#virtual.get(imageId) ?? new Map();
@@ -52,6 +52,28 @@ export class MirrorService {
52
52
  wasPending: this.registeredWindows?.pending() ?? null,
53
53
  });
54
54
  this.registeredWindows?.invalidate();
55
+ this.scheduleOwnershipVerify();
56
+ }
57
+ /**
58
+ * Until a read proves ownership again, every retained session refuses input
59
+ * and geometry. A workspace added or removed (another session created or
60
+ * killed) invalidates without any channel resyncing, and nothing else read
61
+ * again until the next stream was issued: the next keystroke closed the
62
+ * stream. Read again at once (coalesced) while a channel is retained; a
63
+ * failed read takes the #764 retry path.
64
+ */
65
+ ownershipVerifyScheduled = false;
66
+ scheduleOwnershipVerify() {
67
+ if (this.ownershipVerifyScheduled || this.disposed)
68
+ return;
69
+ this.ownershipVerifyScheduled = true;
70
+ const timer = setTimeout(() => {
71
+ this.ownershipVerifyScheduled = false;
72
+ if (this.disposed || this.channelSessions.size === 0 || !this.registeredWindows?.pending())
73
+ return;
74
+ void this.verifyRegisteredWindows().catch(() => { });
75
+ }, 0);
76
+ timer.unref?.();
55
77
  }
56
78
  /**
57
79
  * #764: a failed re-read must not leave every session "being verified"
@@ -425,6 +447,10 @@ export class MirrorService {
425
447
  if (message)
426
448
  throw new Error(message);
427
449
  }
450
+ /** Registered-window ownership is being read again; input waits for it. */
451
+ windowOwnershipPending() {
452
+ return this.registeredWindows?.pending() ?? false;
453
+ }
428
454
  windowOwnershipMessage(session) {
429
455
  if (this.registeredWindows?.pending())
430
456
  return "Window ownership is being verified. Retry after session discovery completes.";