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
@@ -220,6 +220,18 @@ export class SessionRuntimeControllerLeaseError extends Error {
220
220
  }
221
221
  }
222
222
 
223
+ /**
224
+ * An input fenced to a pane lifetime (capability 105) whose lifetime has
225
+ * ended: its owner is gone or was replaced. The input must not reach another
226
+ * lifetime; the pane's delivery tells the client that its lifetime ended.
227
+ */
228
+ export class SessionRuntimeInputLifetimeEndedError extends Error {
229
+ constructor(message: string) {
230
+ super(message);
231
+ this.name = "SessionRuntimeInputLifetimeEndedError";
232
+ }
233
+ }
234
+
223
235
  export interface SessionRuntimeConsumer {
224
236
  readonly generation: SessionRuntimeGeneration;
225
237
  readonly session: string;
@@ -696,6 +708,11 @@ export class SessionRuntimeRegistry implements PaneStreamMirror {
696
708
  await this.#mirror.verifyRegisteredWindows();
697
709
  }
698
710
 
711
+ /** Ownership is being read again: input and geometry wait, they are not refused for good. */
712
+ windowOwnershipPending(): boolean {
713
+ return !this.#disposed && this.#mirror.windowOwnershipPending();
714
+ }
715
+
699
716
  /** Install the bounded registered-session membership reader. */
700
717
  setRegisteredWindowReader(
701
718
  reader: import("../mirror/registered-window-guard.ts").RegisteredWindowReader,
@@ -1264,6 +1281,12 @@ class SessionRuntime {
1264
1281
  readonly #consumersByClientId = new Map<string, SessionRuntimeConsumerImpl>();
1265
1282
  readonly #terminalReplicas = new Map<string, SessionRuntimeTerminalReplicaOwner>();
1266
1283
  readonly #terminalReplicaClocks = new Map<string, { epoch: number; revision: number }>();
1284
+ /** The renderer's last reported cell size; every pane's image placements use it. */
1285
+ #cellPixels: {
1286
+ width: number;
1287
+ height: number;
1288
+ precise?: { width: number; height: number };
1289
+ } | null = null;
1267
1290
  #outputTraces: RuntimeTraceCorrelator | null;
1268
1291
  readonly #outputObservations = new Map<
1269
1292
  string,
@@ -1658,7 +1681,8 @@ class SessionRuntime {
1658
1681
  const replicaOwner = expectedLifetime
1659
1682
  ? this.#terminalReplicas.get(semanticPaneId)
1660
1683
  : this.#terminalReplicaOwner(semanticPaneId);
1661
- if (!replicaOwner) throw new Error("Input target lifetime unavailable");
1684
+ if (!replicaOwner)
1685
+ throw new SessionRuntimeInputLifetimeEndedError("Input target lifetime unavailable");
1662
1686
  if (causalProbe) {
1663
1687
  this.#activeCausalCellProbes += 1;
1664
1688
  let settled = false;
@@ -1689,7 +1713,7 @@ class SessionRuntime {
1689
1713
  this.#terminalReplicas.get(semanticPaneId) !== replicaOwner ||
1690
1714
  replicaOwner.inputAdmissionIncarnation() !== expectedLifetime.incarnation)
1691
1715
  )
1692
- throw new Error("Input target lifetime changed");
1716
+ throw new SessionRuntimeInputLifetimeEndedError("Input target lifetime changed");
1693
1717
  if (input.kind === "text")
1694
1718
  this.#mirror.sendText(
1695
1719
  this.session,
@@ -1818,6 +1842,9 @@ class SessionRuntime {
1818
1842
  ): void {
1819
1843
  this.#assertConnected(clientId);
1820
1844
  this.#mirror.setCellPixels?.(this.session, width, height, precise);
1845
+ this.#cellPixels = { width, height, ...(precise ? { precise } : {}) };
1846
+ for (const owner of this.#terminalReplicas.values())
1847
+ owner.setCellPixels(width, height, precise);
1821
1848
  }
1822
1849
 
1823
1850
  fitViewportWithAuthority(
@@ -2042,6 +2069,12 @@ class SessionRuntime {
2042
2069
  },
2043
2070
  );
2044
2071
  owner = candidate;
2072
+ if (this.#cellPixels)
2073
+ owner.setCellPixels(
2074
+ this.#cellPixels.width,
2075
+ this.#cellPixels.height,
2076
+ this.#cellPixels.precise,
2077
+ );
2045
2078
  this.#terminalReplicas.set(semanticPaneId, owner);
2046
2079
  }
2047
2080
  return owner;
@@ -1,4 +1,5 @@
1
1
  import { assertStockCaptureRepresentable } from "./stock-capture-fidelity.ts";
2
+ import { logger } from "../../lib/log.ts";
2
3
  import { rememberNativeSeedBacking } from "./native-seed-backing.ts";
3
4
  import type { NativeGridCapture } from "../mirror/native-grid-capture.ts";
4
5
  import type { MirrorObservedTerminalModes } from "../mirror/events.ts";
@@ -184,6 +185,9 @@ export class TerminalReplicaInterpreter {
184
185
  #nativeSeedBackingCandidate: NativeGridCapture | undefined;
185
186
  readonly #generation: SessionRuntimeGeneration;
186
187
  readonly #workspaceName: string;
188
+ #stockTabsNoted = false;
189
+ #seedOrdinal = 0;
190
+ #reconstructedSeed: number | null = null;
187
191
  readonly #semanticPaneId: string;
188
192
  readonly #incarnation: string;
189
193
  #scrollback: number;
@@ -344,6 +348,15 @@ export class TerminalReplicaInterpreter {
344
348
  return this.#needsSeed ? null : this.#seed();
345
349
  }
346
350
 
351
+ /**
352
+ * Names the current seed when its tab cells were reconstructed from a stock
353
+ * capture; null otherwise. Such a seed can wrap a reflowed line at other
354
+ * places than tmux does, so its history can differ from tmux's in length.
355
+ */
356
+ reconstructedSeed(): number | null {
357
+ return this.#reconstructedSeed;
358
+ }
359
+
347
360
  /** Prioritize one future parser admission, independent of diagnostic tracing. */
348
361
  prioritizeNextWrite(): void {
349
362
  if (!this.#closed) this.#prioritizeNextWrite = true;
@@ -428,7 +441,12 @@ export class TerminalReplicaInterpreter {
428
441
  ): Promise<void> {
429
442
  if (this.#closed) return;
430
443
  if (operation.type === "reseed") {
431
- if (operation.bootstrap === "painted-capture" && !operation.native)
444
+ // A stock capture prints a saved tab cell as one HT and drops its width.
445
+ // Paint it to the next tab stop; refuse only when the parser cannot say
446
+ // where its cursor is.
447
+ const paintCapturedTabs = operation.bootstrap === "painted-capture" && !operation.native;
448
+ let seedReconstructed: boolean;
449
+ if (paintCapturedTabs && !this.#backend.graphicsCursor)
432
450
  assertStockCaptureRepresentable(operation.captureChunks ?? operation.chunks);
433
451
  this.#causalCell?.fail("reseeded");
434
452
  const nativeCols = operation.nativeCols ?? operation.cols;
@@ -447,9 +465,23 @@ export class TerminalReplicaInterpreter {
447
465
  try {
448
466
  if (operation.native && !replacement.importNativeGrid?.(operation.native))
449
467
  throw new Error("Native bootstrap requires a compatible interpreter");
468
+ // Capture chunks come first and in order; anything else is live output,
469
+ // where HT stays cursor motion.
470
+ const captured = operation.captureChunks ?? operation.chunks;
471
+ let nextCaptured = 0;
472
+ let reconstructed = false;
450
473
  for (const chunk of operation.chunks) {
451
- await this.#writeToBackend(replacement, chunk);
474
+ const fromCapture =
475
+ paintCapturedTabs &&
476
+ nextCaptured < captured.length &&
477
+ Buffer.compare(chunk, captured[nextCaptured]!) === 0;
478
+ if (fromCapture) nextCaptured += 1;
479
+ if (fromCapture && chunk.includes(9)) {
480
+ reconstructed = true;
481
+ await this.#writeStockCapture(replacement, chunk);
482
+ } else await this.#writeToBackend(replacement, chunk);
452
483
  }
484
+ seedReconstructed = reconstructed;
453
485
  if (operation.wraparound !== undefined)
454
486
  replacement.setAuthoritativeWraparound(operation.wraparound);
455
487
  if (operation.observedModes) replacement.setAuthoritativeModes(operation.observedModes);
@@ -484,6 +516,8 @@ export class TerminalReplicaInterpreter {
484
516
  previous.modes().alternateScreen === replacement.modes().alternateScreen;
485
517
  if (!sameGraphicsBasis) this.#kitty.dropCursorPlacements();
486
518
  this.#nativeReseedRequested = false;
519
+ this.#seedOrdinal += 1;
520
+ this.#reconstructedSeed = seedReconstructed ? this.#seedOrdinal : null;
487
521
  this.#scrollback = scrollback;
488
522
  this.#bootstrap = {
489
523
  kind: operation.bootstrap,
@@ -673,6 +707,44 @@ export class TerminalReplicaInterpreter {
673
707
  }, 250);
674
708
  }
675
709
 
710
+ /**
711
+ * Replay one stock `capture-pane -e` chunk. tmux stores a tab as one wide
712
+ * cell and prints it as a single HT, without its width. Blank the cells up
713
+ * to the next default tab stop instead (ECH, then CUF): that is the cell tmux
714
+ * made when the tab was written at this column, and erased cells take the
715
+ * rendition the capture set for it, as tmux's blank tab cell does. tmux never
716
+ * tabs into the last column (`input_c0_dispatch`).
717
+ * Where this differs from tmux: a row edited after its tab was written
718
+ * (insert or delete character) or written under custom tab stops is columns
719
+ * off in that row. A line reflowed by a resize is worse: tmux keeps the tab
720
+ * cell's width, this measures it again from the new column, so the line can
721
+ * wrap at other places and the pane can hold other rows than tmux shows,
722
+ * until that output scrolls away or is redrawn. The owner accepts the
723
+ * resulting difference in history length (`reconstructedSeed`).
724
+ */
725
+ async #writeStockCapture(backend: TerminalInterpreterBackend, chunk: Uint8Array): Promise<void> {
726
+ let start = 0;
727
+ for (;;) {
728
+ const tab = chunk.indexOf(9, start);
729
+ if (tab < 0) break;
730
+ if (tab > start) await this.#writeToBackend(backend, chunk.subarray(start, tab));
731
+ const column = backend.graphicsCursor!().x;
732
+ const stop = Math.min(backend.cols - 1, (Math.floor(column / 8) + 1) * 8);
733
+ if (stop > column)
734
+ await this.#writeToBackend(backend, `\x1b[${stop - column}X\x1b[${stop - column}C`);
735
+ start = tab + 1;
736
+ }
737
+ if (!this.#stockTabsNoted) {
738
+ this.#stockTabsNoted = true;
739
+ // Once per pane: its saved rows are not tmux's exact cells on this server.
740
+ logger.info("terminal-replica", "stock capture: tab positions reconstructed", {
741
+ pane: this.#semanticPaneId,
742
+ workspace: this.#workspaceName,
743
+ });
744
+ }
745
+ if (start < chunk.length) await this.#writeToBackend(backend, chunk.subarray(start));
746
+ }
747
+
676
748
  #writeToBackend(backend: TerminalInterpreterBackend, data: Uint8Array | string): Promise<void> {
677
749
  if (this.#prioritizeNextWrite) {
678
750
  this.#prioritizeNextWrite = false;
@@ -128,6 +128,7 @@ export class SessionRuntimeTerminalReplicaOwner {
128
128
  #historyTimer: SessionRuntimeTimer | null = null;
129
129
  #historyChecking = false;
130
130
  #historyDirty = false;
131
+ #reconstructedHistoryGap: { readonly seed: number; readonly gap: number } | null = null;
131
132
 
132
133
  constructor(
133
134
  readonly generation: SessionRuntimeGeneration,
@@ -437,6 +438,11 @@ export class SessionRuntimeTerminalReplicaOwner {
437
438
  return this.#interpreter.onGraphics(listener);
438
439
  }
439
440
 
441
+ /** The renderer's cell size, for image placements that give no `c`/`r` (group H). */
442
+ setCellPixels(width: number, height: number, precise?: { width: number; height: number }): void {
443
+ this.#interpreter.kittyImages().setCellPixels(width, height, precise);
444
+ }
445
+
440
446
  /** Image bytes by content digest, while the pane's store still holds them. */
441
447
  graphicsImage(digest: string): KittyImage | null {
442
448
  return this.#interpreter.kittyImages().imageByDigest(digest) ?? null;
@@ -515,7 +521,21 @@ export class SessionRuntimeTerminalReplicaOwner {
515
521
  )
516
522
  return;
517
523
  const seed = this.#interpreter.currentSeed();
518
- if (seed && seed.snapshot.history.length !== size) upstream.reseed();
524
+ if (!seed) return;
525
+ const gap = size - seed.snapshot.history.length;
526
+ // A seed with reconstructed tabs can differ from tmux in row count, and
527
+ // a new capture would paint the same rows again. Accept the difference
528
+ // that seed has at its first check, zero included, and reseed only when
529
+ // the difference changes.
530
+ const reconstructed = this.#interpreter.reconstructedSeed();
531
+ if (reconstructed !== null) {
532
+ if (this.#reconstructedHistoryGap?.seed !== reconstructed) {
533
+ this.#reconstructedHistoryGap = { seed: reconstructed, gap };
534
+ return;
535
+ }
536
+ if (this.#reconstructedHistoryGap.gap === gap) return;
537
+ } else if (gap === 0) return;
538
+ upstream.reseed();
519
539
  } catch {
520
540
  // Unavailable metadata is not evidence that history disappeared.
521
541
  } finally {
@@ -135,8 +135,8 @@ function authenticatedSurface(transport: SessionRuntimeTransport, hostClientId:
135
135
  export class SessionRuntimeTransportBinding {
136
136
  readonly #binder: SessionRuntimeTransportBinder;
137
137
  readonly #shared: SharedClient;
138
- readonly #allowedSourcePaneIds: ReadonlySet<string>;
139
- readonly #contributedSourcePaneIds: ReadonlySet<string>;
138
+ readonly #allowedSourcePaneIds: Set<string>;
139
+ readonly #contributedSourcePaneIds: Set<string>;
140
140
  readonly #interactive: boolean;
141
141
  readonly #explicitAuthority: boolean;
142
142
  readonly #deliverySubscriberId: string;
@@ -315,6 +315,46 @@ export class SessionRuntimeTransportBinding {
315
315
  this.#binder.registry.assertExecutionHandle(this.#baseHandle, semanticPaneId);
316
316
  }
317
317
 
318
+ /**
319
+ * The session's pane set changed under this live transport (#723). The
320
+ * caller is the daemon's own stream boundary, and the panes come from its
321
+ * trusted inventory of this binding's session: a client can never name a
322
+ * pane here. The grant stays exact: added panes join it, removed panes leave
323
+ * it, and every execution handle is rebuilt from the amended set.
324
+ * All-or-nothing: an invalid pane id changes nothing.
325
+ */
326
+ amendPaneGrant(change: {
327
+ readonly added: readonly string[];
328
+ readonly removed: readonly string[];
329
+ }): void {
330
+ this.#assertOpen();
331
+ const added = change.added.map((paneId) =>
332
+ TerminalAttachmentSemanticPaneIdSchemaZ.parse(paneId),
333
+ );
334
+ const removed = change.removed.map((paneId) =>
335
+ TerminalAttachmentSemanticPaneIdSchemaZ.parse(paneId),
336
+ );
337
+ for (const paneId of removed) {
338
+ if (!this.#allowedSourcePaneIds.delete(paneId)) continue;
339
+ if (!this.#contributedSourcePaneIds.delete(paneId)) continue;
340
+ const next = (this.#shared.grantRefs.get(paneId) ?? 0) - 1;
341
+ if (next > 0) this.#shared.grantRefs.set(paneId, next);
342
+ else this.#shared.grantRefs.delete(paneId);
343
+ }
344
+ for (const paneId of added) {
345
+ if (this.#allowedSourcePaneIds.has(paneId)) continue;
346
+ this.#allowedSourcePaneIds.add(paneId);
347
+ // As at bind: only an interactive transport contributes authorship.
348
+ if (!this.#interactive) continue;
349
+ this.#contributedSourcePaneIds.add(paneId);
350
+ this.#shared.grantRefs.set(paneId, (this.#shared.grantRefs.get(paneId) ?? 0) + 1);
351
+ }
352
+ // Handles carry a copy of the grant; the next use rebuilds them.
353
+ this.#baseHandle = null;
354
+ this.#baseHandleLease = null;
355
+ this.#intentHandles.clear();
356
+ }
357
+
318
358
  openTerminalDelivery(
319
359
  semanticPaneId: string,
320
360
  offer: TerminalDeliveryOffer,
@@ -20,7 +20,16 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
20
20
  import { dirname, join } from "node:path";
21
21
  import { z } from "zod";
22
22
  import { runTmux } from "@tmux-ide/tmux-bridge";
23
- import { readProcessTable, resolveAgentCommand, type ProcEntry } from "../detect/process-tree.ts";
23
+ import {
24
+ readProcessTable,
25
+ readProcessTableAsync,
26
+ resolveAgentCommand,
27
+ type ProcEntry,
28
+ } from "../detect/process-tree.ts";
29
+ import {
30
+ snapshotIsRestorePoint,
31
+ type CrashSnapshotSource,
32
+ } from "../../lib/daemon-crash-snapshot.ts";
24
33
  import { isListableSession } from "../team/sessions.ts";
25
34
 
26
35
  // ---------------------------------------------------------------------------
@@ -384,12 +393,29 @@ export function snapshotEvery(): number {
384
393
  return Number.isInteger(n) && n > 0 ? n : SNAPSHOT_EVERY;
385
394
  }
386
395
 
396
+ export { snapshotIsRestorePoint };
397
+
398
+ /**
399
+ * The file and builder the daemon's own writer uses (#783). The process that
400
+ * owns a headless daemon passes this in; the engine may not import it.
401
+ */
402
+ export const fleetCrashSnapshotSource: CrashSnapshotSource<FleetSnapshot> = {
403
+ sessionFormat: SNAPSHOT_SESSION_FORMAT,
404
+ paneFormat: SNAPSHOT_PANE_FORMAT,
405
+ build: async (panes, sessions) => buildSnapshot(panes, sessions, await readProcessTableAsync()),
406
+ read: () => readSnapshot(),
407
+ write: writeSnapshot,
408
+ fingerprint: snapshotFingerprint,
409
+ };
410
+
387
411
  /** Deps for {@link createSnapshotter} — injectable so the throttle is unit-tested. */
388
412
  export interface SnapshotterDeps {
389
413
  collect: () => FleetSnapshot;
390
414
  read: () => FleetSnapshot | null;
391
415
  write: (snapshot: FleetSnapshot) => void;
392
416
  every: number;
417
+ /** When the running tmux server started. With it, a restore point is not replaced. */
418
+ serverStartMs?: () => number;
393
419
  }
394
420
 
395
421
  /**
@@ -406,6 +432,7 @@ export function createSnapshotter(deps: SnapshotterDeps): Snapshotter {
406
432
  let ticks = 0;
407
433
  let seeded = false;
408
434
  let lastFingerprint: string | null = null;
435
+ let held = false;
409
436
  return {
410
437
  onTick(): void {
411
438
  ticks++;
@@ -416,6 +443,25 @@ export function createSnapshotter(deps: SnapshotterDeps): Snapshotter {
416
443
  seeded = true;
417
444
  }
418
445
  const snapshot = deps.collect();
446
+ if (deps.serverStartMs) {
447
+ const existing = deps.read();
448
+ let serverStartMs = Number.NaN;
449
+ try {
450
+ serverStartMs = deps.serverStartMs();
451
+ } catch {
452
+ // Unknown start time: not a restore point.
453
+ }
454
+ const sessions = snapshot.sessions.map((session) => session.name);
455
+ if (snapshotIsRestorePoint(existing, { serverStartMs, sessions })) {
456
+ held = true;
457
+ return;
458
+ }
459
+ if (held) {
460
+ // Released: the file changed hands or is gone. Compare with it afresh.
461
+ held = false;
462
+ lastFingerprint = existing ? snapshotFingerprint(existing) : null;
463
+ }
464
+ }
419
465
  const fingerprint = snapshotFingerprint(snapshot);
420
466
  if (fingerprint === lastFingerprint) return;
421
467
  lastFingerprint = fingerprint;
@@ -555,10 +555,13 @@ export function unadoptSession(session: string): void {
555
555
  // fallback if the fleet probe races a tab closing.
556
556
  clearPaneChromeWindows([session]);
557
557
  for (const argv of unadoptOptionCommands(session)) runTmux(argv);
558
- // KNOWN SIMPLIFICATION: the popup key AND the status-click router are
559
- // SERVER-wide binds, so unadopting one session removes them for ALL adopted
560
- // sessions. Acceptable for now — best-effort so a missing bind (already
558
+ // The popup key, the status-click router, the right-click menus and every
559
+ // Alt/prefix key are SERVER-wide binds. Another session on this server that
560
+ // is still adopted keeps using them, so they go only with the last adopted
561
+ // session (this session's marker is already gone above). A probe that fails
562
+ // reads as "none left", as before. Best-effort so a missing bind (already
561
563
  // unadopted) doesn't throw. Unbind the SAME configured keys adopt bound.
564
+ if (listAdoptedSessions().length > 0) return;
562
565
  const keys = getAppConfig().keys;
563
566
  // The mouse binds (status-click router + the two right-click menu openers).
564
567
  for (const undo of [
@@ -600,5 +603,5 @@ export function unadoptSession(session: string): void {
600
603
  }
601
604
  }
602
605
  // The updater only needs to run while something is adopted.
603
- if (listAdoptedSessions().length === 0) stopUpdater();
606
+ stopUpdater();
604
607
  }
@@ -754,6 +754,9 @@ export function runUpdaterLoop(): void {
754
754
  read: readSnapshot,
755
755
  write: writeSnapshot,
756
756
  every: config.updater.snapshotEvery,
757
+ // A dead server's snapshot is kept until its sessions are restored (#783).
758
+ serverStartMs: () =>
759
+ Number(runTmux(["display-message", "-p", "#{start_time}"]).toString().trim()) * 1000,
757
760
  });
758
761
  const shouldGiveUp = createUnreachableCounter();
759
762
  const tick = () => {
@@ -1,5 +1,6 @@
1
1
  import type { HomeAgentRow } from "./application-home-agents.ts";
2
2
  import type { ApplicationGenerationStartResult } from "./application-generation-starter.ts";
3
+ import type { AdmittedPaneSelectionOutcome } from "./application-terminal-interaction-controller.ts";
3
4
 
4
5
  export type HomeAgentNavigationSource = "keyboard" | "mouse";
5
6
  export type HomeAgentNavigationTarget = Pick<
@@ -22,6 +23,7 @@ export type HomeAgentNavigationFailure =
22
23
  | "attach-failed"
23
24
  | "generation-changed"
24
25
  | "pane-removed"
26
+ | "selection-failed"
25
27
  | "superseded";
26
28
 
27
29
  export interface HomeAgentNavigationResult {
@@ -53,7 +55,7 @@ export function createApplicationHomeAgentNavigator(options: {
53
55
  paneId: string,
54
56
  source: HomeAgentNavigationSource,
55
57
  admission?: Promise<boolean>,
56
- ) => void;
58
+ ) => void | Promise<AdmittedPaneSelectionOutcome> | undefined;
57
59
  /**
58
60
  * Home's roster can list an agent a moment before the attached session does.
59
61
  * Resolves true once `listed()` holds, false on the bound, abort or a
@@ -64,6 +66,16 @@ export function createApplicationHomeAgentNavigator(options: {
64
66
  listed: () => boolean,
65
67
  signal: AbortSignal,
66
68
  ) => Promise<boolean>;
69
+ /**
70
+ * "Is it current" answers no while the roster re-reads a session, which it
71
+ * does whenever an agent appears or changes: exactly when a row gets clicked.
72
+ * Resolves once the roster has settled for this target (true: current again)
73
+ * or a bound passed. Without it a click during a re-read is refused at once.
74
+ */
75
+ readonly waitForCurrentTarget?: (
76
+ target: HomeAgentNavigationTarget,
77
+ signal: AbortSignal,
78
+ ) => Promise<boolean>;
67
79
  readonly showTerminals: (source: HomeAgentNavigationSource) => void;
68
80
  readonly setNote: (note: string | null) => void;
69
81
  }) {
@@ -90,6 +102,23 @@ export function createApplicationHomeAgentNavigator(options: {
90
102
  !!current?.agents.some(
91
103
  (agent) => agent.id === target.agentId && agent.paneId === target.paneId,
92
104
  );
105
+ /** Before a check that would refuse a stale target: let a re-reading roster finish. */
106
+ const settleTarget = async (
107
+ token: number,
108
+ target: HomeAgentNavigationTarget,
109
+ signal: AbortSignal,
110
+ ): Promise<void> => {
111
+ if (!options.waitForCurrentTarget || !active(token) || options.isCurrentTarget(target)) return;
112
+ if (waitingNote !== token) {
113
+ options.setNote(`Waiting for agent in ${target.sessionName}…`);
114
+ waitingNote = token;
115
+ }
116
+ try {
117
+ await options.waitForCurrentTarget(target, signal);
118
+ } catch {
119
+ // A failed wait decides nothing; the check that follows does.
120
+ }
121
+ };
93
122
  /** Every admission check; null admits. Notes are set only for a refusal. */
94
123
  const refusal = (
95
124
  token: number,
@@ -160,7 +189,7 @@ export function createApplicationHomeAgentNavigator(options: {
160
189
  const admission = new Promise<boolean>((resolve) => {
161
190
  settle = resolve;
162
191
  });
163
- options.selectPane(target.paneId!, source, admission);
192
+ const selection = options.selectPane(target.paneId!, source, admission);
164
193
  // The cold path's "Opening agent in …" note, for the warm wait.
165
194
  options.setNote(`Waiting for agent in ${target.sessionName}…`);
166
195
  waitingNote = token;
@@ -169,11 +198,36 @@ export function createApplicationHomeAgentNavigator(options: {
169
198
  } catch {
170
199
  // A failed wait is a refusal below, never an admission.
171
200
  }
172
- if (waitingNote === token) waitingNote = null;
201
+ if (options.waitForCurrentTarget && !options.isCurrentTarget(target))
202
+ await settleTarget(token, target, signal);
173
203
  // A refusal replaces the note; an admission clears it below.
174
204
  const refused = refusal(token, target, generationKey);
175
205
  settle(refused === null);
176
- if (refused) return refused;
206
+ if (refused) {
207
+ if (waitingNote === token) waitingNote = null;
208
+ return refused;
209
+ }
210
+ // Admitted is not selected: the runtime may still refuse the pane, or take
211
+ // a moment for a pane that was just created. The wait note stays until it
212
+ // answers, and the terminals are shown only for a pane that was selected.
213
+ let selected: AdmittedPaneSelectionOutcome;
214
+ try {
215
+ selected = (await selection) ?? "selected";
216
+ } catch {
217
+ selected = "failed";
218
+ }
219
+ if (waitingNote === token) waitingNote = null;
220
+ if (!active(token)) return { opened: false, failure: "superseded" };
221
+ if (selected === "superseded" || selected === "not-admitted") {
222
+ options.setNote(null);
223
+ return { opened: false, failure: "superseded" };
224
+ }
225
+ if (selected === "failed")
226
+ return failure(
227
+ token,
228
+ "selection-failed",
229
+ "That agent's terminal could not be selected yet. Select the agent again.",
230
+ );
177
231
  options.showTerminals(source);
178
232
  options.setNote(null);
179
233
  return { opened: true };
@@ -193,6 +247,12 @@ export function createApplicationHomeAgentNavigator(options: {
193
247
  try {
194
248
  if (!target.paneId)
195
249
  return failure(token, "unavailable", "This agent has no available terminal to open.");
250
+ // Only when it is needed: a warm open of a current target stays synchronous.
251
+ if (options.waitForCurrentTarget && !options.isCurrentTarget(target)) {
252
+ await settleTarget(token, target, controller.signal);
253
+ if (!active(token)) return { opened: false, failure: "superseded" };
254
+ if (waitingNote === token) waitingNote = null;
255
+ }
196
256
  if (!options.isCurrentTarget(target))
197
257
  return failure(
198
258
  token,
@@ -247,6 +307,11 @@ export function createApplicationHomeAgentNavigator(options: {
247
307
  "The session opened, but agent details are not ready. Return Home and retry.",
248
308
  );
249
309
  }
310
+ if (options.waitForCurrentTarget && !options.isCurrentTarget(target)) {
311
+ await settleTarget(token, target, controller.signal);
312
+ if (!active(token)) return { opened: false, failure: "superseded" };
313
+ if (waitingNote === token) waitingNote = null;
314
+ }
250
315
  return admit(token, target, source, opened.generationKey);
251
316
  } catch {
252
317
  return failure(
@@ -1,3 +1,6 @@
1
+ import { waitForRosterTarget } from "../../../lib/home-agent-observer.ts";
2
+ import type { HomeAgentNavigationTarget } from "./application-home-agent-navigation.ts";
3
+ import type { AdmittedPaneSelectionOutcome } from "./application-terminal-interaction-controller.ts";
1
4
  import { createApplicationNewAgentOwner } from "./application-new-agent-owner.ts";
2
5
  import type { ApplicationPaletteCommand } from "./application-palette-input.ts";
3
6
  import { createEffect, createSignal, onCleanup, untrack, type Accessor } from "solid-js";
@@ -142,7 +145,10 @@ export function createApplicationHomeAgentsOwner(options: {
142
145
  readonly generation: () => OpenTuiGenerationHostSnapshot | null;
143
146
  readonly sessionName: () => string | null;
144
147
  readonly startGeneration: ReturnType<typeof createApplicationGenerationStarter>;
145
- readonly selectPane: (paneId: string, admission?: Promise<boolean>) => void;
148
+ readonly selectPane: (
149
+ paneId: string,
150
+ admission?: Promise<boolean>,
151
+ ) => void | Promise<AdmittedPaneSelectionOutcome>;
146
152
  readonly showTerminals: (source: "keyboard" | "mouse") => void;
147
153
  readonly restoreHome?: (source: "keyboard" | "mouse") => Promise<void> | void;
148
154
  readonly setNote: (note: string | null) => void;
@@ -154,19 +160,20 @@ export function createApplicationHomeAgentsOwner(options: {
154
160
  const [selected, setSelected] = createSignal(selection.snapshot());
155
161
  const [opening, setOpening] = createSignal(false);
156
162
  let request = 0;
163
+ const currentTarget = (target: HomeAgentNavigationTarget): boolean => {
164
+ const catalog = options.catalog();
165
+ return (
166
+ catalog.phase === "live" &&
167
+ catalog.daemonInstanceId === target.daemonInstanceId &&
168
+ catalog.sessions.some(
169
+ (session) =>
170
+ session.name === target.sessionName && session.liveSessionId === target.liveSessionId,
171
+ ) &&
172
+ observer.isCurrentTarget(target)
173
+ );
174
+ };
157
175
  const navigator = createApplicationHomeAgentNavigator({
158
- isCurrentTarget(target) {
159
- const catalog = options.catalog();
160
- return (
161
- catalog.phase === "live" &&
162
- catalog.daemonInstanceId === target.daemonInstanceId &&
163
- catalog.sessions.some(
164
- (session) =>
165
- session.name === target.sessionName && session.liveSessionId === target.liveSessionId,
166
- ) &&
167
- observer.isCurrentTarget(target)
168
- );
169
- },
176
+ isCurrentTarget: currentTarget,
170
177
  currentGeneration() {
171
178
  const generation = options.generation();
172
179
  const generationKey = applicationGenerationNavigationKey(generation);
@@ -181,6 +188,16 @@ export function createApplicationHomeAgentsOwner(options: {
181
188
  agents: semantic.sidebar.agents,
182
189
  };
183
190
  },
191
+ waitForCurrentTarget: (target, signal) =>
192
+ waitForRosterTarget({
193
+ isCurrent: () => currentTarget(target),
194
+ refreshing: () => {
195
+ const observed = observer.getSnapshot();
196
+ return observed.refreshingSessionKeys.length > 0 || observed.loadingSessions > 0;
197
+ },
198
+ subscribe: (listener) => observer.subscribe(() => listener()),
199
+ signal,
200
+ }),
184
201
  waitForGeneration: (key, signal) => waitForHomeAgentSemantic(options.generation, key, signal),
185
202
  waitForAgent: (key, listed, signal) =>
186
203
  waitForHomeAgentListed(options.generation, key, listed, signal),