tmux-ide 2.9.24 → 2.9.26

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 (77) hide show
  1. package/bin/cli.js +1689 -393
  2. package/package.json +5 -2
  3. package/packages/contracts/src/pane-stream.ts +72 -0
  4. package/packages/contracts/src/terminal-delivery.ts +8 -2
  5. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  6. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  7. package/packages/daemon/dist/command-center/discovery.js +24 -5
  8. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  9. package/packages/daemon/dist/command-center/server.js +81 -75
  10. package/packages/daemon/dist/command-center/tmux-servers.js +17 -7
  11. package/packages/daemon/dist/doctor.js +46 -10
  12. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  13. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  14. package/packages/daemon/dist/lib/daemon-embed.js +6 -0
  15. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  16. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  17. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  18. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  19. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  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/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  27. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  28. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  29. package/packages/daemon/dist/terminal/mirror/session-channel.js +31 -2
  30. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  31. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +831 -222
  32. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  33. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  34. package/packages/daemon/dist/terminal/session-runtime/registry.js +25 -2
  35. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +121 -6
  36. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +79 -2
  37. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  38. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  39. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  40. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  41. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  42. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  43. package/packages/daemon/src/command-center/discovery.ts +24 -4
  44. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  45. package/packages/daemon/src/command-center/server.ts +67 -67
  46. package/packages/daemon/src/command-center/tmux-servers.ts +19 -6
  47. package/packages/daemon/src/doctor.ts +50 -9
  48. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  49. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  50. package/packages/daemon/src/lib/daemon-embed.ts +22 -0
  51. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  52. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  53. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  54. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  55. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  56. package/packages/daemon/src/lib/update-check.ts +34 -0
  57. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  58. package/packages/daemon/src/lib/update.ts +58 -16
  59. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  60. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  61. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  62. package/packages/daemon/src/terminal/mirror/session-channel.ts +38 -2
  63. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  64. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +915 -236
  65. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  66. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  67. package/packages/daemon/src/terminal/session-runtime/registry.ts +36 -2
  68. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +136 -6
  69. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  70. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +76 -2
  71. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  72. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  73. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
  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-client/src/pane-stream-client.ts +47 -5
@@ -2,14 +2,14 @@ import { TERMINAL_SURFACE_MAX_CONTROL_BYTES, TERMINAL_SURFACE_CAPABILITY_VERSION
2
2
  import { NativeSurfaceViewer } from "../graphics/native-surface-viewer.js";
3
3
  import { compressGraphicsChunk } from "../graphics/compress-chunk.js";
4
4
  import { TERMINAL_GRAPHICS_COMPRESSED_CAPABILITY_VERSION, TERMINAL_GRAPHICS_COMPRESSED_LOCAL_CAPABILITY_VERSION, TERMINAL_PROJECTION_CAPABILITY_VERSION, TERMINAL_PROJECTION_LOCAL_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
5
- import { PANE_STREAM_INPUT_LIFETIME_CAPABILITY_VERSION, PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION, PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION, PANE_STREAM_READER_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
5
+ import { PANE_STREAM_INPUT_LIFETIME_CAPABILITY_VERSION, PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION, PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION, PANE_STREAM_READER_CAPABILITY_VERSION, PANE_STREAM_BROWSER_KIND_CAPABILITY_VERSION, PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION, PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
6
6
  import { inflateSync } from "node:zlib";
7
7
  import { PaneStreamLayoutSnapshotFrameSchemaZ } from "@tmux-ide/contracts";
8
8
  import { z } from "zod";
9
9
  import { logger } from "../../lib/log.js";
10
10
  import { PANE_STREAM_MAX_HELD_DELTAS, PANE_STREAM_MAX_OUTPUT_BYTES, PANE_STREAM_MAX_PANES, PANE_STREAM_MAX_SEED_BYTES, PANE_STREAM_PROTOCOL_VERSION, PANE_STREAM_REDEEM_PATH, PANE_STREAM_WEBSOCKET_SUBPROTOCOL, TERMINAL_GRAPHICS_BLOB_CHUNK_BYTES, TERMINAL_DELIVERY_BINARY_CAPABILITY_VERSION, TERMINAL_DELIVERY_BINARY_LOCAL_CAPABILITY_VERSION, TERMINAL_GRAPHICS_BINARY_CAPABILITY_VERSION, TERMINAL_GRAPHICS_LOCAL_CAPABILITY_VERSION, encodeTerminalGraphicsBinary, encodeTerminalDeliveryBinaryChunk, TERMINAL_GRAPHICS_CELL_PIXELS_CAPABILITY_VERSION, TERMINAL_GRAPHICS_PRECISE_PIXELS_CAPABILITY_VERSION, TERMINAL_GRAPHICS_LEGACY_MAX_IMAGE_BYTES, TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION, PaneStreamClientFrameSchemaZ, PaneStreamLoopbackWebSocketUrlSchemaZ, PaneStreamRedeemFrameSchemaZ, PaneStreamServerFrameSchemaZ, sharedMonotonicMicros, } from "@tmux-ide/contracts";
11
11
  import { canonicalOriginOrNull, digestSecret, digestsEqual, rawDataByteLength, rawDataToBuffer, safeCloseSocket, strictJsonParse, } from "../attachments/admission-util.js";
12
- import { SessionRuntimeControllerLeaseError } from "../session-runtime/registry.js";
12
+ import { SessionRuntimeControllerLeaseError, SessionRuntimeInputLifetimeEndedError, } from "../session-runtime/registry.js";
13
13
  import { terminalDeliveryObservationOrdinal } from "../session-runtime/terminal-delivery-observation-identity.js";
14
14
  import { PaneStreamLeaseError, } from "./lease-manager.js";
15
15
  import { DEFAULT_PANE_STREAM_FLOW_BUDGETS, PaneStreamWireLedger, } from "./wire-ledger.js";
@@ -164,6 +164,8 @@ export class PaneStreamAdmissionCoordinator {
164
164
  #redemptionTimeoutMs;
165
165
  #flowBudgets;
166
166
  #drainTickMs;
167
+ #openRetryDelaysMs;
168
+ #ownershipWaitMs;
167
169
  #maxSocketBufferedBytes;
168
170
  #maxInputFrames;
169
171
  #maxInputBytes;
@@ -199,6 +201,8 @@ export class PaneStreamAdmissionCoordinator {
199
201
  this.#flowBudgets = options.flowBudgets ?? DEFAULT_PANE_STREAM_FLOW_BUDGETS;
200
202
  this.#ledger = new PaneStreamWireLedger(this.#flowBudgets);
201
203
  this.#drainTickMs = boundedInteger(options.drainTickMs, 15, 1_000);
204
+ this.#openRetryDelaysMs = options.openRetryDelaysMs ?? PANE_STREAM_OPEN_RETRY_DELAYS_MS;
205
+ this.#ownershipWaitMs = options.ownershipWaitMs ?? PANE_STREAM_OWNERSHIP_WAIT_MS;
202
206
  this.#maxSocketBufferedBytes = boundedInteger(options.maxSocketBufferedBytes, 32 << 20, 256 << 20);
203
207
  this.#maxInputFrames = boundedInteger(options.maxInputFramesPerWindow, 16_384, 1 << 20);
204
208
  this.#maxInputBytes = boundedInteger(options.maxInputBytesPerWindow, 4 << 20, 64 << 20);
@@ -255,6 +259,16 @@ export class PaneStreamAdmissionCoordinator {
255
259
  throw new PaneStreamAdmissionError("pane-not-found", `The pane ${pane} is not present in the workspace session.`);
256
260
  }
257
261
  }
262
+ // #806: a stream for one window is issued for exactly that window's
263
+ // panes, as the trusted inventory places them now.
264
+ if (request.semanticWindowId !== undefined) {
265
+ const windowPanes = new Set(described.panes
266
+ .filter((pane) => pane.semanticWindowId === request.semanticWindowId)
267
+ .map((pane) => pane.semanticPaneId));
268
+ if (windowPanes.size !== request.panes.length ||
269
+ request.panes.some((pane) => !windowPanes.has(pane)))
270
+ throw new PaneStreamAdmissionError("pane-not-found", "The panes are not exactly the panes of that window of the workspace session.");
271
+ }
258
272
  const issued = await this.#leaseManager.issue(request, {
259
273
  requestId,
260
274
  projectIdentity,
@@ -480,6 +494,8 @@ export class PaneStreamAdmissionCoordinator {
480
494
  leaseManager: this.#leaseManager,
481
495
  ledger: this.#ledger,
482
496
  drainTickMs: this.#drainTickMs,
497
+ openRetryDelaysMs: this.#openRetryDelaysMs,
498
+ ownershipWaitMs: this.#ownershipWaitMs,
483
499
  maxSocketBufferedBytes: this.#maxSocketBufferedBytes,
484
500
  maxInputFrames: this.#maxInputFrames,
485
501
  maxInputBytes: this.#maxInputBytes,
@@ -658,6 +674,19 @@ class PreAuthAdmission {
658
674
  socket.off("error", this.#onClose);
659
675
  }
660
676
  }
677
+ /**
678
+ * How long an in-place topology change waits for the layout that matches the
679
+ * session's inventory, when the inventory read was newer than the layout in
680
+ * hand (a split and a close in quick succession). After it the stream closes
681
+ * as it would without capability 119.
682
+ */
683
+ export const PANE_STREAM_TOPOLOGY_SETTLE_MS = 500;
684
+ /** About half a second in all: long enough for one slow tmux answer, short for a user. */
685
+ export const PANE_STREAM_OPEN_RETRY_DELAYS_MS = [150, 400];
686
+ /** Input waits this long for ownership to be read again before the stream closes. */
687
+ export const PANE_STREAM_OWNERSHIP_WAIT_MS = 2_000;
688
+ /** At most this many input and geometry frames wait for it. */
689
+ export const PANE_STREAM_OWNERSHIP_HELD_FRAMES = 256;
661
690
  const GRAPHICS_MAX_QUEUED_DIGESTS = 256;
662
691
  /** Graphics state as renderers without zlib support must see it. */
663
692
  export function rawGraphicsState(state) {
@@ -699,6 +728,8 @@ export class PaneStreamLiveConnection {
699
728
  #leaseManager;
700
729
  #ledger;
701
730
  #drainTickMs;
731
+ #openRetryDelaysMs;
732
+ #ownershipWaitMs;
702
733
  #maxSocketBufferedBytes;
703
734
  #maxInputFrames;
704
735
  #maxInputBytes;
@@ -712,6 +743,13 @@ export class PaneStreamLiveConnection {
712
743
  #panes = new Map();
713
744
  #semanticLayouts = new Map();
714
745
  #semanticExpectedPaneIds = null;
746
+ /** Capability 119 (#723): a changed pane set is announced, not a reason to close. */
747
+ #topologyInPlace;
748
+ /** The stream was issued for every pane of its session: new panes join it. */
749
+ #leasesWholeSession = false;
750
+ #topologyReconciling = false;
751
+ #topologyPending = null;
752
+ #topologyWaiter = null;
715
753
  #semanticRuntimeSessionId = null;
716
754
  #semanticWindowLinks = null;
717
755
  #semanticTopologyEpoch = -1;
@@ -796,6 +834,8 @@ export class PaneStreamLiveConnection {
796
834
  this.#leaseManager = options.leaseManager;
797
835
  this.#ledger = options.ledger;
798
836
  this.#drainTickMs = options.drainTickMs;
837
+ this.#openRetryDelaysMs = options.openRetryDelaysMs;
838
+ this.#ownershipWaitMs = options.ownershipWaitMs ?? PANE_STREAM_OWNERSHIP_WAIT_MS;
799
839
  this.#maxSocketBufferedBytes = options.maxSocketBufferedBytes;
800
840
  this.#maxInputFrames = options.maxInputFrames;
801
841
  this.#maxInputBytes = options.maxInputBytes;
@@ -810,26 +850,11 @@ export class PaneStreamLiveConnection {
810
850
  : undefined;
811
851
  this.#diagnosticAfterFrameParse = options.diagnosticAfterFrameParse;
812
852
  this.#onRetire = options.onRetire;
813
- for (const pane of options.descriptor.panes) {
814
- this.#panes.set(pane, {
815
- semanticPaneId: pane,
816
- sub: null,
817
- delivery: null,
818
- deliveryAddress: null,
819
- serverSeq: 0,
820
- sentPaneFrames: 0,
821
- consumedSeq: 0,
822
- nextInputSeq: 1,
823
- frozenByWire: false,
824
- closed: false,
825
- batch: null,
826
- graphicsAnnounced: false,
827
- graphicsQueue: [],
828
- graphicsSending: false,
829
- graphicsServed: new Map(),
830
- graphicsState: null,
831
- });
832
- }
853
+ this.#topologyInPlace =
854
+ options.descriptor.terminalDelivery?.protocolVersions.some((version) => version === PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION ||
855
+ version === PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION) === true;
856
+ for (const pane of options.descriptor.panes)
857
+ this.#panes.set(pane, newPaneChannel(pane));
833
858
  }
834
859
  get clientId() {
835
860
  return this.#clientId;
@@ -853,6 +878,7 @@ export class PaneStreamLiveConnection {
853
878
  this.#descriptor.terminalDelivery?.protocolVersions.includes(PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION)
854
879
  ? { inputBytes: true }
855
880
  : {}),
881
+ ...(this.#topologyInPlace ? { topologyInPlace: true } : {}),
856
882
  protocolVersion: PANE_STREAM_PROTOCOL_VERSION,
857
883
  daemonInstanceId: this.#binding.daemonInstanceId,
858
884
  requestId: this.#binding.requestId,
@@ -867,7 +893,12 @@ export class PaneStreamLiveConnection {
867
893
  });
868
894
  this.#recordDiagnosticLifecycle("pane-stream-server-ready");
869
895
  }
870
- catch {
896
+ catch (error) {
897
+ // The one 1011 that still closed without a cause in the log.
898
+ this.#closeCause = {
899
+ cause: "ready-frame-failed",
900
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
901
+ };
871
902
  this.close(1011, "stream-unavailable-describe");
872
903
  return;
873
904
  }
@@ -906,8 +937,14 @@ export class PaneStreamLiveConnection {
906
937
  // Whether this connection held input when it went: the next stream of
907
938
  // the same client can only be granted input once that is released.
908
939
  ...(this.#heldInput === null ? {} : { heldInput: this.#heldInput }),
940
+ // Keys not delivered because their pane lifetime had ended (#397).
941
+ ...(this.#inputLifetimeEndedDropped > 0
942
+ ? { droppedEndedLifetimeInputs: this.#inputLifetimeEndedDropped }
943
+ : {}),
909
944
  });
910
945
  this.#closed = true;
946
+ this.#ownershipHeld.length = 0;
947
+ this.#ownershipWake?.();
911
948
  for (const demand of this.#surfaceDemands.values())
912
949
  demand.close();
913
950
  this.#surfaceDemands.clear();
@@ -974,7 +1011,7 @@ export class PaneStreamLiveConnection {
974
1011
  // is absence; a describe FAILURE is not and fails the connection).
975
1012
  let described;
976
1013
  try {
977
- described = await this.#mirror.describeSession(this.#descriptor.sessionName);
1014
+ described = await this.#retryOpenStep("describe-session", () => this.#mirror.describeSession(this.#descriptor.sessionName));
978
1015
  }
979
1016
  catch (error) {
980
1017
  this.#fail("describe-session-failed", error);
@@ -1030,6 +1067,37 @@ export class PaneStreamLiveConnection {
1030
1067
  }
1031
1068
  this.#closeIfAllPanesGone();
1032
1069
  }
1070
+ /**
1071
+ * One step of a stream's opening, tried again after a failure (#585): on a
1072
+ * loaded host one slow tmux answer failed the step, the step closed the whole
1073
+ * stream with 1011, and nothing was tried twice. A refusal of authority is a
1074
+ * decision, not a failure, and is never repeated. Each repeat is logged.
1075
+ */
1076
+ async #retryOpenStep(step, run, final = () => false) {
1077
+ for (let attempt = 0;; attempt += 1) {
1078
+ try {
1079
+ return await run();
1080
+ }
1081
+ catch (error) {
1082
+ const delayMs = this.#openRetryDelaysMs[attempt];
1083
+ if (delayMs === undefined ||
1084
+ this.#closed ||
1085
+ error instanceof SessionRuntimeControllerLeaseError ||
1086
+ final(error))
1087
+ throw error;
1088
+ logger.info("pane-stream", "stream open step failed; trying again", {
1089
+ session: this.#descriptor.sessionName,
1090
+ clientId: this.#clientId,
1091
+ step,
1092
+ attempt: attempt + 1,
1093
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
1094
+ });
1095
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1096
+ if (this.#closed)
1097
+ throw error;
1098
+ }
1099
+ }
1100
+ }
1033
1101
  async #subscribeSemantic(known) {
1034
1102
  const binding = this.#sessionRuntimeBinding;
1035
1103
  const offer = this.#descriptor.terminalDelivery;
@@ -1051,25 +1119,40 @@ export class PaneStreamLiveConnection {
1051
1119
  let stagedAuthority = null;
1052
1120
  let authorityMalformed = false;
1053
1121
  let layoutActivated = false;
1122
+ let layoutAttempt = 0;
1054
1123
  // Establish the single session layout observer first. MirrorService owns
1055
1124
  // this lifecycle and may share native control state with delivery setup;
1056
1125
  // only the independent pane delivery opens below are parallelized.
1057
1126
  try {
1058
- if (!this.#mirror.subscribeLayout)
1127
+ const subscribeLayout = this.#mirror.subscribeLayout?.bind(this.#mirror);
1128
+ if (!subscribeLayout)
1059
1129
  throw new Error("authoritative layout is unavailable");
1060
- const subscription = await this.#mirror.subscribeLayout(this.#descriptor.sessionName, () => undefined, {
1061
- expectedSemanticPaneIds: expectedPaneIds,
1062
- expectedRuntimeSessionId: this.#descriptor.runtimeSessionId,
1063
- onAuthority: (snapshot) => {
1064
- this.#recordDiagnosticLifecycle("pane-stream-layout-staged");
1065
- if (snapshot.layouts.length > PANE_STREAM_MAX_PANES)
1066
- authorityMalformed = true;
1067
- else if (!layoutActivated)
1068
- stagedAuthority = snapshot;
1069
- else
1070
- this.#onLayoutAuthority(snapshot);
1071
- },
1072
- });
1130
+ // The session's trusted inventory can be unsettled for a moment after a
1131
+ // pane change ("lacks verified identity"): a stream re-issued at once
1132
+ // closed 1011 while the next, 100 ms later, opened. Try again, as the
1133
+ // other opening steps do (#585). A changed pane set is a decision, not
1134
+ // a failure, and still closes 1012 at once. A try that failed is
1135
+ // disowned: its authority callback is ignored.
1136
+ const subscription = await this.#retryOpenStep("semantic-layout-subscribe", () => {
1137
+ const attempt = ++layoutAttempt;
1138
+ stagedAuthority = null;
1139
+ authorityMalformed = false;
1140
+ return subscribeLayout(this.#descriptor.sessionName, () => undefined, {
1141
+ expectedSemanticPaneIds: expectedPaneIds,
1142
+ expectedRuntimeSessionId: this.#descriptor.runtimeSessionId,
1143
+ onAuthority: (snapshot) => {
1144
+ if (attempt !== layoutAttempt)
1145
+ return;
1146
+ this.#recordDiagnosticLifecycle("pane-stream-layout-staged");
1147
+ if (snapshot.layouts.length > PANE_STREAM_MAX_PANES)
1148
+ authorityMalformed = true;
1149
+ else if (!layoutActivated)
1150
+ stagedAuthority = snapshot;
1151
+ else
1152
+ this.#onLayoutAuthority(snapshot);
1153
+ },
1154
+ });
1155
+ }, (error) => error instanceof Error && error.name === "MirrorTopologyChangedError");
1073
1156
  if (this.#closed) {
1074
1157
  await subscription.close().catch(() => undefined);
1075
1158
  return;
@@ -1114,28 +1197,7 @@ export class PaneStreamLiveConnection {
1114
1197
  // removes N x attachment latency without allowing a fast pane to make the
1115
1198
  // session look ready while a sibling is still missing. allSettled is
1116
1199
  // deliberate: partial success is always closed before the socket retires.
1117
- const openings = channels.map(async (channel) => {
1118
- const pending = [];
1119
- let ready = false;
1120
- let negotiated = false;
1121
- const delivery = await binding.openTerminalDelivery(channel.semanticPaneId, offer, (message) => {
1122
- if (!ready && !(negotiated && message.type === "terminal.delivery.fault"))
1123
- pending.push(message);
1124
- else
1125
- return this.#sendTerminalDelivery(channel.semanticPaneId, message);
1126
- }, this.#descriptor.workspaceName);
1127
- return {
1128
- channel,
1129
- delivery,
1130
- pending,
1131
- markNegotiated: () => {
1132
- negotiated = true;
1133
- },
1134
- markReady: () => {
1135
- ready = true;
1136
- },
1137
- };
1138
- });
1200
+ const openings = channels.map((channel) => this.#openPaneDelivery(binding, offer, channel));
1139
1201
  const settled = await Promise.allSettled(openings);
1140
1202
  const opened = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
1141
1203
  if (this.#closed ||
@@ -1147,27 +1209,7 @@ export class PaneStreamLiveConnection {
1147
1209
  }
1148
1210
  return;
1149
1211
  }
1150
- const deliveryIdentityChanged = opened.some(({ channel, delivery, pending }) => {
1151
- if (!delivery.negotiation.accepted)
1152
- return true;
1153
- const negotiated = delivery.negotiation.negotiated;
1154
- if (negotiated.generation !== this.#binding.daemonInstanceId)
1155
- return true;
1156
- let incarnation = null;
1157
- for (const message of pending) {
1158
- if (message.type !== "terminal.delivery" && message.type !== "terminal.projection")
1159
- continue;
1160
- if (message.workspaceName !== this.#descriptor.workspaceName ||
1161
- message.semanticPaneId !== channel.semanticPaneId ||
1162
- message.generation !== negotiated.generation ||
1163
- message.deliveryNonce !== negotiated.deliveryNonce ||
1164
- (incarnation !== null && message.incarnation !== incarnation))
1165
- return true;
1166
- incarnation = message.incarnation;
1167
- }
1168
- return false;
1169
- });
1170
- if (deliveryIdentityChanged) {
1212
+ if (opened.some((entry) => this.#deliveryIdentityChanged(entry))) {
1171
1213
  await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
1172
1214
  this.#failTopologyChanged();
1173
1215
  return;
@@ -1194,6 +1236,7 @@ export class PaneStreamLiveConnection {
1194
1236
  }
1195
1237
  this.#recordDiagnosticLifecycle("pane-stream-layout-validated");
1196
1238
  this.#semanticExpectedPaneIds = expectedPaneIds;
1239
+ this.#leasesWholeSession = expectedPaneIds.every((pane) => this.#panes.has(pane));
1197
1240
  this.#semanticRuntimeSessionId = authority.runtimeSessionId;
1198
1241
  this.#semanticWindowLinks = authority.windowLinks;
1199
1242
  this.#semanticTopologyEpoch = authority.topologyEpoch;
@@ -1214,6 +1257,60 @@ export class PaneStreamLiveConnection {
1214
1257
  const visibleAtDelivery = new Set(authority.layouts.flatMap((layout) => layout.currentWindow ? layout.panes.map((pane) => pane.semanticPaneId) : []));
1215
1258
  opened.sort((left, right) => Number(visibleAtDelivery.has(right.channel.semanticPaneId)) -
1216
1259
  Number(visibleAtDelivery.has(left.channel.semanticPaneId)));
1260
+ await this.#publishOpenedDeliveries(opened);
1261
+ this.#closeIfAllPanesGone();
1262
+ }
1263
+ /** Open one pane's delivery; its messages wait until the pane is announced. */
1264
+ async #openPaneDelivery(binding, offer, channel) {
1265
+ const pending = [];
1266
+ let ready = false;
1267
+ let negotiated = false;
1268
+ // #585: a failed open is tried again (150 ms, 400 ms) before the stream
1269
+ // closes; this applies to a pane added in place too.
1270
+ const delivery = await this.#retryOpenStep("pane-delivery-open", () => {
1271
+ // A try that failed may have delivered something; start clean.
1272
+ pending.length = 0;
1273
+ return binding.openTerminalDelivery(channel.semanticPaneId, offer, (message) => {
1274
+ if (!ready && !(negotiated && message.type === "terminal.delivery.fault"))
1275
+ pending.push(message);
1276
+ else
1277
+ return this.#sendTerminalDelivery(channel.semanticPaneId, message);
1278
+ }, this.#descriptor.workspaceName);
1279
+ });
1280
+ return {
1281
+ channel,
1282
+ delivery,
1283
+ pending,
1284
+ markNegotiated: () => {
1285
+ negotiated = true;
1286
+ },
1287
+ markReady: () => {
1288
+ ready = true;
1289
+ },
1290
+ };
1291
+ }
1292
+ #deliveryIdentityChanged({ channel, delivery, pending }) {
1293
+ if (!delivery.negotiation.accepted)
1294
+ return true;
1295
+ const negotiated = delivery.negotiation.negotiated;
1296
+ if (negotiated.generation !== this.#binding.daemonInstanceId)
1297
+ return true;
1298
+ let incarnation = null;
1299
+ for (const message of pending) {
1300
+ if (message.type !== "terminal.delivery" && message.type !== "terminal.projection")
1301
+ continue;
1302
+ if (message.workspaceName !== this.#descriptor.workspaceName ||
1303
+ message.semanticPaneId !== channel.semanticPaneId ||
1304
+ message.generation !== negotiated.generation ||
1305
+ message.deliveryNonce !== negotiated.deliveryNonce ||
1306
+ (incarnation !== null && message.incarnation !== incarnation))
1307
+ return true;
1308
+ incarnation = message.incarnation;
1309
+ }
1310
+ return false;
1311
+ }
1312
+ /** Announce validated deliveries, then replay what each collected meanwhile. */
1313
+ async #publishOpenedDeliveries(opened) {
1217
1314
  for (const { channel, delivery, markNegotiated } of opened) {
1218
1315
  if (this.#closed || channel.closed) {
1219
1316
  await delivery.close();
@@ -1260,9 +1357,43 @@ export class PaneStreamLiveConnection {
1260
1357
  markReady();
1261
1358
  this.#startGraphics(channel);
1262
1359
  }
1263
- this.#closeIfAllPanesGone();
1264
1360
  }
1361
+ /**
1362
+ * A tombstone ends a pane's delivery for good: the hub drops the pane and
1363
+ * sends nothing more. Without capability 119 the pane's removal closes the
1364
+ * stream anyway. With it, the removal arrives as a `topology` frame within
1365
+ * moments; if none comes, the pane is still in the session and would stay
1366
+ * blank for ever, so the stream closes as it would without the capability
1367
+ * and the client takes a new one.
1368
+ */
1369
+ #watchTombstone(pane) {
1370
+ const channel = this.#panes.get(pane);
1371
+ if (!this.#topologyInPlace || !channel || channel.closed)
1372
+ return;
1373
+ const timer = setTimeout(() => {
1374
+ if (this.#closed || channel.retiredInPlace || this.#panes.get(pane) !== channel)
1375
+ return;
1376
+ // A change being applied may be the one that removes this pane (kill-pane
1377
+ // plus split: the new pane's delivery can take longer to open than the
1378
+ // settle time). Decide again once it is done, with a fresh settle time.
1379
+ if (this.#topologyReconciling) {
1380
+ this.#tombstonesAfterChange.add(channel);
1381
+ return;
1382
+ }
1383
+ this.#failTopologyChanged("a pane that stays lost its source");
1384
+ }, PANE_STREAM_TOPOLOGY_SETTLE_MS);
1385
+ timer.unref?.();
1386
+ }
1387
+ /**
1388
+ * Tombstoned channels whose guard came due while a change was being applied.
1389
+ * The channel, not the pane id: a pane that left and came back within the
1390
+ * change has a fresh channel, which this tombstone is not about.
1391
+ */
1392
+ #tombstonesAfterChange = new Set();
1265
1393
  async #sendTerminalDelivery(pane, message) {
1394
+ if ((message.type === "terminal.delivery" || message.type === "terminal.projection") &&
1395
+ message.frame === "tombstone")
1396
+ this.#watchTombstone(pane);
1266
1397
  if (message.type === "terminal.projection") {
1267
1398
  const channel = this.#panes.get(pane);
1268
1399
  if (channel?.deliveryAddress)
@@ -1406,7 +1537,8 @@ export class PaneStreamLiveConnection {
1406
1537
  // when served.
1407
1538
  const zlib = this.#descriptor.terminalDelivery?.protocolVersions.some((version) => version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION ||
1408
1539
  version === PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION ||
1409
- version === PANE_STREAM_READER_CAPABILITY_VERSION) === true;
1540
+ version === PANE_STREAM_READER_CAPABILITY_VERSION ||
1541
+ version === PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION) === true;
1410
1542
  channel.graphicsZlib = zlib;
1411
1543
  channel.graphicsLocal =
1412
1544
  !!this.#localImages &&
@@ -1803,15 +1935,28 @@ export class PaneStreamLiveConnection {
1803
1935
  #onLayoutAuthority(snapshot) {
1804
1936
  if (this.#closed || !this.#semanticExpectedPaneIds || !this.#semanticRuntimeSessionId)
1805
1937
  return;
1806
- if (snapshot.session !== this.#descriptor.sessionName ||
1807
- snapshot.runtimeSessionId !== this.#semanticRuntimeSessionId ||
1808
- snapshot.topologyEpoch <= this.#semanticTopologyEpoch ||
1809
- snapshot.layouts.length > PANE_STREAM_MAX_PANES) {
1938
+ if (this.#topologyReconciling) {
1939
+ // One change at a time, and only the newest state is worth announcing.
1940
+ this.#topologyPending = snapshot;
1941
+ this.#topologyWaiter?.();
1942
+ return;
1943
+ }
1944
+ if (!this.#layoutAuthorityAdmissible(snapshot)) {
1810
1945
  this.#failTopologyChanged();
1811
1946
  return;
1812
1947
  }
1813
1948
  const frames = this.#validateInitialLayout(snapshot.layouts, this.#semanticExpectedPaneIds);
1949
+ // #806: a pane can also move between windows while the session keeps its
1950
+ // panes; for a stream of one window that changes its pane set.
1951
+ const windowChanged = frames !== null && this.#windowPaneSetChanged(snapshot);
1952
+ if ((!frames || windowChanged) && this.#topologyInPlace) {
1953
+ // The layout does not fit the pane set this stream knows. With
1954
+ // capability 119 that is a change to follow, not a reason to close.
1955
+ void this.#reconcileTopology(snapshot);
1956
+ return;
1957
+ }
1814
1958
  if (!frames ||
1959
+ windowChanged ||
1815
1960
  !PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
1816
1961
  type: "layout-snapshot",
1817
1962
  topologyEpoch: snapshot.topologyEpoch,
@@ -1821,27 +1966,299 @@ export class PaneStreamLiveConnection {
1821
1966
  this.#failTopologyChanged();
1822
1967
  return;
1823
1968
  }
1969
+ if (!this.#windowLinksAdmissible(snapshot)) {
1970
+ this.#failTopologyChanged();
1971
+ return;
1972
+ }
1973
+ this.#semanticWindowLinks = snapshot.windowLinks;
1974
+ this.#semanticTopologyEpoch = snapshot.topologyEpoch;
1975
+ this.#semanticLayouts.clear();
1976
+ for (const event of snapshot.layouts)
1977
+ this.#semanticLayouts.set(event.semanticWindowId, event);
1978
+ this.#sendFrame(null, {
1979
+ type: "layout-snapshot",
1980
+ topologyEpoch: snapshot.topologyEpoch,
1981
+ layouts: frames,
1982
+ windowLinks: snapshot.windowLinks,
1983
+ });
1984
+ }
1985
+ /** #806: the layout no longer shows this stream's window with exactly its panes. */
1986
+ #windowPaneSetChanged(snapshot) {
1987
+ const window = this.#descriptor.semanticWindowId;
1988
+ if (window === null)
1989
+ return false;
1990
+ const live = [...this.#panes.values()]
1991
+ .filter((channel) => !channel.closed)
1992
+ .map((channel) => channel.semanticPaneId);
1993
+ const shown = snapshot.layouts.find((event) => event.semanticWindowId === window);
1994
+ if (!shown)
1995
+ return true;
1996
+ const panes = shown.panes.map((pane) => pane.semanticPaneId ?? "");
1997
+ if (shown.zoomed)
1998
+ return panes.length !== 1 || !live.includes(panes[0]);
1999
+ return panes.length !== live.length || panes.some((pane) => !live.includes(pane));
2000
+ }
2001
+ /** The same session and runtime, a newer epoch, a layout a stream can carry. */
2002
+ #layoutAuthorityAdmissible(snapshot) {
2003
+ return (snapshot.session === this.#descriptor.sessionName &&
2004
+ snapshot.runtimeSessionId === this.#semanticRuntimeSessionId &&
2005
+ snapshot.topologyEpoch > this.#semanticTopologyEpoch &&
2006
+ snapshot.layouts.length <= PANE_STREAM_MAX_PANES);
2007
+ }
2008
+ #windowLinksAdmissible(snapshot) {
1824
2009
  const previousLinks = this.#semanticWindowLinks;
1825
- if (!previousLinks ||
2010
+ return !(!previousLinks ||
1826
2011
  snapshot.windowLinks.liveSessionId !== previousLinks.liveSessionId ||
1827
2012
  snapshot.windowLinks.linkRevision < previousLinks.linkRevision ||
1828
2013
  (snapshot.windowLinks.linkRevision === previousLinks.linkRevision &&
1829
2014
  JSON.stringify([...snapshot.windowLinks.links].sort((a, b) => a.linkId.localeCompare(b.linkId))) !==
1830
- JSON.stringify([...previousLinks.links].sort((a, b) => a.linkId.localeCompare(b.linkId))))) {
1831
- this.#failTopologyChanged();
1832
- return;
2015
+ JSON.stringify([...previousLinks.links].sort((a, b) => a.linkId.localeCompare(b.linkId)))));
2016
+ }
2017
+ /**
2018
+ * Capability 119 (#723). Follow a changed pane set without closing: one
2019
+ * change at a time, newest state only. Every doubt ends where a stream
2020
+ * without the capability ends, in `#failTopologyChanged()`.
2021
+ */
2022
+ async #reconcileTopology(first) {
2023
+ this.#topologyReconciling = true;
2024
+ let snapshot = first;
2025
+ try {
2026
+ for (;;) {
2027
+ this.#topologyPending = null;
2028
+ const outcome = await this.#applyTopology(snapshot);
2029
+ if (this.#closed)
2030
+ return;
2031
+ if (outcome === "failed")
2032
+ return this.#failTopologyChanged(this.#topologyFailure);
2033
+ let next = this.#topologyPending;
2034
+ if (outcome === "stale" && !next) {
2035
+ // The inventory was read after a further change: its layout follows.
2036
+ next = await this.#nextTopologySnapshot();
2037
+ if (this.#closed)
2038
+ return;
2039
+ if (!next)
2040
+ return this.#failTopologyChanged();
2041
+ }
2042
+ if (!next)
2043
+ return;
2044
+ if (!this.#layoutAuthorityAdmissible(next))
2045
+ return this.#failTopologyChanged();
2046
+ snapshot = next;
2047
+ }
2048
+ }
2049
+ finally {
2050
+ this.#topologyReconciling = false;
2051
+ this.#topologyPending = null;
2052
+ const tombstoned = [...this.#tombstonesAfterChange];
2053
+ this.#tombstonesAfterChange.clear();
2054
+ for (const channel of tombstoned)
2055
+ if (this.#panes.get(channel.semanticPaneId) === channel)
2056
+ this.#watchTombstone(channel.semanticPaneId);
2057
+ }
2058
+ }
2059
+ #nextTopologySnapshot() {
2060
+ if (this.#topologyPending)
2061
+ return Promise.resolve(this.#topologyPending);
2062
+ return new Promise((resolve) => {
2063
+ const finish = () => {
2064
+ clearTimeout(timer);
2065
+ this.#topologyWaiter = null;
2066
+ resolve(this.#topologyPending);
2067
+ };
2068
+ const timer = setTimeout(finish, PANE_STREAM_TOPOLOGY_SETTLE_MS);
2069
+ timer.unref?.();
2070
+ this.#topologyWaiter = finish;
2071
+ });
2072
+ }
2073
+ /**
2074
+ * "applied": the client was told and the stream goes on. "stale": this
2075
+ * layout does not fit the session's inventory as read now; a newer layout
2076
+ * decides. "failed": close.
2077
+ */
2078
+ async #applyTopology(snapshot) {
2079
+ const binding = this.#sessionRuntimeBinding;
2080
+ const offer = this.#descriptor.terminalDelivery;
2081
+ if (!binding ||
2082
+ !offer ||
2083
+ !this.#semanticExpectedPaneIds ||
2084
+ !this.#windowLinksAdmissible(snapshot))
2085
+ return this.#topologyFailed("not a semantic stream, or its window links changed");
2086
+ // A zoomed window lists one pane, so the layout alone cannot tell which
2087
+ // panes exist: the trusted inventory does.
2088
+ // The inventory is read by session NAME. Only an inventory that states
2089
+ // the runtime session this stream was issued for may extend the grant: a
2090
+ // session replaced under the same name is another session.
2091
+ let described;
2092
+ let inventoryIsThisSession = false;
2093
+ try {
2094
+ if (this.#mirror.describeSessionAuthority) {
2095
+ const authority = await this.#mirror.describeSessionAuthority(this.#descriptor.sessionName);
2096
+ if (authority.runtimeSessionId !== this.#semanticRuntimeSessionId)
2097
+ return this.#topologyFailed("inventory is of another runtime session");
2098
+ described = authority.description;
2099
+ inventoryIsThisSession = true;
2100
+ }
2101
+ else {
2102
+ described = await this.#mirror.describeSession(this.#descriptor.sessionName);
2103
+ }
2104
+ }
2105
+ catch (error) {
2106
+ return this.#topologyFailed("session inventory unavailable", error);
2107
+ }
2108
+ if (this.#closed)
2109
+ return this.#topologyFailed("closed");
2110
+ const next = [...new Set(described.panes.map((pane) => pane.semanticPaneId))].sort();
2111
+ if (next.length === 0)
2112
+ return this.#topologyFailed("session has no panes");
2113
+ const frames = this.#validateInitialLayout(snapshot.layouts, next);
2114
+ if (!frames)
2115
+ return "stale";
2116
+ if (!PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
2117
+ type: "layout-snapshot",
2118
+ topologyEpoch: snapshot.topologyEpoch,
2119
+ layouts: frames,
2120
+ windowLinks: snapshot.windowLinks,
2121
+ }).success)
2122
+ return this.#topologyFailed("layout snapshot invalid");
2123
+ // #806: a stream issued for one window follows that window's panes, as the
2124
+ // trusted inventory places them, and the same layout must show that window
2125
+ // with exactly those panes (a zoomed window shows one of them).
2126
+ const window = this.#descriptor.semanticWindowId;
2127
+ let windowPanes = null;
2128
+ if (window !== null) {
2129
+ windowPanes = [
2130
+ ...new Set(described.panes
2131
+ .filter((pane) => pane.semanticWindowId === window)
2132
+ .map((pane) => pane.semanticPaneId)),
2133
+ ].sort();
2134
+ if (windowPanes.length === 0)
2135
+ return this.#topologyFailed("the stream's window is gone");
2136
+ const shown = snapshot.layouts.find((event) => event.semanticWindowId === window);
2137
+ const shownPanes = (shown?.panes ?? []).map((pane) => pane.semanticPaneId ?? "");
2138
+ if (!shown ||
2139
+ (shown.zoomed
2140
+ ? shownPanes.length !== 1 || !windowPanes.includes(shownPanes[0])
2141
+ : shownPanes.length !== windowPanes.length ||
2142
+ shownPanes.some((pane) => !windowPanes.includes(pane))))
2143
+ return "stale";
2144
+ }
2145
+ const followed = windowPanes ?? next;
2146
+ const live = [...this.#panes.values()].filter((channel) => !channel.closed);
2147
+ const removed = live.filter((channel) => !followed.includes(channel.semanticPaneId));
2148
+ // A stream issued for the whole session follows it, and one issued for a
2149
+ // window follows that window; one issued for some panes keeps exactly those.
2150
+ const liveIds = new Set(live.map((channel) => channel.semanticPaneId));
2151
+ const added = windowPanes !== null || this.#leasesWholeSession
2152
+ ? followed.filter((pane) => !liveIds.has(pane))
2153
+ : [];
2154
+ if (added.length > 0 && !inventoryIsThisSession)
2155
+ return this.#topologyFailed("inventory cannot prove the runtime session");
2156
+ const remaining = live.length - removed.length + added.length;
2157
+ if (remaining === 0 || remaining > PANE_STREAM_MAX_PANES)
2158
+ return this.#topologyFailed("pane count outside the stream limit");
2159
+ // The transport's pane grant is exact. The daemon amends it from its own
2160
+ // inventory of this session before a new pane's delivery can open.
2161
+ if (added.length > 0) {
2162
+ try {
2163
+ if (!binding.amendPaneGrant)
2164
+ return this.#topologyFailed("transport cannot amend its grant");
2165
+ binding.amendPaneGrant({ added, removed: [] });
2166
+ }
2167
+ catch (error) {
2168
+ return this.#topologyFailed("pane grant refused", error);
2169
+ }
2170
+ }
2171
+ const channels = added.map(newPaneChannel);
2172
+ const settled = await Promise.allSettled(channels.map((channel) => this.#openPaneDelivery(binding, offer, channel)));
2173
+ const opened = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
2174
+ if (this.#closed ||
2175
+ opened.length !== channels.length ||
2176
+ opened.some((entry) => this.#deliveryIdentityChanged(entry))) {
2177
+ await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
2178
+ if (added.length > 0) {
2179
+ try {
2180
+ binding.amendPaneGrant?.({ added: [], removed: added });
2181
+ }
2182
+ catch {
2183
+ // The stream closes; its binding and grant go with it.
2184
+ }
2185
+ }
2186
+ const rejected = settled.find((result) => result.status === "rejected");
2187
+ return this.#topologyFailed(this.#closed
2188
+ ? "closed while opening"
2189
+ : rejected
2190
+ ? "delivery open rejected"
2191
+ : opened.some((entry) => !entry.delivery.negotiation.accepted)
2192
+ ? "delivery negotiation refused"
2193
+ : "delivery identity changed", rejected?.status === "rejected" ? rejected.reason : undefined);
2194
+ }
2195
+ // Commit. From here on nothing can fail the change.
2196
+ if (removed.length > 0) {
2197
+ try {
2198
+ binding.amendPaneGrant?.({
2199
+ added: [],
2200
+ removed: removed.map((channel) => channel.semanticPaneId),
2201
+ });
2202
+ }
2203
+ catch {
2204
+ // A pane that is gone cannot be used through a grant that lingers.
2205
+ }
1833
2206
  }
2207
+ for (const channel of removed)
2208
+ this.#retirePaneInPlace(channel);
2209
+ for (const channel of channels)
2210
+ this.#panes.set(channel.semanticPaneId, channel);
2211
+ this.#semanticExpectedPaneIds = next;
1834
2212
  this.#semanticWindowLinks = snapshot.windowLinks;
1835
2213
  this.#semanticTopologyEpoch = snapshot.topologyEpoch;
1836
2214
  this.#semanticLayouts.clear();
1837
2215
  for (const event of snapshot.layouts)
1838
2216
  this.#semanticLayouts.set(event.semanticWindowId, event);
2217
+ this.#sendFrame(null, {
2218
+ type: "topology",
2219
+ topologyEpoch: snapshot.topologyEpoch,
2220
+ panes: [...this.#panes.values()]
2221
+ .filter((channel) => !channel.closed)
2222
+ .map((channel) => channel.semanticPaneId),
2223
+ removed: removed.map((channel) => channel.semanticPaneId),
2224
+ added,
2225
+ });
1839
2226
  this.#sendFrame(null, {
1840
2227
  type: "layout-snapshot",
1841
2228
  topologyEpoch: snapshot.topologyEpoch,
1842
2229
  layouts: frames,
1843
2230
  windowLinks: snapshot.windowLinks,
1844
2231
  });
2232
+ await this.#publishOpenedDeliveries(opened);
2233
+ return "applied";
2234
+ }
2235
+ #topologyFailure = "";
2236
+ #topologyFailed(why, error) {
2237
+ this.#topologyFailure = error === undefined ? why : `${why}: ${String(error).slice(0, 200)}`;
2238
+ return "failed";
2239
+ }
2240
+ /** A pane that left the session: its delivery ends, the stream does not. */
2241
+ #retirePaneInPlace(channel) {
2242
+ const sub = channel.sub;
2243
+ const delivery = channel.delivery;
2244
+ channel.sub = null;
2245
+ channel.delivery = null;
2246
+ channel.closed = true;
2247
+ channel.retiredInPlace = true;
2248
+ // The channel stays only so late client frames for it are dropped; a long
2249
+ // stream under an agent that splits often must not keep each pane's buffers.
2250
+ channel.deliveryAddress = null;
2251
+ channel.batch = null;
2252
+ channel.graphicsQueue = [];
2253
+ channel.graphicsServed = new Map();
2254
+ channel.graphicsState = null;
2255
+ this.#surfaceDemands.get(channel.semanticPaneId)?.close();
2256
+ this.#surfaceDemands.delete(channel.semanticPaneId);
2257
+ if (sub)
2258
+ void sub.close().catch(() => undefined);
2259
+ if (delivery)
2260
+ void delivery.close().catch(() => undefined);
2261
+ this.#ledger.forgetPane(this.#clientId, channel.semanticPaneId);
1845
2262
  }
1846
2263
  #onLayout(event) {
1847
2264
  if (this.#closed)
@@ -1868,7 +2285,14 @@ export class PaneStreamLiveConnection {
1868
2285
  this.#sendFrame(null, frame);
1869
2286
  }
1870
2287
  #offers(version) {
1871
- return this.#descriptor.terminalDelivery?.protocolVersions.includes(version) === true;
2288
+ const offered = this.#descriptor.terminalDelivery?.protocolVersions;
2289
+ if (!offered)
2290
+ return false;
2291
+ // 120 stands for 118 and 119 together.
2292
+ return (offered.includes(version) ||
2293
+ ((version === PANE_STREAM_READER_CAPABILITY_VERSION ||
2294
+ version === PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION) &&
2295
+ offered.includes(PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION)));
1872
2296
  }
1873
2297
  #layoutFrame(event) {
1874
2298
  const frame = {
@@ -1892,6 +2316,9 @@ export class PaneStreamLiveConnection {
1892
2316
  ...(this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
1893
2317
  ? { reader: pane.reader ? { name: pane.reader.name } : null }
1894
2318
  : {}),
2319
+ ...(this.#offers(PANE_STREAM_BROWSER_KIND_CAPABILITY_VERSION)
2320
+ ? { browserKind: pane.browserKind ?? null }
2321
+ : {}),
1895
2322
  left: pane.left,
1896
2323
  top: pane.top,
1897
2324
  width: pane.width,
@@ -1938,9 +2365,12 @@ export class PaneStreamLiveConnection {
1938
2365
  return null;
1939
2366
  return frames;
1940
2367
  }
1941
- #failTopologyChanged() {
2368
+ /** `inPlaceFailure`: why a capability-119 stream could not follow the change. */
2369
+ #failTopologyChanged(inPlaceFailure) {
1942
2370
  if (this.#closed)
1943
2371
  return;
2372
+ if (inPlaceFailure)
2373
+ this.#closeCause = { cause: `topology-in-place: ${inPlaceFailure}` };
1944
2374
  this.#sendFrame(null, {
1945
2375
  type: "error",
1946
2376
  protocolVersion: PANE_STREAM_PROTOCOL_VERSION,
@@ -2144,22 +2574,28 @@ export class PaneStreamLiveConnection {
2144
2574
  if (!this.#acceptAuthorityGeneration(frame.generation))
2145
2575
  return;
2146
2576
  this.#usesExplicitAuthority = true;
2147
- if (!this.#sessionRuntimeBinding?.updatePresence)
2577
+ const binding = this.#sessionRuntimeBinding;
2578
+ if (!binding?.updatePresence)
2148
2579
  return this.#failProtocol("protocol-error");
2149
- const snapshot = this.#sessionRuntimeBinding.updatePresence(frame.state);
2150
- if (!this.#sessionRuntimeBinding.onAuthoritySnapshot)
2151
- this.#sendAuthoritySnapshot(snapshot);
2580
+ this.#afterHeldFrames(() => {
2581
+ const snapshot = binding.updatePresence(frame.state);
2582
+ if (!binding.onAuthoritySnapshot)
2583
+ this.#sendAuthoritySnapshot(snapshot);
2584
+ });
2152
2585
  return;
2153
2586
  }
2154
2587
  if (frame.type === "activity") {
2155
2588
  if (!this.#acceptAuthorityGeneration(frame.generation))
2156
2589
  return;
2157
2590
  this.#usesExplicitAuthority = true;
2158
- if (!this.#sessionRuntimeBinding?.noteActivity)
2591
+ const binding = this.#sessionRuntimeBinding;
2592
+ if (!binding?.noteActivity)
2159
2593
  return this.#failProtocol("protocol-error");
2160
- const snapshot = this.#sessionRuntimeBinding.noteActivity(frame.activity);
2161
- if (!this.#sessionRuntimeBinding.onAuthoritySnapshot)
2162
- this.#sendAuthoritySnapshot(snapshot);
2594
+ this.#afterHeldFrames(() => {
2595
+ const snapshot = binding.noteActivity(frame.activity);
2596
+ if (!binding.onAuthoritySnapshot)
2597
+ this.#sendAuthoritySnapshot(snapshot);
2598
+ });
2163
2599
  return;
2164
2600
  }
2165
2601
  if (frame.type === "authority-request") {
@@ -2169,44 +2605,57 @@ export class PaneStreamLiveConnection {
2169
2605
  if (!this.#sessionRuntimeBinding?.requestAuthority ||
2170
2606
  !this.#sessionRuntimeBinding.authoritySnapshot)
2171
2607
  return this.#failProtocol("protocol-error");
2172
- let lease = null;
2173
- try {
2174
- lease = this.#sessionRuntimeBinding.requestAuthority(frame.authority);
2175
- }
2176
- catch (error) {
2177
- // Topology changes can temporarily prevent ownership. Reject this
2178
- // request without letting an expected conflict terminate the daemon.
2179
- if (!(error instanceof SessionRuntimeControllerLeaseError) ||
2180
- error.code !== "controller-conflict")
2181
- return this.#failProtocol("input-rejected");
2182
- }
2183
- if (lease)
2184
- this.#requestedAuthorities.add(frame.authority);
2185
- this.#sendFrame(null, {
2186
- type: "authority-receipt",
2187
- requestId: frame.requestId,
2188
- authority: frame.authority,
2189
- status: lease ? "granted" : "rejected",
2190
- lease,
2191
- snapshot: this.#sessionRuntimeBinding.authoritySnapshot(),
2192
- });
2608
+ const binding = this.#sessionRuntimeBinding;
2609
+ // While ownership is read again the request waits for it, in order with
2610
+ // input, instead of being rejected: a rejected request left a new stream
2611
+ // without input until the client gave up on it.
2612
+ const request = () => {
2613
+ let lease = null;
2614
+ try {
2615
+ lease = binding.requestAuthority(frame.authority);
2616
+ }
2617
+ catch (error) {
2618
+ if (this.#holdForWindowOwnership(error, request))
2619
+ return;
2620
+ // Topology changes can temporarily prevent ownership. Reject this
2621
+ // request without letting an expected conflict terminate the daemon.
2622
+ if (!(error instanceof SessionRuntimeControllerLeaseError) ||
2623
+ error.code !== "controller-conflict")
2624
+ return this.#failProtocol("input-rejected");
2625
+ }
2626
+ if (lease)
2627
+ this.#requestedAuthorities.add(frame.authority);
2628
+ this.#sendFrame(null, {
2629
+ type: "authority-receipt",
2630
+ requestId: frame.requestId,
2631
+ authority: frame.authority,
2632
+ status: lease ? "granted" : "rejected",
2633
+ lease,
2634
+ snapshot: binding.authoritySnapshot(),
2635
+ });
2636
+ };
2637
+ this.#afterWindowOwnership(request);
2193
2638
  return;
2194
2639
  }
2195
2640
  if (frame.type === "authority-release") {
2196
2641
  if (!this.#acceptAuthorityGeneration(frame.generation))
2197
2642
  return;
2198
2643
  this.#usesExplicitAuthority = true;
2199
- this.#requestedAuthorities.delete(frame.authority);
2200
- if (!this.#sessionRuntimeBinding?.releaseAuthority)
2644
+ const binding = this.#sessionRuntimeBinding;
2645
+ if (!binding?.releaseAuthority)
2201
2646
  return this.#failProtocol("protocol-error");
2202
- const snapshot = this.#sessionRuntimeBinding.releaseAuthority(frame.authority);
2203
- this.#sendFrame(null, {
2204
- type: "authority-receipt",
2205
- requestId: frame.requestId,
2206
- authority: frame.authority,
2207
- status: "released",
2208
- lease: null,
2209
- snapshot,
2647
+ // After any held request or input: a release must not overtake them.
2648
+ this.#afterHeldFrames(() => {
2649
+ this.#requestedAuthorities.delete(frame.authority);
2650
+ const snapshot = binding.releaseAuthority(frame.authority);
2651
+ this.#sendFrame(null, {
2652
+ type: "authority-receipt",
2653
+ requestId: frame.requestId,
2654
+ authority: frame.authority,
2655
+ status: "released",
2656
+ lease: null,
2657
+ snapshot,
2658
+ });
2210
2659
  });
2211
2660
  return;
2212
2661
  }
@@ -2256,7 +2705,7 @@ export class PaneStreamLiveConnection {
2256
2705
  return;
2257
2706
  }
2258
2707
  if (frame.type === "semantic-intent") {
2259
- this.#acceptSemanticIntent(frame.operationId, frame.intent);
2708
+ this.#afterHeldFrames(() => this.#acceptSemanticIntent(frame.operationId, frame.intent));
2260
2709
  return;
2261
2710
  }
2262
2711
  if (frame.type === "terminal-surface-watch") {
@@ -2413,35 +2862,40 @@ export class PaneStreamLiveConnection {
2413
2862
  if (!this.#prepareInputAuthority(true))
2414
2863
  return;
2415
2864
  this.#nextViewportSeq += 1;
2416
- try {
2417
- if (frame.semanticWindowId === undefined)
2418
- this.#sessionRuntimeBinding.fitViewport(frame.authorityLease, frame.cols, frame.rows);
2419
- else
2420
- this.#sessionRuntimeBinding.fitViewport(frame.authorityLease, frame.cols, frame.rows, frame.semanticWindowId);
2421
- this.#sendFrame(null, {
2422
- type: "viewport-ack",
2423
- seq: frame.seq,
2424
- cols: frame.cols,
2425
- rows: frame.rows,
2426
- outcome: "ok",
2427
- authorityLease: frame.authorityLease,
2428
- });
2429
- }
2430
- catch (error) {
2431
- if (error instanceof SessionRuntimeControllerLeaseError &&
2432
- (error.code === "invalid-client-capability" || error.code === "stale-controller-lease")) {
2865
+ const fit = () => {
2866
+ try {
2867
+ if (frame.semanticWindowId === undefined)
2868
+ this.#sessionRuntimeBinding.fitViewport(frame.authorityLease, frame.cols, frame.rows);
2869
+ else
2870
+ this.#sessionRuntimeBinding.fitViewport(frame.authorityLease, frame.cols, frame.rows, frame.semanticWindowId);
2433
2871
  this.#sendFrame(null, {
2434
2872
  type: "viewport-ack",
2435
2873
  seq: frame.seq,
2436
2874
  cols: frame.cols,
2437
2875
  rows: frame.rows,
2438
- outcome: "geometry-authority-conflict",
2876
+ outcome: "ok",
2439
2877
  authorityLease: frame.authorityLease,
2440
2878
  });
2441
- return;
2442
2879
  }
2443
- this.#failProtocol("input-rejected");
2444
- }
2880
+ catch (error) {
2881
+ if (error instanceof SessionRuntimeControllerLeaseError &&
2882
+ (error.code === "invalid-client-capability" || error.code === "stale-controller-lease")) {
2883
+ this.#sendFrame(null, {
2884
+ type: "viewport-ack",
2885
+ seq: frame.seq,
2886
+ cols: frame.cols,
2887
+ rows: frame.rows,
2888
+ outcome: "geometry-authority-conflict",
2889
+ authorityLease: frame.authorityLease,
2890
+ });
2891
+ return;
2892
+ }
2893
+ if (this.#holdForWindowOwnership(error, fit))
2894
+ return;
2895
+ this.#failProtocol("input-rejected");
2896
+ }
2897
+ };
2898
+ this.#afterWindowOwnership(fit);
2445
2899
  return;
2446
2900
  }
2447
2901
  this.#acceptInput(frame.pane, frame.seq, frame.kind, frame.data, byteLength, frame.performanceTraceId, frame.causalProbe, ingressAtMicros, callbackAtSharedMicros, ingressAtSharedMicros, frame.expectedLifetime);
@@ -2500,6 +2954,8 @@ export class PaneStreamLiveConnection {
2500
2954
  }
2501
2955
  #deliveryChannel(address) {
2502
2956
  const channel = this.#panes.get(address.semanticPaneId);
2957
+ if (channel?.retiredInPlace)
2958
+ return null;
2503
2959
  const expected = channel?.deliveryAddress;
2504
2960
  if (!channel?.delivery ||
2505
2961
  !expected ||
@@ -2583,6 +3039,8 @@ export class PaneStreamLiveConnection {
2583
3039
  }
2584
3040
  #acceptConsumed(pane, seq) {
2585
3041
  const channel = this.#panes.get(pane);
3042
+ if (channel?.retiredInPlace)
3043
+ return;
2586
3044
  if (!this.#deliveryAcks ||
2587
3045
  !channel ||
2588
3046
  seq <= channel.consumedSeq ||
@@ -2613,6 +3071,8 @@ export class PaneStreamLiveConnection {
2613
3071
  return;
2614
3072
  }
2615
3073
  const channel = this.#panes.get(pane);
3074
+ if (channel?.retiredInPlace)
3075
+ return;
2616
3076
  const semanticDelivery = this.#descriptor.terminalDelivery !== null;
2617
3077
  if (!channel ||
2618
3078
  channel.closed ||
@@ -2676,90 +3136,219 @@ export class PaneStreamLiveConnection {
2676
3136
  this.#inputWindowFrames += 1;
2677
3137
  this.#inputWindowBytes += frameBytes;
2678
3138
  channel.nextInputSeq += 1;
2679
- try {
2680
- this.#sessionRuntimeBinding.assertController(pane);
2681
- if (semanticDelivery)
2682
- this.#sessionRuntimeBinding.sendInput(pane, { kind, data }, performanceTraceId, causalProbe, causalProbe
2683
- ? (result) => {
2684
- if (this.#closed)
2685
- return;
2686
- if (result.status === "proved") {
2687
- this.#sendFrame(null, { type: "causal-cell-proof", proof: result.proof });
2688
- }
2689
- else {
2690
- this.#sendFrame(null, {
2691
- type: "causal-cell-failure",
2692
- failure: {
2693
- version: 1,
2694
- capability: "causal-cell-v1",
2695
- traceId: result.traceId,
2696
- reason: result.reason,
2697
- ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
2698
- },
2699
- });
3139
+ const deliver = () => {
3140
+ // Held for an ownership read (#394) while the pane left the stream in
3141
+ // place: dropped like any other late frame for it, not delivered.
3142
+ if (channel.retiredInPlace)
3143
+ return;
3144
+ try {
3145
+ this.#sessionRuntimeBinding.assertController(pane);
3146
+ if (semanticDelivery)
3147
+ this.#sessionRuntimeBinding.sendInput(pane, { kind, data }, performanceTraceId, causalProbe, causalProbe
3148
+ ? (result) => {
3149
+ if (this.#closed)
3150
+ return;
3151
+ if (result.status === "proved") {
3152
+ this.#sendFrame(null, { type: "causal-cell-proof", proof: result.proof });
3153
+ }
3154
+ else {
3155
+ this.#sendFrame(null, {
3156
+ type: "causal-cell-failure",
3157
+ failure: {
3158
+ version: 1,
3159
+ capability: "causal-cell-v1",
3160
+ traceId: result.traceId,
3161
+ reason: result.reason,
3162
+ ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
3163
+ },
3164
+ });
3165
+ }
2700
3166
  }
2701
- }
2702
- : undefined, expectedLifetime);
2703
- else if (kind === "text")
2704
- channel.sub.sendText(data);
2705
- else if (kind === "key")
2706
- channel.sub.sendKey(data);
2707
- else
2708
- throw new Error("Byte input requires semantic runtime");
2709
- let ackStartedAtMicros = null;
2710
- let ackStartedAtSharedMicros = null;
2711
- if (trace) {
2712
- try {
2713
- ackStartedAtMicros = this.#observability.nowMicros();
2714
- }
2715
- catch {
2716
- // Diagnostics cannot alter protocol truth.
2717
- }
2718
- if (this.#diagnosticSharedRawMicros) {
3167
+ : undefined, expectedLifetime);
3168
+ else if (kind === "text")
3169
+ channel.sub.sendText(data);
3170
+ else if (kind === "key")
3171
+ channel.sub.sendKey(data);
3172
+ else
3173
+ throw new Error("Byte input requires semantic runtime");
3174
+ // Its echo goes ahead of the connection's other panes (remote links).
3175
+ channel.delivery?.prioritize?.();
3176
+ let ackStartedAtMicros = null;
3177
+ let ackStartedAtSharedMicros = null;
3178
+ if (trace) {
2719
3179
  try {
2720
- ackStartedAtSharedMicros = this.#sharedMicros();
3180
+ ackStartedAtMicros = this.#observability.nowMicros();
2721
3181
  }
2722
3182
  catch {
2723
- // Preserve process-local ACK diagnostics.
2724
- }
2725
- }
2726
- }
2727
- sendControl(this.#socket, { type: "input-ack", pane, seq });
2728
- if (trace && ackStartedAtMicros !== null) {
2729
- let ackEndedAtMicros = null;
2730
- try {
2731
- ackEndedAtMicros = this.#observability.nowMicros();
2732
- }
2733
- catch {
2734
- // Diagnostics cannot alter protocol truth.
2735
- }
2736
- let ackEndedAtSharedMicros = null;
2737
- if (ackStartedAtSharedMicros !== null) {
2738
- try {
2739
- ackEndedAtSharedMicros = this.#sharedMicros();
3183
+ // Diagnostics cannot alter protocol truth.
2740
3184
  }
2741
- catch {
2742
- // Preserve process-local ACK diagnostics.
3185
+ if (this.#diagnosticSharedRawMicros) {
3186
+ try {
3187
+ ackStartedAtSharedMicros = this.#sharedMicros();
3188
+ }
3189
+ catch {
3190
+ // Preserve process-local ACK diagnostics.
3191
+ }
2743
3192
  }
2744
3193
  }
2745
- if (ackEndedAtMicros !== null) {
3194
+ sendControl(this.#socket, { type: "input-ack", pane, seq });
3195
+ if (trace && ackStartedAtMicros !== null) {
3196
+ let ackEndedAtMicros = null;
2746
3197
  try {
2747
- this.#observability.recordSpan("transport", "pane-stream-input-ack-socket-send", ackStartedAtMicros, ackEndedAtMicros, trace, ackStartedAtSharedMicros === null || ackEndedAtSharedMicros === null
2748
- ? undefined
2749
- : {
2750
- startedAtMicros: ackStartedAtSharedMicros,
2751
- endedAtMicros: ackEndedAtSharedMicros,
2752
- });
3198
+ ackEndedAtMicros = this.#observability.nowMicros();
2753
3199
  }
2754
3200
  catch {
2755
3201
  // Diagnostics cannot alter protocol truth.
2756
3202
  }
3203
+ let ackEndedAtSharedMicros = null;
3204
+ if (ackStartedAtSharedMicros !== null) {
3205
+ try {
3206
+ ackEndedAtSharedMicros = this.#sharedMicros();
3207
+ }
3208
+ catch {
3209
+ // Preserve process-local ACK diagnostics.
3210
+ }
3211
+ }
3212
+ if (ackEndedAtMicros !== null) {
3213
+ try {
3214
+ this.#observability.recordSpan("transport", "pane-stream-input-ack-socket-send", ackStartedAtMicros, ackEndedAtMicros, trace, ackStartedAtSharedMicros === null || ackEndedAtSharedMicros === null
3215
+ ? undefined
3216
+ : {
3217
+ startedAtMicros: ackStartedAtSharedMicros,
3218
+ endedAtMicros: ackEndedAtSharedMicros,
3219
+ });
3220
+ }
3221
+ catch {
3222
+ // Diagnostics cannot alter protocol truth.
3223
+ }
3224
+ }
2757
3225
  }
2758
3226
  }
3227
+ catch (error) {
3228
+ if (this.#holdForWindowOwnership(error, deliver))
3229
+ return;
3230
+ if (error instanceof SessionRuntimeInputLifetimeEndedError) {
3231
+ // Fenced to a lifetime that ended: not delivered, not acknowledged.
3232
+ // The pane's delivery tells the client its lifetime ended.
3233
+ this.#noteInputLifetimeEnded(pane, error);
3234
+ return;
3235
+ }
3236
+ this.#fail("control-frame-handler-failed", error);
3237
+ }
3238
+ };
3239
+ this.#afterWindowOwnership(deliver);
3240
+ }
3241
+ /**
3242
+ * Input and geometry frames that arrive while registered-window ownership is
3243
+ * being read again (another session was created or killed) wait for that
3244
+ * read, in arrival order, instead of closing the stream. The mirror refuses
3245
+ * them meanwhile; before, the stream closed with 1011 and the client had to
3246
+ * reconnect. Bounded: a read that does not settle in time closes as before.
3247
+ */
3248
+ #ownershipHeld = [];
3249
+ #ownershipDraining = false;
3250
+ /** Ends the drain's wait when the stream closes. */
3251
+ #ownershipWake = null;
3252
+ #afterWindowOwnership(run) {
3253
+ if (this.#ownershipHeld.length === 0 && !this.#mirror.windowOwnershipPending?.()) {
3254
+ run();
3255
+ return;
2759
3256
  }
2760
- catch (error) {
2761
- this.#fail("control-frame-handler-failed", error);
3257
+ this.#holdUntilWindowOwnership(run);
3258
+ }
3259
+ /**
3260
+ * Frames whose effect depends on authority order (release, presence,
3261
+ * activity, intents) are not held for the read themselves, but must not
3262
+ * overtake frames that are.
3263
+ */
3264
+ #afterHeldFrames(run) {
3265
+ if (this.#ownershipHeld.length === 0) {
3266
+ run();
3267
+ return;
3268
+ }
3269
+ this.#holdUntilWindowOwnership(run);
3270
+ }
3271
+ /** A refusal while ownership is pending holds the frame; anything else is the caller's. */
3272
+ #holdForWindowOwnership(error, run) {
3273
+ if (!(error instanceof SessionRuntimeControllerLeaseError) ||
3274
+ error.code !== "controller-conflict" ||
3275
+ !this.#mirror.windowOwnershipPending?.())
3276
+ return false;
3277
+ this.#ownershipHeld.unshift(run);
3278
+ if (!this.#ownershipDraining)
3279
+ void this.#drainWindowOwnership();
3280
+ return true;
3281
+ }
3282
+ #holdUntilWindowOwnership(run) {
3283
+ if (this.#ownershipHeld.length >= PANE_STREAM_OWNERSHIP_HELD_FRAMES) {
3284
+ this.#ownershipHeld.length = 0;
3285
+ this.#fail("window-ownership-held-overflow");
3286
+ return;
2762
3287
  }
3288
+ this.#ownershipHeld.push(run);
3289
+ if (!this.#ownershipDraining)
3290
+ void this.#drainWindowOwnership();
3291
+ }
3292
+ async #drainWindowOwnership() {
3293
+ this.#ownershipDraining = true;
3294
+ try {
3295
+ await this.#drainWindowOwnershipOnce();
3296
+ }
3297
+ finally {
3298
+ this.#ownershipDraining = false;
3299
+ }
3300
+ }
3301
+ async #drainWindowOwnershipOnce() {
3302
+ const deadline = Date.now() + this.#ownershipWaitMs;
3303
+ while (!this.#closed && this.#ownershipHeld.length > 0) {
3304
+ if (this.#mirror.windowOwnershipPending?.()) {
3305
+ const left = deadline - Date.now();
3306
+ if (left <= 0) {
3307
+ this.#ownershipHeld.length = 0;
3308
+ this.#fail("window-ownership-unverified");
3309
+ return;
3310
+ }
3311
+ const timers = [];
3312
+ const wait = (ms) => new Promise((resolve) => {
3313
+ const timer = setTimeout(resolve, ms);
3314
+ timer.unref?.();
3315
+ timers.push(timer);
3316
+ });
3317
+ const read = this.#mirror.verifyWindowOwnership?.();
3318
+ await Promise.race([
3319
+ // Without a read to wait on, poll instead of spinning.
3320
+ read ? read.catch(() => wait(25)) : wait(25),
3321
+ wait(left),
3322
+ new Promise((resolve) => {
3323
+ this.#ownershipWake = resolve;
3324
+ }),
3325
+ ]);
3326
+ this.#ownershipWake = null;
3327
+ for (const timer of timers)
3328
+ clearTimeout(timer);
3329
+ continue;
3330
+ }
3331
+ const run = this.#ownershipHeld.shift();
3332
+ const before = this.#ownershipHeld.length;
3333
+ run();
3334
+ // A refusal inside run() put it back at the front: wait again.
3335
+ if (this.#ownershipHeld.length > before)
3336
+ continue;
3337
+ }
3338
+ }
3339
+ #inputLifetimeEndedLogged = new Set();
3340
+ #inputLifetimeEndedDropped = 0;
3341
+ #noteInputLifetimeEnded(pane, error) {
3342
+ this.#inputLifetimeEndedDropped += 1;
3343
+ if (this.#inputLifetimeEndedLogged.has(pane))
3344
+ return;
3345
+ this.#inputLifetimeEndedLogged.add(pane);
3346
+ logger.info("pane-stream", "input for an ended pane lifetime not delivered", {
3347
+ session: this.#descriptor.sessionName,
3348
+ clientId: this.#clientId,
3349
+ pane,
3350
+ error: error.message.slice(0, 200),
3351
+ });
2763
3352
  }
2764
3353
  #failProtocol(code) {
2765
3354
  try {
@@ -2787,6 +3376,26 @@ export class PaneStreamLiveConnection {
2787
3376
  }
2788
3377
  #onSocketClose = () => this.close(1000, "peer-closed");
2789
3378
  }
3379
+ function newPaneChannel(pane) {
3380
+ return {
3381
+ semanticPaneId: pane,
3382
+ sub: null,
3383
+ delivery: null,
3384
+ deliveryAddress: null,
3385
+ serverSeq: 0,
3386
+ sentPaneFrames: 0,
3387
+ consumedSeq: 0,
3388
+ nextInputSeq: 1,
3389
+ frozenByWire: false,
3390
+ closed: false,
3391
+ batch: null,
3392
+ graphicsAnnounced: false,
3393
+ graphicsQueue: [],
3394
+ graphicsSending: false,
3395
+ graphicsServed: new Map(),
3396
+ graphicsState: null,
3397
+ };
3398
+ }
2790
3399
  function concatBytes(chunks) {
2791
3400
  if (chunks.length === 0)
2792
3401
  return new Uint8Array(0);