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
@@ -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 {
@@ -34,12 +34,21 @@ export const DEFAULT_HOOK_HEALTHCHECK_SCHEDULE = Object.freeze({
34
34
  // `set-hook -gu`) can take them away; that is then noticed within 5 minutes.
35
35
  maxMs: 300_000,
36
36
  });
37
- /** Pure cadence rule: healthy checks double the wait up to the cap; anything else resets it. */
38
- export function nextHookHealthcheckDelay(previousMs, outcome, schedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE) {
37
+ /**
38
+ * Pure cadence rule: healthy checks double the wait up to the cap; a repair or
39
+ * failure resets it to the base. A check that is unhealthy again right after
40
+ * one that was (`consecutiveUnhealthy` of 2 or more) backs off as well: on a
41
+ * tmux server that is shutting down but cannot exit, every repair "succeeds"
42
+ * and is gone at the next check, and the base cadence then cost about 400 tmux
43
+ * calls a minute for as long as the server lingered.
44
+ */
45
+ export function nextHookHealthcheckDelay(previousMs, outcome, schedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE, consecutiveUnhealthy = 1) {
39
46
  const base = Math.max(1, Math.floor(schedule.baseMs));
40
47
  const max = Math.max(base, Math.floor(schedule.maxMs));
41
- if (outcome !== "healthy")
42
- return base;
48
+ if (outcome !== "healthy") {
49
+ const streak = Math.max(1, Math.min(32, Math.floor(consecutiveUnhealthy) || 1));
50
+ return Math.min(base * 2 ** (streak - 1), max);
51
+ }
43
52
  const previous = Number.isFinite(previousMs) ? Math.max(base, Math.floor(previousMs)) : base;
44
53
  return Math.min(previous * 2, max);
45
54
  }
@@ -249,6 +258,8 @@ export class TmuxExternalInteractionObserver {
249
258
  #healthcheckSchedule;
250
259
  #healthcheckDelayMs;
251
260
  #lastHealthcheckOutcome = "failed";
261
+ /** Scheduled checks in a row that did not find the hooks intact. */
262
+ #unhealthyChecks = 0;
252
263
  #onAvailability;
253
264
  #onGap;
254
265
  #tmuxWork = Promise.resolve();
@@ -374,9 +385,10 @@ export class TmuxExternalInteractionObserver {
374
385
  this.#reportGap("hook-repair-failed");
375
386
  outcome = "failed";
376
387
  }
388
+ this.#unhealthyChecks = outcome === "healthy" ? 0 : this.#unhealthyChecks + 1;
377
389
  // A signal-path reset that landed during this check wins over the outcome.
378
390
  if (this.#healthcheckDelayMs === delayBefore) {
379
- this.#healthcheckDelayMs = nextHookHealthcheckDelay(delayBefore, outcome, this.#healthcheckSchedule);
391
+ this.#healthcheckDelayMs = nextHookHealthcheckDelay(delayBefore, outcome, this.#healthcheckSchedule, this.#unhealthyChecks);
380
392
  }
381
393
  if (this.#hookHealthcheck === null)
382
394
  this.#scheduleHealthcheck();
@@ -485,11 +497,20 @@ export class TmuxExternalInteractionObserver {
485
497
  const work = this.#serializeTmux(async () => {
486
498
  const finish = this.#beginDiagnostic("healthcheck");
487
499
  try {
488
- if (await this.#ownedHooksPresent(this.#abort.signal)) {
500
+ const hooks = await this.#ownedHooksPresent(this.#abort.signal);
501
+ if (hooks === "present") {
489
502
  this.#lastHealthcheckOutcome = "healthy";
490
503
  finish(true);
491
504
  return;
492
505
  }
506
+ if (hooks === "unknown") {
507
+ // The check could not be made (tmux timed out or could not be
508
+ // started). That says nothing about the hooks: leave them, report
509
+ // no gap, and ask again at the base cadence.
510
+ this.#lastHealthcheckOutcome = "failed";
511
+ finish(false);
512
+ return;
513
+ }
493
514
  // Hooks that were installed and are now gone dropped every interaction
494
515
  // since their removal; the repair restores future observation only.
495
516
  if (this.#installed)
@@ -756,10 +777,12 @@ export class TmuxExternalInteractionObserver {
756
777
  output = await this.#io.runTmux(["show-hooks", "-g", "after-send-keys", ";", "show-hooks", "-g", "after-capture-pane"], signal);
757
778
  }
758
779
  catch {
759
- return false;
780
+ return "unknown";
760
781
  }
761
- return (ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
762
- ownedHookInstalled(output, "after-capture-pane", this.#bufferName));
782
+ return ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
783
+ ownedHookInstalled(output, "after-capture-pane", this.#bufferName)
784
+ ? "present"
785
+ : "missing";
763
786
  }
764
787
  get available() {
765
788
  return this.#installed;
@@ -33,6 +33,7 @@ import { liveSessionIdForNativeIdentity } from "../terminal/protocol/live-sessio
33
33
  import { SessionRuntimeRegistry } from "../terminal/session-runtime/registry.js";
34
34
  import { createSessionRuntimeMultiplexerBackend } from "../terminal/session-runtime/multiplexer-backend.js";
35
35
  import { TmuxExternalInteractionObserver } from "./tmux-external-interaction-observer.js";
36
+ import { createOrphanedControlClientWatch } from "./orphaned-control-clients.js";
36
37
  import { InteractionReceiptJournal } from "./interaction-receipt-journal.js";
37
38
  import { InteractionObservationStatusStore } from "./interaction-observation-status.js";
38
39
  import { InteractionEvidenceAuthority } from "./interaction-evidence-authority.js";
@@ -58,9 +59,19 @@ function discoveredWorkspaceName(registry, sessionName) {
58
59
  throw new Error("Unable to allocate discovered workspace identity");
59
60
  }
60
61
  /** Refresh discovered live membership without changing durable workspace intent or aliases. */
61
- export function createNativeTmuxServerCatalog(workspaceRegistry, run, assertOpen = () => undefined) {
62
+ export function createNativeTmuxServerCatalog(workspaceRegistry, run, assertOpen = () => undefined,
63
+ /** Told when the server has no sessions or does not answer; never awaited. */
64
+ onTrouble) {
62
65
  return async () => {
63
66
  assertOpen();
67
+ const tell = (kind) => {
68
+ try {
69
+ void Promise.resolve(onTrouble?.(kind)).catch(() => undefined);
70
+ }
71
+ catch {
72
+ /* A watcher never decides the catalog. */
73
+ }
74
+ };
64
75
  const raw = await run([
65
76
  "-N",
66
77
  "if-shell",
@@ -76,12 +87,18 @@ export function createNativeTmuxServerCatalog(workspaceRegistry, run, assertOpen
76
87
  ]
77
88
  .map(shellEscape)
78
89
  .join(" "),
79
- ], AbortSignal.timeout(2_000));
90
+ ], AbortSignal.timeout(2_000)).catch((error) => {
91
+ tell("unanswered");
92
+ throw error;
93
+ });
80
94
  assertOpen();
81
95
  const rows = new Map();
82
96
  // Only the successful server-side zero-session branch proves emptiness.
83
97
  // Command errors, unsupported formats and unwitnessed blank output stay failures.
84
- const lines = raw.trim() === "tmux-ide-empty-catalog-v1" ? [] : raw.trim().split("\n");
98
+ const empty = raw.trim() === "tmux-ide-empty-catalog-v1";
99
+ if (empty)
100
+ tell("no-sessions");
101
+ const lines = empty ? [] : raw.trim().split("\n");
85
102
  for (const line of lines) {
86
103
  const [pid, id, created, name, pane, window, activity, ...pathParts] = line.split("\t");
87
104
  const dir = pathParts.join("\t");
@@ -156,6 +173,11 @@ export async function createNativeTmuxServerOwner(options) {
156
173
  startTime: identityParts[1],
157
174
  };
158
175
  const generationRunAsync = createServerGenerationFencedTmuxAsyncRunner(authority, nativeServerIdentity);
176
+ const orphanWatch = createOrphanedControlClientWatch({
177
+ selector: authority.socketSelector,
178
+ serverId: options.serverId,
179
+ });
180
+ void orphanWatch.onOwnership();
159
181
  const multiplexer = new WorkspaceMultiplexerAuthority({
160
182
  daemonInstanceId: generation,
161
183
  registry: workspaceRegistry,
@@ -401,7 +423,7 @@ export async function createNativeTmuxServerOwner(options) {
401
423
  registry: sessionRuntimeRegistry,
402
424
  resolveSession: (name) => workspaceRegistry.get(name)?.sessionName ?? null,
403
425
  });
404
- const catalog = createNativeTmuxServerCatalog(workspaceRegistry, generationRunAsync, assertOpen);
426
+ const catalog = createNativeTmuxServerCatalog(workspaceRegistry, generationRunAsync, assertOpen, orphanWatch.onTrouble);
405
427
  const sessionCreator = createNativeTmuxSessionCreator({
406
428
  generation,
407
429
  registry: workspaceRegistry,
@@ -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
  }
@@ -81,6 +81,11 @@ const ERROR_MESSAGES = {
81
81
  operation_conflict: "The operation id was already used for another promotion intent.",
82
82
  operation_capacity: "The daemon has reached its bounded workspace-promote operation capacity.",
83
83
  };
84
+ /**
85
+ * How often a promotion stamps and proves a session whose pane inventory
86
+ * changed between the proof's two reads, before it refuses.
87
+ */
88
+ export const PROMOTION_PROOF_ATTEMPTS = 3;
84
89
  export class WorkspacePromotionError extends Error {
85
90
  code;
86
91
  context;
@@ -392,9 +397,25 @@ export class WorkspacePromotionAuthority {
392
397
  ? { workspaceName: alreadyRegistered.name, sessionName: session.sessionName }
393
398
  : derivePromotionIdentity(session.sessionName);
394
399
  this.#assertConflictFreeIdentity(identity);
395
- const canonicalRoot = await this.#stampSession(request, session, identity);
396
- this.#assertActive(request.operationId);
397
- await this.#verifyPromotedInventory(session.sessionId, identity);
400
+ // Another tmux client may split or close a pane while the session is
401
+ // being proved (an agent does it all day). The proof then cannot hold:
402
+ // stamp what is there now and prove again, a bounded number of times.
403
+ let canonicalRoot;
404
+ for (let attempt = 1;; attempt += 1) {
405
+ canonicalRoot = await this.#stampSession(request, session, identity);
406
+ this.#assertActive(request.operationId);
407
+ try {
408
+ await this.#verifyPromotedInventory(session.sessionId, identity);
409
+ break;
410
+ }
411
+ catch (error) {
412
+ if (attempt >= PROMOTION_PROOF_ATTEMPTS ||
413
+ !(error instanceof WorkspacePromotionError) ||
414
+ error.context.reason !== "inventory_changed_during_proof")
415
+ throw error;
416
+ this.#assertActive(request.operationId);
417
+ }
418
+ }
398
419
  await this.#publishFleetEnrollment(request, session, identity);
399
420
  // Catalog discovery can admit this session while the native stamping
400
421
  // and verification awaits run. Reuse that exact registry identity instead
@@ -21,9 +21,9 @@
21
21
  <key>CFBundlePackageType</key>
22
22
  <string>APPL</string>
23
23
  <key>CFBundleShortVersionString</key>
24
- <string>2.9.23</string>
24
+ <string>2.9.25</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.23</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
- eIcSkXParZcC4QAg0KZlGi3qdeA=
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
- s1pgcF7YhjrKOlxkEdh7I3iHyy1chYzX1V7z2eoz8Nk=
29
+ DHqrNoKM8WzcXeuCicvLfyxe5ANT6B5xPmqAVvoF3zs=
30
30
  </data>
31
31
  </dict>
32
32
  </dict>
@@ -1075,6 +1075,21 @@ export class WorkspaceTerminalInventoryRuntime {
1075
1075
  throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
1076
1076
  const epoch = this.#inventoryEpoch;
1077
1077
  const nativeEpoch = this.#nativeServerEpoch?.() ?? null;
1078
+ // An invalidation can also land while the snapshot is being adopted. That
1079
+ // publication is refused, as before, and the inventory is read again: it
1080
+ // used to fail the caller, and at startup the caller is the daemon.
1081
+ const publish = async (value, publicationSignal) => {
1082
+ try {
1083
+ return await this.#publishInventory(value, nativeEpoch, publicationSignal, epoch);
1084
+ }
1085
+ catch (error) {
1086
+ if (this.#disposed || signal?.aborted || this.#inventoryEpoch === epoch)
1087
+ throw error;
1088
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1089
+ return this.#readInventory(signal, staleRetry + 1);
1090
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1091
+ }
1092
+ };
1078
1093
  if (signal) {
1079
1094
  if (signal.aborted)
1080
1095
  throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
@@ -1097,7 +1112,7 @@ export class WorkspaceTerminalInventoryRuntime {
1097
1112
  return this.#readInventory(signal, staleRetry + 1);
1098
1113
  throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1099
1114
  }
1100
- return this.#publishInventory(snapshot, nativeEpoch, signal, epoch);
1115
+ return publish(snapshot, signal);
1101
1116
  }
1102
1117
  if (this.#inventoryRead?.epoch === epoch)
1103
1118
  return this.#inventoryRead.promise;
@@ -1120,7 +1135,7 @@ export class WorkspaceTerminalInventoryRuntime {
1120
1135
  return this.#readInventory(undefined, staleRetry + 1);
1121
1136
  throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1122
1137
  }
1123
- return this.#publishInventory(value, nativeEpoch, abort.signal, epoch);
1138
+ return publish(value, abort.signal);
1124
1139
  })().finally(() => {
1125
1140
  if (this.#inventoryRead?.promise === promise)
1126
1141
  this.#inventoryRead = null;
@@ -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.";
@@ -884,10 +884,34 @@ export class SessionChannel {
884
884
  }
885
885
  this.input.flush();
886
886
  this.clearWindowViewports();
887
- this.restoreWindowSizing(this.attachedIdentity?.runtimeSessionId ?? `=${this.opts.session}`);
887
+ const target = this.attachedIdentity?.runtimeSessionId ?? `=${this.opts.session}`;
888
+ this.restoreWindowSizing(target);
888
889
  this.io.send(`refresh-client -C ${cols}x${rows}${this.cellPixelSuffix()}`);
890
+ this.reclaimWindowSize(target);
889
891
  this.clientViewport = { cols, rows };
890
892
  }
893
+ /**
894
+ * Under `window-size latest` a second tmux client on the session (a terminal
895
+ * the user also attached) takes the window, and nothing this control client
896
+ * sends makes it tmux's latest client again: input and refresh-client are not
897
+ * client activity. Output then prints at the other client's width and tmux
898
+ * re-wraps it mid-word when that width goes away (#695). A fit is the app
899
+ * being used (it fits on focus and on a change of its canvas), so after one,
900
+ * when the window is not this client's size, switch to the same session:
901
+ * that makes this client the latest one. Only here, never on a timer or a
902
+ * notification, so two clients never fight; whichever the user used last
903
+ * wins, as between two terminals. Other window-size policies are the user's.
904
+ */
905
+ reclaimWindowSize(target) {
906
+ if (!this.geometryParticipating)
907
+ return;
908
+ const quoted = tmuxSingleQuote(target);
909
+ // Two FIFO slots whichever branch runs, as in restoreWindowSizing.
910
+ this.io.commandListInline(`if-shell -F -t ${quoted} '#{&&:#{==:#{window-size},latest},#{||:#{!=:#{window_width},#{client_width}},#{!=:#{window_height},#{client_height}}}}' ` +
911
+ tmuxSingleQuote(`switch-client -t ${quoted}`) +
912
+ " " +
913
+ tmuxSingleQuote(`display-message -p -t ${quoted} ''`), 2, 1, () => { });
914
+ }
891
915
  clientViewport = null;
892
916
  cellPixels = null;
893
917
  /** "/WxH" for tmux's refresh-client -C (patched tmux; stock ignores it). */
@@ -3080,7 +3104,8 @@ export class SessionChannel {
3080
3104
  !leftLayout ||
3081
3105
  !rightLayout ||
3082
3106
  leftWindow.semanticId !== rightWindow.semanticId ||
3083
- leftWindow.name !== rightWindow.name ||
3107
+ // Not the name: tmux derives it from the running command, and the
3108
+ // pane rows' own check ignores it too (sameSessionPaneInventory, #730).
3084
3109
  leftWindow.paneBorderStatus !== rightWindow.paneBorderStatus ||
3085
3110
  leftWindow.modeKeys !== rightWindow.modeKeys ||
3086
3111
  !layoutIdentitiesEqual(leftLayout, rightLayout)) {