tmux-ide 2.9.21 → 2.9.23

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 (131) hide show
  1. package/bin/cli.js +6235 -8473
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +2 -0
  4. package/packages/contracts/src/pane-reader.ts +121 -0
  5. package/packages/contracts/src/pane-stream.ts +18 -0
  6. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  7. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  8. package/packages/daemon/dist/command-center/automation.js +1 -1
  9. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  10. package/packages/daemon/dist/command-center/discovery.js +28 -2
  11. package/packages/daemon/dist/command-center/server.js +8 -2
  12. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  13. package/packages/daemon/dist/command-center/tmux-servers.js +7 -1
  14. package/packages/daemon/dist/doctor.js +147 -43
  15. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  16. package/packages/daemon/dist/lib/cli-command.js +13 -0
  17. package/packages/daemon/dist/lib/daemon-embed.js +126 -55
  18. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  19. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  20. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  21. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  22. package/packages/daemon/dist/lib/log.js +18 -1
  23. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  24. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  25. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  26. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  27. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  28. package/packages/daemon/dist/lib/tmux-pane-reader.js +107 -0
  29. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  30. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  31. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  32. package/packages/daemon/dist/lib/tmux-server-owner.js +38 -37
  33. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  34. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  35. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  36. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  37. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  38. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  39. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  40. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  41. package/packages/daemon/dist/open-browser.js +26 -12
  42. package/packages/daemon/dist/open-reader.js +84 -0
  43. package/packages/daemon/dist/plugins/cli.js +1 -2
  44. package/packages/daemon/dist/plugins/daemon-plugins.js +2 -10
  45. package/packages/daemon/dist/restore.js +57 -40
  46. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  47. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  48. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  49. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  50. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  51. package/packages/daemon/dist/terminal/mirror/session-channel.js +13 -12
  52. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +123 -25
  53. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  54. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  55. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +30 -2
  56. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  57. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  58. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  59. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  60. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  61. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  62. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  63. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  64. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  65. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  66. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +35 -5
  67. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  68. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  69. package/packages/daemon/src/command-center/automation.ts +1 -1
  70. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  71. package/packages/daemon/src/command-center/discovery.ts +35 -2
  72. package/packages/daemon/src/command-center/server.ts +22 -8
  73. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  74. package/packages/daemon/src/command-center/tmux-servers.ts +7 -1
  75. package/packages/daemon/src/doctor.ts +164 -45
  76. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  77. package/packages/daemon/src/lib/cli-command.ts +16 -0
  78. package/packages/daemon/src/lib/daemon-embed.ts +176 -64
  79. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  80. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  81. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  82. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  83. package/packages/daemon/src/lib/log.ts +18 -1
  84. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  85. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  86. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  87. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  88. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  89. package/packages/daemon/src/lib/tmux-pane-reader.ts +145 -0
  90. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  91. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  92. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +41 -35
  94. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  95. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  96. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  97. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  98. package/packages/daemon/src/open-browser.ts +59 -18
  99. package/packages/daemon/src/open-reader.ts +148 -0
  100. package/packages/daemon/src/plugins/cli.ts +1 -2
  101. package/packages/daemon/src/plugins/daemon-plugins.ts +2 -12
  102. package/packages/daemon/src/restore.ts +80 -44
  103. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  104. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  105. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  106. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  107. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  108. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  109. package/packages/daemon/src/terminal/mirror/session-channel.ts +15 -14
  110. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +140 -23
  111. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  112. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  113. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +41 -1
  114. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  115. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  116. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  117. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  118. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  119. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  120. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  121. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  122. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  123. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  124. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  125. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +58 -6
  126. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  127. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  128. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  129. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  130. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
  131. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -365,6 +365,23 @@ export interface RestoreOptions {
365
365
  runCommands?: boolean;
366
366
  /** Relaunch resumable agent panes (`--resume-agents`); ORed with config default. */
367
367
  resumeAgents?: boolean;
368
+ /** Read this snapshot file instead of `~/.tmux-ide/snapshot.json` (`--from`). */
369
+ from?: string;
370
+ /** Rebuild every session from the snapshot, never from its workspace config. */
371
+ snapshotOnly?: boolean;
372
+ /** OR `resumeAgents` with the config default (default true). The upgrade passes false. */
373
+ resumeFromConfig?: boolean;
374
+ }
375
+
376
+ /** What one restore run did; sessions that threw while rebuilding are in `failed`. */
377
+ export interface RestoreOutcome {
378
+ snapshot: FleetSnapshot;
379
+ plan: RestorePlan;
380
+ restored: string[];
381
+ launched: string[];
382
+ resumed: ResumedSession[];
383
+ failed: string[];
384
+ resumeAgents: boolean;
368
385
  }
369
386
 
370
387
  /** One rebuilt session's resumed agent panes (for the report). */
@@ -380,75 +397,88 @@ interface ResumedSession {
380
397
  * (flag ORed with the `~/.tmux-ide/config.json` default) revives agent
381
398
  * conversations via `claude --resume <id>`.
382
399
  */
383
- export async function restore({
400
+ export async function restore(options: RestoreOptions = {}): Promise<void> {
401
+ const { json = false, dryRun = false } = options;
402
+ const outcome = await restoreFleet(options);
403
+ reportPlan(outcome.plan, outcome.snapshot, { ...outcome, json, dryRun });
404
+ if (outcome.failed.length) {
405
+ throw new IdeError(`could not rebuild ${outcome.failed.join(", ")}`, {
406
+ code: "RESTORE_FAILED",
407
+ exitCode: 1,
408
+ });
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Rebuild the fleet without printing. One session failing to rebuild does not
414
+ * stop the rest; it is listed in `failed`.
415
+ */
416
+ export async function restoreFleet({
384
417
  json = false,
385
418
  dryRun = false,
386
419
  runCommands = false,
387
420
  resumeAgents = false,
388
- }: RestoreOptions = {}): Promise<void> {
389
- const snapshot = readSnapshot();
421
+ from,
422
+ snapshotOnly = false,
423
+ resumeFromConfig = true,
424
+ }: RestoreOptions = {}): Promise<RestoreOutcome> {
425
+ const snapshot = readSnapshot(from);
390
426
  if (!snapshot) {
391
427
  throw new IdeError(
392
- "no snapshot yet — the updater writes one every ~30s while any session is adopted",
428
+ from
429
+ ? `no readable snapshot at ${from}`
430
+ : "no snapshot yet — the updater writes one every ~30s while any session is adopted",
393
431
  { code: "NO_SNAPSHOT", exitCode: 1 },
394
432
  );
395
433
  }
396
434
 
397
435
  // The flag forces resume on; config makes it the default. No negative flag.
398
- const resume = resumeAgents || readRestorePrefs().resumeAgents;
399
- const plan = buildRestorePlan(snapshot, liveSessions(), ideBackedProjects());
400
-
401
- if (dryRun) {
402
- reportPlan(plan, snapshot, {
403
- json,
404
- dryRun: true,
405
- restored: [],
406
- launched: [],
407
- resumed: [],
408
- resumeAgents: resume,
409
- });
410
- return;
411
- }
436
+ const resume = resumeAgents || (resumeFromConfig && readRestorePrefs().resumeAgents);
437
+ const plan = buildRestorePlan(
438
+ snapshot,
439
+ liveSessions(),
440
+ snapshotOnly ? new Map() : ideBackedProjects(),
441
+ );
442
+ const outcome: RestoreOutcome = {
443
+ snapshot,
444
+ plan,
445
+ restored: [],
446
+ launched: [],
447
+ resumed: [],
448
+ failed: [],
449
+ resumeAgents: resume,
450
+ };
451
+ if (dryRun) return outcome;
412
452
 
413
- const restored: string[] = [];
414
- const launched: string[] = [];
415
- const resumed: ResumedSession[] = [];
416
453
  const recordResumed = (session: string, panes: string[]) => {
417
- if (panes.length) resumed.push({ session, panes });
454
+ if (panes.length) outcome.resumed.push({ session, panes });
455
+ };
456
+ const rebuild = (session: SessionSnapshot) => {
457
+ try {
458
+ recordResumed(session.name, rebuildSession(session, { runCommands, resumeAgents: resume }));
459
+ } catch {
460
+ outcome.failed.push(session.name);
461
+ return;
462
+ }
463
+ if (session.adopted) safeAdopt(session.name);
464
+ outcome.restored.push(session.name);
418
465
  };
419
466
  for (const action of plan.actions) {
420
467
  if (action.kind === "skip") continue;
421
468
  if (action.kind === "launch") {
422
469
  const ok = await launchProject(action.dir, json);
423
- if (ok) launched.push(action.session);
470
+ if (ok) outcome.launched.push(action.session);
424
471
  else {
425
472
  // Launch failed — fall back to a raw rebuild from the snapshot so the
426
473
  // session still comes back.
427
474
  const snap = snapshot.sessions.find((s) => s.name === action.session);
428
- if (snap) {
429
- recordResumed(snap.name, rebuildSession(snap, { runCommands, resumeAgents: resume }));
430
- if (snap.adopted) safeAdopt(snap.name);
431
- restored.push(action.session);
432
- }
475
+ if (snap) rebuild(snap);
433
476
  }
434
477
  continue;
435
478
  }
436
- recordResumed(
437
- action.session.name,
438
- rebuildSession(action.session, { runCommands, resumeAgents: resume }),
439
- );
440
- if (action.session.adopted) safeAdopt(action.session.name);
441
- restored.push(action.session.name);
479
+ rebuild(action.session);
442
480
  }
443
-
444
- reportPlan(plan, snapshot, {
445
- json,
446
- dryRun: false,
447
- restored,
448
- launched,
449
- resumed,
450
- resumeAgents: resume,
451
- });
481
+ return outcome;
452
482
  }
453
483
 
454
484
  /** Adopt a restored session into the chrome; never let a chrome failure abort restore. */
@@ -488,12 +518,14 @@ interface ReportContext {
488
518
  resumed: ResumedSession[];
489
519
  /** Whether resume is on (drives the dry-run `(would resume N agents)` note). */
490
520
  resumeAgents: boolean;
521
+ /** Sessions whose rebuild threw. */
522
+ failed: string[];
491
523
  }
492
524
 
493
525
  function reportPlan(
494
526
  plan: RestorePlan,
495
527
  snapshot: FleetSnapshot,
496
- { json, dryRun, restored, launched, resumed, resumeAgents }: ReportContext,
528
+ { json, dryRun, restored, launched, resumed, resumeAgents, failed }: ReportContext,
497
529
  ): void {
498
530
  const skipped = plan.actions.filter((a) => a.kind === "skip").map((a) => a.session);
499
531
  const willLaunch = plan.actions.filter((a) => a.kind === "launch").map((a) => a.session);
@@ -513,6 +545,7 @@ function reportPlan(
513
545
  resumeAgents,
514
546
  resumedPanes,
515
547
  resumed,
548
+ failed,
516
549
  },
517
550
  null,
518
551
  2,
@@ -553,5 +586,8 @@ function reportPlan(
553
586
  parts.push(`rebuilt ${restored.map((s) => `${s}${resumeSuffix(s)}`).join(", ")}`);
554
587
  if (launched.length) parts.push(`launched ${launched.join(", ")}`);
555
588
  if (skipped.length) parts.push(`skipped ${skipped.join(", ")} (already running)`);
589
+ if (failed.length) parts.push(`failed to rebuild ${failed.join(", ")}`);
590
+ // Name the snapshot's age: an old snapshot brings back an old fleet (#766).
591
+ console.log(`Snapshot saved ${snapshot.savedAt}.`);
556
592
  console.log(parts.length ? `Restored: ${parts.join("; ")}` : "Nothing to restore.");
557
593
  }
@@ -3,6 +3,7 @@ import type { Socket } from "node:net";
3
3
  import { WebSocketServer } from "ws";
4
4
  import { PANE_STREAM_REDEEM_PATH, PANE_STREAM_WEBSOCKET_SUBPROTOCOL } from "@tmux-ide/contracts";
5
5
  import type { DirectTerminalSocket } from "../terminal/attachments/direct-websocket.ts";
6
+ import { daemonWebSocketHeartbeat, type WebSocketHeartbeat } from "./websocket-heartbeat.ts";
6
7
  import {
7
8
  PANE_STREAM_MAX_CONTROL_BYTES,
8
9
  PANE_STREAM_MAX_REDEMPTION_BYTES,
@@ -60,6 +61,7 @@ export function attachPaneStreamWebSocket(
60
61
  coordinator: PaneStreamAdmissionCoordinator,
61
62
  redemptionPath: string = PANE_STREAM_REDEEM_PATH,
62
63
  isCurrent: () => boolean = () => true,
64
+ heartbeat: WebSocketHeartbeat = daemonWebSocketHeartbeat(),
63
65
  ): PaneStreamWebSocketBoundary {
64
66
  const wss = new WebSocketServer({
65
67
  noServer: true,
@@ -74,6 +76,9 @@ export function attachPaneStreamWebSocket(
74
76
  },
75
77
  });
76
78
 
79
+ // Old clients ignore the header and answer the pings by protocol.
80
+ wss.on("headers", (headers) => heartbeat.advertise(headers));
81
+
77
82
  const upgrade = (
78
83
  request: import("node:http").IncomingMessage,
79
84
  socket: Socket,
@@ -140,6 +145,7 @@ export function attachPaneStreamWebSocket(
140
145
  wss.handleUpgrade(request, socket, head, (ws) => {
141
146
  socket.off("close", cancelUnbound);
142
147
  socket.off("error", cancelUnbound);
148
+ heartbeat.watch(ws, `pane-stream ${redemptionPath}`);
143
149
  decision.admission.bind(ws as unknown as DirectTerminalSocket);
144
150
  });
145
151
  } catch {
@@ -0,0 +1,135 @@
1
+ import {
2
+ WEBSOCKET_HEARTBEAT_HEADER,
3
+ WEBSOCKET_HEARTBEAT_INTERVAL_MS,
4
+ WEBSOCKET_HEARTBEAT_MAX_INTERVAL_MS,
5
+ WEBSOCKET_HEARTBEAT_MIN_INTERVAL_MS,
6
+ WEBSOCKET_HEARTBEAT_MISSED_LIMIT,
7
+ formatWebSocketHeartbeatHeader,
8
+ type WebSocketHeartbeatPolicy,
9
+ } from "@tmux-ide/contracts";
10
+ import { logger } from "../lib/log.ts";
11
+
12
+ /** The part of a `ws` socket the heartbeat needs. */
13
+ export interface HeartbeatSocket {
14
+ ping(): void;
15
+ terminate(): void;
16
+ on(event: "pong" | "close", listener: () => void): unknown;
17
+ off(event: "pong" | "close", listener: () => void): unknown;
18
+ }
19
+
20
+ export interface WebSocketHeartbeat {
21
+ readonly policy: WebSocketHeartbeatPolicy;
22
+ /** Start pinging this socket; it leaves by itself when it closes. */
23
+ watch(socket: HeartbeatSocket, label: string): void;
24
+ /** `ws` "headers" listener: advertises the cadence on the upgrade response. */
25
+ advertise(headers: string[]): void;
26
+ readonly watched: number;
27
+ /** True while the one shared timer exists, i.e. while anything is watched. */
28
+ readonly ticking: boolean;
29
+ }
30
+
31
+ /**
32
+ * One timer for every watched socket, and none while nothing is watched: an
33
+ * idle daemon with no clients pays nothing. Each tick sends one ping frame
34
+ * (2 bytes) per connection and reads back one pong (6 bytes); a socket that
35
+ * answered none of `missedLimit` consecutive pings is terminated, which lets
36
+ * the owning transport release its leases through its ordinary close path.
37
+ */
38
+ export function createWebSocketHeartbeat(
39
+ policy: WebSocketHeartbeatPolicy = {
40
+ intervalMs: WEBSOCKET_HEARTBEAT_INTERVAL_MS,
41
+ missedLimit: WEBSOCKET_HEARTBEAT_MISSED_LIMIT,
42
+ },
43
+ ): WebSocketHeartbeat {
44
+ const sockets = new Map<HeartbeatSocket, { unanswered: number; label: string }>();
45
+ let timer: ReturnType<typeof setInterval> | null = null;
46
+ const tick = (): void => {
47
+ for (const [socket, state] of [...sockets]) {
48
+ if (state.unanswered >= policy.missedLimit) {
49
+ logger.warn("websocket-heartbeat", "peer answered no ping; connection dropped", {
50
+ connection: state.label,
51
+ unansweredPings: state.unanswered,
52
+ intervalMs: policy.intervalMs,
53
+ });
54
+ forget(socket);
55
+ try {
56
+ socket.terminate();
57
+ } catch {
58
+ /* Already gone. */
59
+ }
60
+ continue;
61
+ }
62
+ state.unanswered += 1;
63
+ try {
64
+ socket.ping();
65
+ } catch {
66
+ /* A socket that cannot be pinged is closing; its close event removes it. */
67
+ }
68
+ }
69
+ };
70
+ const listeners = new Map<HeartbeatSocket, { pong: () => void; close: () => void }>();
71
+ const forget = (socket: HeartbeatSocket): void => {
72
+ const attached = listeners.get(socket);
73
+ if (attached) {
74
+ socket.off("pong", attached.pong);
75
+ socket.off("close", attached.close);
76
+ listeners.delete(socket);
77
+ }
78
+ sockets.delete(socket);
79
+ if (sockets.size === 0 && timer) {
80
+ clearInterval(timer);
81
+ timer = null;
82
+ }
83
+ };
84
+ return {
85
+ policy,
86
+ watch(socket, label) {
87
+ if (sockets.has(socket)) return;
88
+ const state = { unanswered: 0, label };
89
+ sockets.set(socket, state);
90
+ const attached = {
91
+ pong: () => {
92
+ state.unanswered = 0;
93
+ },
94
+ close: () => forget(socket),
95
+ };
96
+ listeners.set(socket, attached);
97
+ socket.on("pong", attached.pong);
98
+ socket.on("close", attached.close);
99
+ if (!timer) {
100
+ timer = setInterval(tick, policy.intervalMs);
101
+ timer.unref?.();
102
+ }
103
+ },
104
+ advertise(headers) {
105
+ headers.push(`${WEBSOCKET_HEARTBEAT_HEADER}: ${formatWebSocketHeartbeatHeader(policy)}`);
106
+ },
107
+ get watched() {
108
+ return sockets.size;
109
+ },
110
+ get ticking() {
111
+ return timer !== null;
112
+ },
113
+ };
114
+ }
115
+
116
+ /** Soaks and tests may shorten the interval; anything out of range keeps the default. */
117
+ export function heartbeatPolicyFromEnvironment(
118
+ environment: NodeJS.ProcessEnv = process.env,
119
+ ): WebSocketHeartbeatPolicy {
120
+ const configured = Number(environment.TMUX_IDE_WS_HEARTBEAT_INTERVAL_MS);
121
+ const intervalMs =
122
+ Number.isSafeInteger(configured) &&
123
+ configured >= WEBSOCKET_HEARTBEAT_MIN_INTERVAL_MS &&
124
+ configured <= WEBSOCKET_HEARTBEAT_MAX_INTERVAL_MS
125
+ ? configured
126
+ : WEBSOCKET_HEARTBEAT_INTERVAL_MS;
127
+ return { intervalMs, missedLimit: WEBSOCKET_HEARTBEAT_MISSED_LIMIT };
128
+ }
129
+
130
+ let shared: WebSocketHeartbeat | null = null;
131
+ /** The daemon process's single heartbeat: every route shares its one timer. */
132
+ export function daemonWebSocketHeartbeat(): WebSocketHeartbeat {
133
+ shared ??= createWebSocketHeartbeat(heartbeatPolicyFromEnvironment());
134
+ return shared;
135
+ }
@@ -111,11 +111,17 @@ const ERROR_MESSAGES: Readonly<Record<NativeTerminalAttachmentRuntimeErrorCode,
111
111
 
112
112
  export class NativeTerminalAttachmentRuntimeError extends Error {
113
113
  readonly code: NativeTerminalAttachmentRuntimeErrorCode;
114
+ /**
115
+ * Which of the several origins of this code it was. For diagnostics only:
116
+ * the message a client sees stays the same.
117
+ */
118
+ readonly detail: string | undefined;
114
119
 
115
- constructor(code: NativeTerminalAttachmentRuntimeErrorCode) {
120
+ constructor(code: NativeTerminalAttachmentRuntimeErrorCode, detail?: string) {
116
121
  super(ERROR_MESSAGES[code]);
117
122
  this.name = "NativeTerminalAttachmentRuntimeError";
118
123
  this.code = code;
124
+ this.detail = detail;
119
125
  }
120
126
  }
121
127
 
@@ -730,7 +736,10 @@ async function requiredTmuxResult(
730
736
  const result = await runner.run({ executable: "tmux", argv }, signal);
731
737
  if (result.status === "not-found") return null;
732
738
  if (result.status !== "ok") {
733
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
739
+ throw new NativeTerminalAttachmentRuntimeError(
740
+ "discovery-failed",
741
+ `tmux-command-${result.status}`,
742
+ );
734
743
  }
735
744
  return result.stdout;
736
745
  }
@@ -919,6 +928,18 @@ function parsePaneSnapshot(
919
928
  * before any pane query, and a second identity/topology snapshot closes races.
920
929
  */
921
930
  const INVENTORY_FENCE_ATTEMPTS = 4;
931
+ /**
932
+ * A read that was overtaken by an inventory invalidation is not a failed
933
+ * read: the answer it was computing is simply out of date, so it is read
934
+ * again. One retry was not enough while tmux topology is in motion: creating
935
+ * an agent pane invalidates the inventory several times within a few hundred
936
+ * milliseconds, a read overtaken twice failed with "discovery-failed", the
937
+ * inventory route answered 503, and a click on the new agent's row landed on
938
+ * "That agent changed or disappeared" until the client's backoff recovered
939
+ * seconds later (#764, journey soak 43257599866). Still bounded: a server
940
+ * whose topology never stops moving must not hold a reader for ever.
941
+ */
942
+ export const INVENTORY_STALE_RETRIES = 4;
922
943
  /** 25, 50, 100 ms: enough for a mutation's identity stamps, bounded for every reader. */
923
944
  const settleDelay = (attempt: number) =>
924
945
  new Promise<void>((resolve) => setTimeout(resolve, 25 * 2 ** (attempt - 1)));
@@ -977,12 +998,17 @@ export async function discoverWorkspaceRegistryTerminalInventory(
977
998
  for (let attempt = 0; attempt < INVENTORY_FENCE_ATTEMPTS && !stable; attempt += 1) {
978
999
  if (attempt > 0) await settleDelay(attempt);
979
1000
  const after = await requiredTmuxResult(runner, argv, signal);
980
- if (after === null) throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1001
+ if (after === null)
1002
+ throw new NativeTerminalAttachmentRuntimeError(
1003
+ "discovery-failed",
1004
+ "session-vanished-mid-read",
1005
+ );
981
1006
  const next = parsePaneSnapshot(after, identity);
982
1007
  if (matches(previous, next)) stable = next;
983
1008
  else previous = next;
984
1009
  }
985
- if (!stable) throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1010
+ if (!stable)
1011
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "topology-not-settled");
986
1012
  bySessionName.set(sessionName, stable.panes);
987
1013
  }
988
1014
 
@@ -1609,15 +1635,23 @@ export class WorkspaceTerminalInventoryRuntime {
1609
1635
  snapshot = await this.#readInventoryAttempt(signal);
1610
1636
  } catch (error) {
1611
1637
  if (this.#inventoryEpoch !== epoch) {
1612
- if (staleRetry < 1) return this.#readInventory(signal, staleRetry + 1);
1613
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1638
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1639
+ return this.#readInventory(signal, staleRetry + 1);
1640
+ throw new NativeTerminalAttachmentRuntimeError(
1641
+ "discovery-failed",
1642
+ "overtaken-by-invalidations",
1643
+ );
1614
1644
  }
1615
1645
  throw error;
1616
1646
  }
1617
1647
  if (signal.aborted) throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
1618
1648
  if (this.#inventoryEpoch !== epoch) {
1619
- if (staleRetry < 1) return this.#readInventory(signal, staleRetry + 1);
1620
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1649
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1650
+ return this.#readInventory(signal, staleRetry + 1);
1651
+ throw new NativeTerminalAttachmentRuntimeError(
1652
+ "discovery-failed",
1653
+ "overtaken-by-invalidations",
1654
+ );
1621
1655
  }
1622
1656
  return this.#publishInventory(snapshot, nativeEpoch, signal, epoch);
1623
1657
  }
@@ -1629,14 +1663,22 @@ export class WorkspaceTerminalInventoryRuntime {
1629
1663
  value = await this.#readInventoryAttempt(abort.signal);
1630
1664
  } catch (error) {
1631
1665
  if (abort.signal.aborted || this.#inventoryEpoch !== epoch) {
1632
- if (staleRetry < 1) return this.#readInventory(undefined, staleRetry + 1);
1633
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1666
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1667
+ return this.#readInventory(undefined, staleRetry + 1);
1668
+ throw new NativeTerminalAttachmentRuntimeError(
1669
+ "discovery-failed",
1670
+ "overtaken-by-invalidations",
1671
+ );
1634
1672
  }
1635
1673
  throw error;
1636
1674
  }
1637
1675
  if (abort.signal.aborted || this.#inventoryEpoch !== epoch) {
1638
- if (staleRetry < 1) return this.#readInventory(undefined, staleRetry + 1);
1639
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1676
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1677
+ return this.#readInventory(undefined, staleRetry + 1);
1678
+ throw new NativeTerminalAttachmentRuntimeError(
1679
+ "discovery-failed",
1680
+ "overtaken-by-invalidations",
1681
+ );
1640
1682
  }
1641
1683
  return this.#publishInventory(value, nativeEpoch, abort.signal, epoch);
1642
1684
  })().finally(() => {
@@ -1703,9 +1745,11 @@ export class WorkspaceTerminalInventoryRuntime {
1703
1745
  const retryIfReplaced = (): Promise<NativeTerminalRuntimeSessionSnapshot | null> | null => {
1704
1746
  assertLive();
1705
1747
  if (this.#inventoryEpoch === epoch) return null;
1706
- if (staleRetry < 1)
1748
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1707
1749
  return this.#discoverTerminalRuntimeSession(requestedSessionName, signal, staleRetry + 1);
1708
- return Promise.reject(new NativeTerminalAttachmentRuntimeError("discovery-failed"));
1750
+ return Promise.reject(
1751
+ new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations"),
1752
+ );
1709
1753
  };
1710
1754
  assertLive();
1711
1755
  const nativeEpoch = this.#nativeServerEpoch?.() ?? null;
@@ -92,6 +92,8 @@ export type MirrorPaneEvent =
92
92
  /** One visible pane rectangle inside a layout event, in window cells. */
93
93
  export interface MirrorLayoutPane {
94
94
  browserIcon?: string | null;
95
+ /** A live Markdown reader pane; the path is daemon-only and never framed. */
96
+ reader?: { name: string; path: string } | null;
95
97
  /** Null while the pane's semantic identity join is still unverified. */
96
98
  semanticPaneId: string | null;
97
99
  /** Daemon-authored presentation; clients never infer this from terminal bytes. */
@@ -11,3 +11,14 @@ export function layoutContentRows(
11
11
  const touchesStatusEdge = border === "top" ? paneTop === 0 : paneTop + paneHeight === windowRows;
12
12
  return paneHeight - (touchesStatusEdge ? 1 : 0);
13
13
  }
14
+
15
+ /**
16
+ * The status line a window's tiled panes have, from its `pane-border-status`.
17
+ * tmux 3.8's `top-floating` and `bottom-floating` put a status line on floating
18
+ * panes only (`window_get_pane_status`), so tiled panes are laid out as "off".
19
+ * Null for a value this daemon does not know.
20
+ */
21
+ export function tiledPaneBorderStatus(option: string | undefined): "off" | "top" | "bottom" | null {
22
+ if (option === "off" || option === "top" || option === "bottom") return option;
23
+ return option === "top-floating" || option === "bottom-floating" ? "off" : null;
24
+ }
@@ -71,6 +71,8 @@ export interface MirrorServiceOptions {
71
71
  /** True only when the server positively lacks the native commands: a stock tmux. */
72
72
  splitLayoutStock?: () => Promise<boolean>;
73
73
  onSharedWindowConflict?: (session: string, conflicted: boolean) => void;
74
+ /** #764 diagnostics: the registered-window guard's lifecycle and pushes. */
75
+ onWindowOwnershipDiagnostic?: (phase: string, details?: Record<string, unknown>) => void;
74
76
  createOwnedViewerAdapter?: (session: string) => OwnedViewerAdapter | undefined;
75
77
  nativeServerIdentity?: import("../../lib/tmux-server-generation-runner.ts").NativeTmuxServerIdentity;
76
78
  resolveSocketPath?: () => string;
@@ -180,6 +182,9 @@ interface ChannelEntry {
180
182
  retired: boolean;
181
183
  }
182
184
 
185
+ /** Backoff for re-reading registered windows after a failed read (#764). */
186
+ const OWNERSHIP_RETRY_MS = [100, 250, 500, 1_000] as const;
187
+
183
188
  export class MirrorService {
184
189
  private readonly opts: MirrorServiceOptions;
185
190
  private readonly channels = new Map<string, ChannelEntry>();
@@ -205,24 +210,71 @@ export class MirrorService {
205
210
  }
206
211
 
207
212
  private invalidateRegisteredWindows(): void {
213
+ this.opts.onWindowOwnershipDiagnostic?.("guard-invalidate", {
214
+ wasPending: this.registeredWindows?.pending() ?? null,
215
+ });
208
216
  this.registeredWindows?.invalidate();
209
217
  }
210
218
 
219
+ /**
220
+ * #764: a failed re-read must not leave every session "being verified"
221
+ * for good. Nothing else re-reads until the next operation, so retry with
222
+ * a short bounded backoff while a channel is retained; success pushes
223
+ * any conflict as usual.
224
+ */
225
+ private ownershipRetries = 0;
226
+ private ownershipRetry: ReturnType<typeof setTimeout> | null = null;
227
+ private retryRegisteredWindows(guard: RegisteredWindowGuard): void {
228
+ if (this.ownershipRetry || this.disposed || guard !== this.registeredWindows) return;
229
+ if (this.channelSessions.size === 0) return;
230
+ const delay =
231
+ OWNERSHIP_RETRY_MS[Math.min(this.ownershipRetries, OWNERSHIP_RETRY_MS.length - 1)]!;
232
+ this.ownershipRetries += 1;
233
+ this.ownershipRetry = setTimeout(() => {
234
+ this.ownershipRetry = null;
235
+ if (this.disposed || guard !== this.registeredWindows || !guard.pending()) return;
236
+ void this.verifyRegisteredWindows().catch(() => {});
237
+ }, delay);
238
+ this.ownershipRetry.unref?.();
239
+ }
240
+
211
241
  async verifyRegisteredWindows(): Promise<void> {
212
242
  const guard = this.registeredWindows;
213
243
  if (!guard) return;
214
- await guard.verify();
244
+ const diagnostic = this.opts.onWindowOwnershipDiagnostic;
245
+ diagnostic?.("guard-verify-start", { pending: guard.pending() });
246
+ try {
247
+ await guard.verify();
248
+ } catch (error) {
249
+ const detail = (error as { detail?: unknown } | null)?.detail;
250
+ diagnostic?.("guard-verify-failed", {
251
+ reason: error instanceof Error ? error.message.slice(0, 200) : "unknown",
252
+ // Which origin of the failure it was, when the thrower said so.
253
+ ...(typeof detail === "string" ? { detail: detail.slice(0, 80) } : {}),
254
+ });
255
+ this.retryRegisteredWindows(guard);
256
+ throw error;
257
+ }
258
+ this.ownershipRetries = 0;
215
259
  if (guard !== this.registeredWindows || this.disposed)
216
260
  throw new Error("Window ownership changed during discovery");
261
+ const blocked: string[] = [];
217
262
  for (const [channel, session] of this.channelSessions) {
218
263
  if (guard.blocked(session)) {
264
+ blocked.push(session);
219
265
  channel.setGeometryParticipation(false);
220
266
  if (!this.registeredConflicts.has(session)) {
221
267
  this.registeredConflicts.add(session);
268
+ diagnostic?.("guard-conflict-push", { session });
222
269
  this.opts.onSharedWindowConflict?.(session, true);
223
270
  }
224
- } else this.registeredConflicts.delete(session);
271
+ } else if (this.registeredConflicts.delete(session)) {
272
+ // The registered-window conflict cleared: report it like a shared-window
273
+ // clear, so idle clients re-read the inventory (perf plan F13).
274
+ this.opts.onSharedWindowConflict?.(session, false);
275
+ }
225
276
  }
277
+ diagnostic?.("guard-verify-ok", { blocked, channels: this.channelSessions.size });
226
278
  }
227
279
  private readonly pendingDisposals = new Set<Promise<void>>();
228
280
  private readonly drainingChannels = new Map<string, Promise<void>>();
@@ -605,6 +657,7 @@ export class MirrorService {
605
657
  const session = this.channelSessions.get(peer);
606
658
  if (session === undefined) continue;
607
659
  if (conflict) peer.setGeometryParticipation(false);
660
+ this.opts.onWindowOwnershipDiagnostic?.("membership-conflict-push", { session, conflict });
608
661
  this.opts.onSharedWindowConflict?.(session, conflict);
609
662
  }
610
663
  }
@@ -729,6 +782,8 @@ export class MirrorService {
729
782
 
730
783
  async dispose(): Promise<void> {
731
784
  this.disposed = true;
785
+ if (this.ownershipRetry) clearTimeout(this.ownershipRetry);
786
+ this.ownershipRetry = null;
732
787
  this.registeredWindows?.dispose();
733
788
  this.sessionExitListeners.clear();
734
789
  const entries = [...this.channels.values()];
@@ -793,6 +848,10 @@ export class MirrorService {
793
848
  hasSharedWindowConflict: () => this.hasSharedWindowConflict(session),
794
849
  beforeIdentityRepair: () => this.verifyRegisteredWindows(),
795
850
  onWindowTopologyChanged: () => {
851
+ this.opts.onWindowOwnershipDiagnostic?.("topology-notification", {
852
+ session,
853
+ current: this.channelSessions.has(channel),
854
+ });
796
855
  if (this.channelSessions.has(channel)) this.invalidateRegisteredWindows();
797
856
  },
798
857
  ownedViewer,