tmux-ide 2.9.22 → 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 (85) hide show
  1. package/bin/cli.js +3434 -7568
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +1 -0
  4. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  5. package/packages/daemon/dist/command-center/automation.js +1 -1
  6. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  7. package/packages/daemon/dist/command-center/discovery.js +28 -2
  8. package/packages/daemon/dist/command-center/server.js +8 -2
  9. package/packages/daemon/dist/command-center/tmux-servers.js +1 -1
  10. package/packages/daemon/dist/doctor.js +41 -0
  11. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  12. package/packages/daemon/dist/lib/daemon-embed.js +111 -55
  13. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  14. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  15. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  16. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  17. package/packages/daemon/dist/lib/log.js +18 -1
  18. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  19. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  20. package/packages/daemon/dist/lib/tmux-pane-reader.js +4 -2
  21. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  22. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  23. package/packages/daemon/dist/lib/tmux-server-owner.js +29 -37
  24. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  25. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  26. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  27. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  29. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  30. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  31. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  32. package/packages/daemon/dist/plugins/cli.js +1 -2
  33. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  34. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  35. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  36. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  37. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  38. package/packages/daemon/dist/terminal/mirror/session-channel.js +9 -11
  39. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +111 -22
  40. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  41. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +23 -0
  42. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  43. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  44. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  45. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  46. package/packages/daemon/src/command-center/automation.ts +1 -1
  47. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  48. package/packages/daemon/src/command-center/discovery.ts +35 -2
  49. package/packages/daemon/src/command-center/server.ts +22 -8
  50. package/packages/daemon/src/command-center/tmux-servers.ts +1 -1
  51. package/packages/daemon/src/doctor.ts +46 -0
  52. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  53. package/packages/daemon/src/lib/daemon-embed.ts +159 -64
  54. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  55. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  56. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  57. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  58. package/packages/daemon/src/lib/log.ts +18 -1
  59. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  60. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  61. package/packages/daemon/src/lib/tmux-pane-reader.ts +4 -3
  62. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  63. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  64. package/packages/daemon/src/lib/tmux-server-owner.ts +32 -35
  65. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  66. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  67. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  68. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  69. package/packages/daemon/src/plugins/cli.ts +1 -2
  70. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  71. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  72. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  73. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  74. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  75. package/packages/daemon/src/terminal/mirror/session-channel.ts +9 -13
  76. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +125 -21
  77. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  78. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +31 -0
  79. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  80. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  81. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  82. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  83. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  84. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  85. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
@@ -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,
@@ -1,5 +1,5 @@
1
1
  import { STOCK_SPLIT_OPTIONS_FORMAT } from "../protocol/stock-split-resize.ts";
2
- import { layoutContentRows } from "./layout-content-rows.ts";
2
+ import { layoutContentRows, tiledPaneBorderStatus } from "./layout-content-rows.ts";
3
3
  import {
4
4
  decodeNativeAtomicSnapshot,
5
5
  decodeNativeAtomicDualSnapshot,
@@ -69,6 +69,7 @@ import {
69
69
  } from "../protocol/layout-parse.ts";
70
70
  import {
71
71
  SESSION_PANE_DESCRIPTOR_FORMAT,
72
+ sameSessionPaneInventory,
72
73
  SessionDescriptorDiscovery,
73
74
  decodeControlReplyUtf8,
74
75
  decodeTmuxArgument,
@@ -2953,7 +2954,7 @@ export class SessionChannel {
2953
2954
  }
2954
2955
  const windowOptionHint =
2955
2956
  name === "subscription-changed"
2956
- ? (/^tmux-ide-pane-borders\s+\$[0-9]+\s+(@[0-9]+)\s+[0-9]+\s+-\s*:\s*(?:top|bottom|off)\s*$/u.exec(
2957
+ ? (/^tmux-ide-pane-borders\s+\$[0-9]+\s+(@[0-9]+)\s+[0-9]+\s+-\s*:\s*(?:top|bottom|off|top-floating|bottom-floating)\s*$/u.exec(
2957
2958
  rest,
2958
2959
  ) ??
2959
2960
  /^tmux-ide-copy-keys\s+\$[0-9]+\s+(@[0-9]+)\s+[0-9]+\s+-\s*:\s*(?:emacs|vi)\s*$/u.exec(
@@ -3112,13 +3113,9 @@ export class SessionChannel {
3112
3113
  this.pendingLayoutOutput.get(change.windowId)?.layout !== pendingLayout
3113
3114
  )
3114
3115
  return;
3115
- const border = reply.lines[0];
3116
+ const border = tiledPaneBorderStatus(reply.lines[0]);
3116
3117
  const window = this.windowsByRuntime.get(change.windowId);
3117
- if (
3118
- !reply.ok ||
3119
- !window ||
3120
- (border !== "top" && border !== "bottom" && border !== "off")
3121
- ) {
3118
+ if (!reply.ok || !window || border === null) {
3122
3119
  this.scheduleSync();
3123
3120
  return;
3124
3121
  }
@@ -3540,9 +3537,7 @@ export class SessionChannel {
3540
3537
  `list-panes -s -t "${expectedRuntimeSessionId}" -F "${SESSION_PANE_DESCRIPTOR_FORMAT}"`,
3541
3538
  );
3542
3539
  const confirmedWindowStage = await this.stageWindows(expectedRuntimeSessionId);
3543
- const coherent =
3544
- beforeLines.length === afterLines.length &&
3545
- beforeLines.every((line, index) => line === afterLines[index]);
3540
+ const coherent = sameSessionPaneInventory(beforeLines, afterLines);
3546
3541
  if (
3547
3542
  windowStage.repairedIdentity ||
3548
3543
  confirmedWindowStage.repairedIdentity ||
@@ -3876,12 +3871,13 @@ export class SessionChannel {
3876
3871
  active = "",
3877
3872
  visible = "",
3878
3873
  zoomed = "",
3879
- borderStatus = "off",
3874
+ borderStatusRaw = "off",
3880
3875
  full = visible,
3881
3876
  modeKeys,
3882
3877
  indexRaw = "",
3883
3878
  ] = parts;
3884
3879
  const index = Number(indexRaw);
3880
+ const borderStatus = tiledPaneBorderStatus(borderStatusRaw);
3885
3881
  if (
3886
3882
  !/^@[0-9]+$/u.test(runtimeId) ||
3887
3883
  !/^(?:0|[1-9][0-9]*)$/u.test(indexRaw) ||
@@ -3889,7 +3885,7 @@ export class SessionChannel {
3889
3885
  seenIndexes.has(index) ||
3890
3886
  (active !== "0" && active !== "1") ||
3891
3887
  (zoomed !== "0" && zoomed !== "1") ||
3892
- (borderStatus !== "top" && borderStatus !== "bottom" && borderStatus !== "off") ||
3888
+ borderStatus === null ||
3893
3889
  (modeKeys !== undefined && modeKeys !== "emacs" && modeKeys !== "vi")
3894
3890
  ) {
3895
3891
  throw new Error(`window layout truth for ${this.opts.session} is malformed`);
@@ -31,6 +31,7 @@ import { PaneStreamLayoutSnapshotFrameSchemaZ, type WindowLinkTopology } from "@
31
31
  import type { TerminalDeliveryGraphics } from "../session-runtime/terminal-delivery-hub.ts";
32
32
  import { z } from "zod";
33
33
  import { logger } from "../../lib/log.ts";
34
+ import type { TmuxServerOwnerRetirement } from "../../lib/tmux-server-owners.ts";
34
35
  import {
35
36
  PANE_STREAM_MAX_HELD_DELTAS,
36
37
  PANE_STREAM_MAX_OUTPUT_BYTES,
@@ -132,6 +133,44 @@ import {
132
133
  export { PANE_STREAM_REDEEM_PATH, PANE_STREAM_WEBSOCKET_SUBPROTOCOL };
133
134
  export const PANE_STREAM_MAX_REDEMPTION_BYTES = 4 * 1024;
134
135
  export const PANE_STREAM_MAX_CONTROL_BYTES = 4 * 1024;
136
+
137
+ export interface PaneStreamShutdownClose {
138
+ readonly code: number;
139
+ readonly reason: "daemon-shutdown" | "tmux-server-retired" | "daemon-restarting";
140
+ }
141
+ /** The daemon process (or its whole generation) is going away. */
142
+ export const PANE_STREAM_DAEMON_SHUTDOWN_CLOSE: PaneStreamShutdownClose = Object.freeze({
143
+ code: 1001,
144
+ reason: "daemon-shutdown",
145
+ });
146
+ /**
147
+ * Only this tmux server owner was retired; the daemon is still up. 1012
148
+ * (service restart) asks the client to list the servers again and reconnect
149
+ * now, without the backoff a vanished daemon deserves (#840).
150
+ */
151
+ export const PANE_STREAM_OWNER_RETIRED_CLOSE: PaneStreamShutdownClose = Object.freeze({
152
+ code: 1012,
153
+ reason: "tmux-server-retired",
154
+ });
155
+ /**
156
+ * The process restarts its daemon generation in place (tmux server replaced,
157
+ * settings restart). A new generation follows at once, possibly on another
158
+ * port: read daemon.json again and reconnect now.
159
+ */
160
+ export const PANE_STREAM_DAEMON_RESTARTING_CLOSE: PaneStreamShutdownClose = Object.freeze({
161
+ code: 1012,
162
+ reason: "daemon-restarting",
163
+ });
164
+ /** What an owner's streams are told when it is disposed for this reason. */
165
+ export function paneStreamCloseForRetirement(
166
+ retirement: TmuxServerOwnerRetirement | undefined,
167
+ ): PaneStreamShutdownClose {
168
+ if (retirement === undefined || retirement === "shutdown")
169
+ return PANE_STREAM_DAEMON_SHUTDOWN_CLOSE;
170
+ return retirement === "generation-restart"
171
+ ? PANE_STREAM_DAEMON_RESTARTING_CLOSE
172
+ : PANE_STREAM_OWNER_RETIRED_CLOSE;
173
+ }
135
174
  export const PANE_STREAM_MAX_REDEMPTION_MS = 1_000;
136
175
 
137
176
  const WS_OPEN = 1;
@@ -731,17 +770,33 @@ export class PaneStreamAdmissionCoordinator {
731
770
  return this.#ledger.snapshot();
732
771
  }
733
772
 
734
- shutdown(): Promise<void> {
773
+ /**
774
+ * Close every stream and refuse new ones. The first caller decides what the
775
+ * clients are told: the daemon going away, or only this tmux server owner
776
+ * being retired while the daemon stays up (reconnect now).
777
+ */
778
+ shutdown(close: PaneStreamShutdownClose = PANE_STREAM_DAEMON_SHUTDOWN_CLOSE): Promise<void> {
735
779
  if (this.#shutdownPromise) return this.#shutdownPromise;
736
780
  this.#shuttingDown = true;
737
- this.#shutdownPromise = this.#finishShutdown();
781
+ // An idle daemon stopping is routine and stays out of the default log:
782
+ // `--headless --json` promises one status line on stdout. Streams that
783
+ // are actually closed, or an owner retired under a live daemon, are not.
784
+ const routine =
785
+ close.reason === "daemon-shutdown" && this.#live.size === 0 && this.#preAuth.size === 0;
786
+ logger[routine ? "debug" : "info"]("pane-stream", "coordinator shutdown", {
787
+ code: close.code,
788
+ reason: close.reason,
789
+ liveStreams: this.#live.size,
790
+ unredeemed: this.#preAuth.size,
791
+ });
792
+ this.#shutdownPromise = this.#finishShutdown(close);
738
793
  return this.#shutdownPromise;
739
794
  }
740
795
 
741
- async #finishShutdown(): Promise<void> {
742
- for (const admission of [...this.#preAuth]) admission.close(1001, "daemon-shutdown");
796
+ async #finishShutdown(close: PaneStreamShutdownClose): Promise<void> {
797
+ for (const admission of [...this.#preAuth]) admission.close(close.code, close.reason);
743
798
  await this.#exclusive(async () => {
744
- for (const connection of [...this.#live]) connection.close(1001, "daemon-shutdown");
799
+ for (const connection of [...this.#live]) connection.close(close.code, close.reason);
745
800
  for (const pending of [...this.#pending.values()]) await this.#retirePending(pending);
746
801
  });
747
802
  await Promise.all([...this.#retiringReleases]);
@@ -1205,6 +1260,8 @@ export class PaneStreamLiveConnection {
1205
1260
  #legacyInputActivated = false;
1206
1261
  #legacyGeometryActivated = false;
1207
1262
  #closed = false;
1263
+ #closeCause: { readonly cause: string; readonly error?: string } | null = null;
1264
+ #heldInput: boolean | null = null;
1208
1265
  #releasePromise: Promise<unknown> | null = null;
1209
1266
  #stopAuthoritySnapshots: (() => void) | null = null;
1210
1267
  #sharedClockOriginMicros: number | null = null;
@@ -1241,6 +1298,8 @@ export class PaneStreamLiveConnection {
1241
1298
  "panes-closed",
1242
1299
  "peer-closed",
1243
1300
  "daemon-shutdown",
1301
+ "tmux-server-retired",
1302
+ "daemon-restarting",
1244
1303
  "redemption-rejected",
1245
1304
  "unknown",
1246
1305
  ]).has(closeReason ?? "")
@@ -1258,6 +1317,8 @@ export class PaneStreamLiveConnection {
1258
1317
  | "panes-closed"
1259
1318
  | "peer-closed"
1260
1319
  | "daemon-shutdown"
1320
+ | "tmux-server-retired"
1321
+ | "daemon-restarting"
1261
1322
  | "redemption-rejected"
1262
1323
  | "unknown";
1263
1324
  this.#observability.recordSpan(
@@ -1391,14 +1452,34 @@ export class PaneStreamLiveConnection {
1391
1452
  void this.#subscribeAll();
1392
1453
  }
1393
1454
 
1455
+ /**
1456
+ * 1011 "stream-unavailable" has ten different origins and the client is told
1457
+ * none of them. The log says which one, with the error text, so a stream
1458
+ * that "just closed" can be traced without a reproduction.
1459
+ */
1460
+ #fail(cause: string, error?: unknown): void {
1461
+ if (this.#closed) return;
1462
+ this.#closeCause = {
1463
+ cause,
1464
+ ...(error === undefined
1465
+ ? {}
1466
+ : { error: (error instanceof Error ? error.message : String(error)).slice(0, 300) }),
1467
+ };
1468
+ this.close(1011, "stream-unavailable");
1469
+ }
1470
+
1394
1471
  close(code = 1000, reason = "stream-closed"): void {
1395
1472
  if (this.#closed) return;
1396
1473
  this.#recordDiagnosticLifecycle("pane-stream-terminal", code, reason);
1397
1474
  logger.info("pane-stream", "stream closed", {
1398
1475
  code,
1399
1476
  reason,
1477
+ ...(this.#closeCause ?? {}),
1400
1478
  session: this.#descriptor.sessionName,
1401
1479
  clientId: this.#clientId,
1480
+ // Whether this connection held input when it went: the next stream of
1481
+ // the same client can only be granted input once that is released.
1482
+ ...(this.#heldInput === null ? {} : { heldInput: this.#heldInput }),
1402
1483
  });
1403
1484
  this.#closed = true;
1404
1485
  for (const demand of this.#surfaceDemands.values()) demand.close();
@@ -1468,8 +1549,8 @@ export class PaneStreamLiveConnection {
1468
1549
  let described: MirrorSessionDescription;
1469
1550
  try {
1470
1551
  described = await this.#mirror.describeSession(this.#descriptor.sessionName);
1471
- } catch {
1472
- this.close(1011, "stream-unavailable");
1552
+ } catch (error) {
1553
+ this.#fail("describe-session-failed", error);
1473
1554
  return;
1474
1555
  }
1475
1556
  if (this.#closed) return;
@@ -1489,8 +1570,8 @@ export class PaneStreamLiveConnection {
1489
1570
  return;
1490
1571
  }
1491
1572
  this.#layoutSubscription = layoutSubscription;
1492
- } catch {
1493
- this.close(1011, "stream-unavailable");
1573
+ } catch (error) {
1574
+ this.#fail("layout-subscribe-failed", error);
1494
1575
  return;
1495
1576
  }
1496
1577
  }
@@ -1514,8 +1595,8 @@ export class PaneStreamLiveConnection {
1514
1595
  continue;
1515
1596
  }
1516
1597
  channel.sub = sub;
1517
- } catch {
1518
- this.close(1011, "stream-unavailable");
1598
+ } catch (error) {
1599
+ this.#fail("pane-subscribe-failed", error);
1519
1600
  return;
1520
1601
  }
1521
1602
  }
@@ -1526,7 +1607,7 @@ export class PaneStreamLiveConnection {
1526
1607
  const binding = this.#sessionRuntimeBinding;
1527
1608
  const offer = this.#descriptor.terminalDelivery;
1528
1609
  if (!binding || !offer) {
1529
- this.close(1011, "stream-unavailable");
1610
+ this.#fail("no-session-runtime-binding");
1530
1611
  return;
1531
1612
  }
1532
1613
  // Layout authority covers the whole session, while content leases may select
@@ -1594,7 +1675,7 @@ export class PaneStreamLiveConnection {
1594
1675
  this.#failTopologyChanged();
1595
1676
  return;
1596
1677
  }
1597
- this.close(1011, "stream-unavailable");
1678
+ this.#fail("semantic-layout-subscribe-failed", cause);
1598
1679
  return;
1599
1680
  }
1600
1681
 
@@ -1652,7 +1733,13 @@ export class PaneStreamLiveConnection {
1652
1733
  )
1653
1734
  ) {
1654
1735
  await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
1655
- if (!this.#closed) this.close(1011, "stream-unavailable");
1736
+ if (!this.#closed) {
1737
+ const rejected = settled.find((result) => result.status === "rejected");
1738
+ this.#fail(
1739
+ "delivery-negotiation-failed",
1740
+ rejected?.status === "rejected" ? rejected.reason : "a pane's delivery offer was refused",
1741
+ );
1742
+ }
1656
1743
  return;
1657
1744
  }
1658
1745
 
@@ -2536,8 +2623,8 @@ export class PaneStreamLiveConnection {
2536
2623
  this.#sentBytesTotal += bytes;
2537
2624
  try {
2538
2625
  this.#socket.send(encoded, { binary });
2539
- } catch {
2540
- this.close(1011, "stream-unavailable");
2626
+ } catch (error) {
2627
+ this.#fail("socket-send-failed", error);
2541
2628
  return;
2542
2629
  }
2543
2630
  // Stall is judged on the drain tick, never synchronously at send: the
@@ -2579,7 +2666,7 @@ export class PaneStreamLiveConnection {
2579
2666
  if (this.#closed) return;
2580
2667
  const buffered = this.#socket.bufferedAmount ?? 0;
2581
2668
  if (!Number.isSafeInteger(buffered) || buffered < 0) {
2582
- this.close(1011, "stream-unavailable");
2669
+ this.#fail("socket-buffer-invalid");
2583
2670
  return;
2584
2671
  }
2585
2672
  if (buffered > this.#maxSocketBufferedBytes) {
@@ -3039,6 +3126,23 @@ export class PaneStreamLiveConnection {
3039
3126
  }
3040
3127
 
3041
3128
  #sendAuthoritySnapshot(snapshot: SessionRuntimeAuthoritySnapshot): void {
3129
+ // One line when this connection gains or loses input, and one for its
3130
+ // first snapshot: a stream that paints but never accepts keys shows up
3131
+ // here as "holdsInput false" with the client that holds it instead.
3132
+ const self = this.#sessionRuntimeBinding?.clientId ?? null;
3133
+ const holdsInput = self !== null && snapshot.owners.input === self;
3134
+ if (this.#heldInput !== holdsInput) {
3135
+ logger.info("pane-stream", "stream input authority", {
3136
+ session: this.#descriptor.sessionName,
3137
+ clientId: this.#clientId,
3138
+ connectionClientId: self,
3139
+ holdsInput,
3140
+ inputOwner: snapshot.owners.input,
3141
+ clients: snapshot.clients.length,
3142
+ revision: snapshot.revision,
3143
+ });
3144
+ this.#heldInput = holdsInput;
3145
+ }
3042
3146
  this.#sendFrame(null, { type: "authority-snapshot", snapshot });
3043
3147
  }
3044
3148
 
@@ -3377,8 +3481,8 @@ export class PaneStreamLiveConnection {
3377
3481
  }
3378
3482
  }
3379
3483
  }
3380
- } catch {
3381
- this.close(1011, "stream-unavailable");
3484
+ } catch (error) {
3485
+ this.#fail("control-frame-handler-failed", error);
3382
3486
  }
3383
3487
  }
3384
3488
 
@@ -3390,8 +3494,8 @@ export class PaneStreamLiveConnection {
3390
3494
  code,
3391
3495
  retryable: false,
3392
3496
  });
3393
- } catch {
3394
- this.close(1011, "stream-unavailable");
3497
+ } catch (error) {
3498
+ this.#fail("error-frame-send-failed", error);
3395
3499
  return;
3396
3500
  }
3397
3501
  this.close(1008, code);
@@ -8,6 +8,7 @@ import { PaneStreamLeaseManager } from "./lease-manager.ts";
8
8
  import {
9
9
  PaneStreamAdmissionCoordinator,
10
10
  type PaneStreamAdmissionCoordinatorOptions,
11
+ type PaneStreamShutdownClose,
11
12
  } from "./pane-stream-websocket.ts";
12
13
 
13
14
  export interface PaneStreamRuntimeOptions {
@@ -75,11 +76,12 @@ export class PaneStreamRuntime {
75
76
  });
76
77
  }
77
78
 
78
- dispose(): Promise<void> {
79
+ /** `close` says what the streams are told; the default is a daemon shutdown. */
80
+ dispose(close?: PaneStreamShutdownClose): Promise<void> {
79
81
  if (!this.#disposePromise) {
80
82
  this.#disposePromise = (async () => {
81
83
  this.nativeSurfaces?.close();
82
- await this.coordinator.shutdown();
84
+ await this.coordinator.shutdown(close);
83
85
  })();
84
86
  }
85
87
  return this.#disposePromise;
@@ -64,6 +64,37 @@ export const SESSION_PANE_DESCRIPTOR_FORMAT = [
64
64
  "#{pane_pid}",
65
65
  ].join("\t");
66
66
 
67
+ /**
68
+ * Descriptor fields the program in a pane changes whenever it likes: its
69
+ * command name, the window name tmux derives from it, and its title.
70
+ */
71
+ const VOLATILE_DESCRIPTOR_FIELDS: ReadonlySet<number> = new Set([
72
+ 4, // pane_current_command
73
+ 7, // window_name
74
+ 9, // pane_title
75
+ ]);
76
+
77
+ /**
78
+ * Whether two `list-panes` replies in SESSION_PANE_DESCRIPTOR_FORMAT describe
79
+ * the same panes. A busy pane changes its command and title between any two
80
+ * reads, which is not a pane set that is still changing: those fields are
81
+ * display text, read again on the next refresh (#730).
82
+ */
83
+ export function sameSessionPaneInventory(
84
+ before: readonly string[],
85
+ after: readonly string[],
86
+ ): boolean {
87
+ const stable = (line: string) =>
88
+ line
89
+ .split("\t")
90
+ .map((field, index) => (VOLATILE_DESCRIPTOR_FIELDS.has(index) ? "" : field))
91
+ .join("\t");
92
+ return (
93
+ before.length === after.length &&
94
+ before.every((line, index) => line === after[index] || stable(line) === stable(after[index]!))
95
+ );
96
+ }
97
+
67
98
  /** Decode the escapes emitted by tmux's `qa` format modifier. */
68
99
  export function decodeTmuxArgument(value: string): string {
69
100
  const encoded =
@@ -175,7 +175,12 @@ export interface StockSplitOptions extends StockSplitSizes {
175
175
  }
176
176
  export function parseStockSplitOptions(line: string | undefined): StockSplitOptions | null {
177
177
  const [borderStatus, scrollbars, style] = (line ?? "").split("\t");
178
- if (!/^(off|top|bottom)$/u.test(borderStatus ?? "") || !/^[a-z]+$/u.test(scrollbars ?? ""))
178
+ // The raw value stays: the guarded command compares it with the option. A
179
+ // floating value leaves tiled panes without a status line, like "off".
180
+ if (
181
+ !/^(off|top|bottom|top-floating|bottom-floating)$/u.test(borderStatus ?? "") ||
182
+ !/^[a-z]+$/u.test(scrollbars ?? "")
183
+ )
179
184
  return null;
180
185
  const field = (name: string) =>
181
186
  Number(new RegExp(`\\b${name}=(\\d+)`, "u").exec(style ?? "")?.[1] ?? 0);
@@ -115,6 +115,14 @@ export interface SessionRuntimeRegistryOptions {
115
115
  readonly observability?: SessionRuntimeObservability;
116
116
  /** Deterministic qualification seam; never invoked while observability is disabled. */
117
117
  readonly createTraceCorrelator?: (scheduler: SessionRuntimeScheduler) => RuntimeTraceCorrelator;
118
+ /**
119
+ * A session's terminal inventory may be readable again: a shared-window or
120
+ * registered-window conflict cleared, or its trusted inventory became
121
+ * qualified after it was not. The daemon publishes a
122
+ * terminal-runtime-inventory change so an idle client that met the 503
123
+ * re-reads at once; that read re-qualifies the session (perf plan F13, #764).
124
+ */
125
+ readonly onInventoryRecovered?: (session: string) => void;
118
126
  }
119
127
 
120
128
  /** Opaque daemon-internal proof that an inventory came from one exact runtime owner. */
@@ -324,6 +332,15 @@ export class SessionRuntimeRegistry implements PaneStreamMirror {
324
332
  readonly #scheduler: SessionRuntimeScheduler;
325
333
  readonly #observability: SessionRuntimeObservability;
326
334
  readonly #createTraceCorrelator: (scheduler: SessionRuntimeScheduler) => RuntimeTraceCorrelator;
335
+ readonly #onInventoryRecovered: ((session: string) => void) | null;
336
+
337
+ #announceInventory(session: string): void {
338
+ try {
339
+ this.#onInventoryRecovered?.(session);
340
+ } catch {
341
+ // A publication failure never changes qualification.
342
+ }
343
+ }
327
344
  readonly #sessions = new Map<string, SessionRuntime>();
328
345
  #listenerDisposal: ListenerDisposalSummary | null = null;
329
346
  readonly #proofPrewarmOwnership = new Map<SessionRuntime, { owned: boolean; claims: number }>();
@@ -342,6 +359,7 @@ export class SessionRuntimeRegistry implements PaneStreamMirror {
342
359
  this.#observability = options.observability ?? DISABLED_SESSION_RUNTIME_OBSERVABILITY;
343
360
  this.#createTraceCorrelator =
344
361
  options.createTraceCorrelator ?? ((scheduler) => new RuntimeTraceCorrelator(scheduler));
362
+ this.#onInventoryRecovered = options.onInventoryRecovered ?? null;
345
363
  const diagnosticMirrorOptions: Partial<MirrorServiceOptions> = {
346
364
  onInputAccepted: (session, action, acceptedAtMicros, ok) => {
347
365
  for (const traceId of action.traceIds ?? []) {
@@ -474,6 +492,9 @@ export class SessionRuntimeRegistry implements PaneStreamMirror {
474
492
  onSharedWindowConflict: (session, conflict) => {
475
493
  options.mirror?.onSharedWindowConflict?.(session, conflict);
476
494
  if (conflict) this.#sessions.get(session)?.invalidateSharedWindowAuthority();
495
+ // A cleared conflict is the trigger an idle client needs: nobody else
496
+ // may read the inventory, and the client's re-read re-qualifies it.
497
+ else if (!this.#mirror.hasSharedWindowConflict(session)) this.#announceInventory(session);
477
498
  },
478
499
  onNativeClientActivity: (session) => {
479
500
  options.mirror?.onNativeClientActivity?.(session);
@@ -573,7 +594,9 @@ export class SessionRuntimeRegistry implements PaneStreamMirror {
573
594
  }
574
595
  signal?.throwIfAborted();
575
596
  await abortable(this.#mirror.verifyRegisteredWindows(), signal);
597
+ const wasQualified = runtime.trustedInventoryQualified();
576
598
  runtime.qualifyTrustedInventory(runtimeSessionId);
599
+ if (!wasQualified && runtime.trustedInventoryQualified()) this.#announceInventory(session);
577
600
  } finally {
578
601
  this.#releaseProofPrewarmRuntime(runtime);
579
602
  }
@@ -117,6 +117,8 @@ export interface SessionRuntimeStageSpan {
117
117
  | "panes-closed"
118
118
  | "peer-closed"
119
119
  | "daemon-shutdown"
120
+ | "tmux-server-retired"
121
+ | "daemon-restarting"
120
122
  | "redemption-rejected"
121
123
  | "unknown";
122
124
  readonly deliveryVisibility?: "visible" | "background" | "hidden" | "frozen";