tmux-ide 2.9.24 → 2.9.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/bin/cli.js +1352 -350
  2. package/package.json +4 -2
  3. package/packages/contracts/src/pane-stream.ts +53 -0
  4. package/packages/daemon/dist/command-center/discovery.js +24 -5
  5. package/packages/daemon/dist/command-center/server.js +81 -75
  6. package/packages/daemon/dist/doctor.js +46 -10
  7. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  8. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  9. package/packages/daemon/dist/lib/daemon-embed.js +6 -0
  10. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  11. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  12. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  13. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  14. package/packages/daemon/dist/lib/update-check.js +18 -0
  15. package/packages/daemon/dist/lib/update-daemon-outcome.js +31 -0
  16. package/packages/daemon/dist/lib/update.js +39 -14
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  21. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  22. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  23. package/packages/daemon/dist/terminal/mirror/session-channel.js +25 -1
  24. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +741 -208
  25. package/packages/daemon/dist/terminal/session-runtime/registry.js +24 -2
  26. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +77 -2
  27. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  28. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  29. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  30. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  31. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  32. package/packages/daemon/src/command-center/discovery.ts +24 -4
  33. package/packages/daemon/src/command-center/server.ts +67 -67
  34. package/packages/daemon/src/doctor.ts +50 -9
  35. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  36. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  37. package/packages/daemon/src/lib/daemon-embed.ts +22 -0
  38. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  39. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  40. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  41. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  42. package/packages/daemon/src/lib/update-check.ts +34 -0
  43. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  44. package/packages/daemon/src/lib/update.ts +58 -16
  45. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  46. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  47. package/packages/daemon/src/terminal/mirror/session-channel.ts +30 -1
  48. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +811 -223
  49. package/packages/daemon/src/terminal/session-runtime/registry.ts +35 -2
  50. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +74 -2
  51. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  52. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  53. package/packages/daemon/src/tui/chrome/snapshot.ts +47 -1
  54. package/packages/daemon/src/tui/chrome/statusline.ts +7 -4
  55. package/packages/daemon/src/tui/chrome/updater.ts +3 -0
  56. 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_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);
@@ -480,6 +484,8 @@ export class PaneStreamAdmissionCoordinator {
480
484
  leaseManager: this.#leaseManager,
481
485
  ledger: this.#ledger,
482
486
  drainTickMs: this.#drainTickMs,
487
+ openRetryDelaysMs: this.#openRetryDelaysMs,
488
+ ownershipWaitMs: this.#ownershipWaitMs,
483
489
  maxSocketBufferedBytes: this.#maxSocketBufferedBytes,
484
490
  maxInputFrames: this.#maxInputFrames,
485
491
  maxInputBytes: this.#maxInputBytes,
@@ -658,6 +664,19 @@ class PreAuthAdmission {
658
664
  socket.off("error", this.#onClose);
659
665
  }
660
666
  }
667
+ /**
668
+ * How long an in-place topology change waits for the layout that matches the
669
+ * session's inventory, when the inventory read was newer than the layout in
670
+ * hand (a split and a close in quick succession). After it the stream closes
671
+ * as it would without capability 119.
672
+ */
673
+ export const PANE_STREAM_TOPOLOGY_SETTLE_MS = 500;
674
+ /** About half a second in all: long enough for one slow tmux answer, short for a user. */
675
+ export const PANE_STREAM_OPEN_RETRY_DELAYS_MS = [150, 400];
676
+ /** Input waits this long for ownership to be read again before the stream closes. */
677
+ export const PANE_STREAM_OWNERSHIP_WAIT_MS = 2_000;
678
+ /** At most this many input and geometry frames wait for it. */
679
+ export const PANE_STREAM_OWNERSHIP_HELD_FRAMES = 256;
661
680
  const GRAPHICS_MAX_QUEUED_DIGESTS = 256;
662
681
  /** Graphics state as renderers without zlib support must see it. */
663
682
  export function rawGraphicsState(state) {
@@ -699,6 +718,8 @@ export class PaneStreamLiveConnection {
699
718
  #leaseManager;
700
719
  #ledger;
701
720
  #drainTickMs;
721
+ #openRetryDelaysMs;
722
+ #ownershipWaitMs;
702
723
  #maxSocketBufferedBytes;
703
724
  #maxInputFrames;
704
725
  #maxInputBytes;
@@ -712,6 +733,13 @@ export class PaneStreamLiveConnection {
712
733
  #panes = new Map();
713
734
  #semanticLayouts = new Map();
714
735
  #semanticExpectedPaneIds = null;
736
+ /** Capability 119 (#723): a changed pane set is announced, not a reason to close. */
737
+ #topologyInPlace;
738
+ /** The stream was issued for every pane of its session: new panes join it. */
739
+ #leasesWholeSession = false;
740
+ #topologyReconciling = false;
741
+ #topologyPending = null;
742
+ #topologyWaiter = null;
715
743
  #semanticRuntimeSessionId = null;
716
744
  #semanticWindowLinks = null;
717
745
  #semanticTopologyEpoch = -1;
@@ -796,6 +824,8 @@ export class PaneStreamLiveConnection {
796
824
  this.#leaseManager = options.leaseManager;
797
825
  this.#ledger = options.ledger;
798
826
  this.#drainTickMs = options.drainTickMs;
827
+ this.#openRetryDelaysMs = options.openRetryDelaysMs;
828
+ this.#ownershipWaitMs = options.ownershipWaitMs ?? PANE_STREAM_OWNERSHIP_WAIT_MS;
799
829
  this.#maxSocketBufferedBytes = options.maxSocketBufferedBytes;
800
830
  this.#maxInputFrames = options.maxInputFrames;
801
831
  this.#maxInputBytes = options.maxInputBytes;
@@ -810,26 +840,11 @@ export class PaneStreamLiveConnection {
810
840
  : undefined;
811
841
  this.#diagnosticAfterFrameParse = options.diagnosticAfterFrameParse;
812
842
  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
- }
843
+ this.#topologyInPlace =
844
+ options.descriptor.terminalDelivery?.protocolVersions.some((version) => version === PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION ||
845
+ version === PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION) === true;
846
+ for (const pane of options.descriptor.panes)
847
+ this.#panes.set(pane, newPaneChannel(pane));
833
848
  }
834
849
  get clientId() {
835
850
  return this.#clientId;
@@ -853,6 +868,7 @@ export class PaneStreamLiveConnection {
853
868
  this.#descriptor.terminalDelivery?.protocolVersions.includes(PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION)
854
869
  ? { inputBytes: true }
855
870
  : {}),
871
+ ...(this.#topologyInPlace ? { topologyInPlace: true } : {}),
856
872
  protocolVersion: PANE_STREAM_PROTOCOL_VERSION,
857
873
  daemonInstanceId: this.#binding.daemonInstanceId,
858
874
  requestId: this.#binding.requestId,
@@ -867,7 +883,12 @@ export class PaneStreamLiveConnection {
867
883
  });
868
884
  this.#recordDiagnosticLifecycle("pane-stream-server-ready");
869
885
  }
870
- catch {
886
+ catch (error) {
887
+ // The one 1011 that still closed without a cause in the log.
888
+ this.#closeCause = {
889
+ cause: "ready-frame-failed",
890
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
891
+ };
871
892
  this.close(1011, "stream-unavailable-describe");
872
893
  return;
873
894
  }
@@ -906,8 +927,14 @@ export class PaneStreamLiveConnection {
906
927
  // Whether this connection held input when it went: the next stream of
907
928
  // the same client can only be granted input once that is released.
908
929
  ...(this.#heldInput === null ? {} : { heldInput: this.#heldInput }),
930
+ // Keys not delivered because their pane lifetime had ended (#397).
931
+ ...(this.#inputLifetimeEndedDropped > 0
932
+ ? { droppedEndedLifetimeInputs: this.#inputLifetimeEndedDropped }
933
+ : {}),
909
934
  });
910
935
  this.#closed = true;
936
+ this.#ownershipHeld.length = 0;
937
+ this.#ownershipWake?.();
911
938
  for (const demand of this.#surfaceDemands.values())
912
939
  demand.close();
913
940
  this.#surfaceDemands.clear();
@@ -974,7 +1001,7 @@ export class PaneStreamLiveConnection {
974
1001
  // is absence; a describe FAILURE is not and fails the connection).
975
1002
  let described;
976
1003
  try {
977
- described = await this.#mirror.describeSession(this.#descriptor.sessionName);
1004
+ described = await this.#retryOpenStep("describe-session", () => this.#mirror.describeSession(this.#descriptor.sessionName));
978
1005
  }
979
1006
  catch (error) {
980
1007
  this.#fail("describe-session-failed", error);
@@ -1030,6 +1057,36 @@ export class PaneStreamLiveConnection {
1030
1057
  }
1031
1058
  this.#closeIfAllPanesGone();
1032
1059
  }
1060
+ /**
1061
+ * One step of a stream's opening, tried again after a failure (#585): on a
1062
+ * loaded host one slow tmux answer failed the step, the step closed the whole
1063
+ * stream with 1011, and nothing was tried twice. A refusal of authority is a
1064
+ * decision, not a failure, and is never repeated. Each repeat is logged.
1065
+ */
1066
+ async #retryOpenStep(step, run) {
1067
+ for (let attempt = 0;; attempt += 1) {
1068
+ try {
1069
+ return await run();
1070
+ }
1071
+ catch (error) {
1072
+ const delayMs = this.#openRetryDelaysMs[attempt];
1073
+ if (delayMs === undefined ||
1074
+ this.#closed ||
1075
+ error instanceof SessionRuntimeControllerLeaseError)
1076
+ throw error;
1077
+ logger.info("pane-stream", "stream open step failed; trying again", {
1078
+ session: this.#descriptor.sessionName,
1079
+ clientId: this.#clientId,
1080
+ step,
1081
+ attempt: attempt + 1,
1082
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
1083
+ });
1084
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1085
+ if (this.#closed)
1086
+ throw error;
1087
+ }
1088
+ }
1089
+ }
1033
1090
  async #subscribeSemantic(known) {
1034
1091
  const binding = this.#sessionRuntimeBinding;
1035
1092
  const offer = this.#descriptor.terminalDelivery;
@@ -1114,28 +1171,7 @@ export class PaneStreamLiveConnection {
1114
1171
  // removes N x attachment latency without allowing a fast pane to make the
1115
1172
  // session look ready while a sibling is still missing. allSettled is
1116
1173
  // 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
- });
1174
+ const openings = channels.map((channel) => this.#openPaneDelivery(binding, offer, channel));
1139
1175
  const settled = await Promise.allSettled(openings);
1140
1176
  const opened = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
1141
1177
  if (this.#closed ||
@@ -1147,27 +1183,7 @@ export class PaneStreamLiveConnection {
1147
1183
  }
1148
1184
  return;
1149
1185
  }
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) {
1186
+ if (opened.some((entry) => this.#deliveryIdentityChanged(entry))) {
1171
1187
  await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
1172
1188
  this.#failTopologyChanged();
1173
1189
  return;
@@ -1194,6 +1210,7 @@ export class PaneStreamLiveConnection {
1194
1210
  }
1195
1211
  this.#recordDiagnosticLifecycle("pane-stream-layout-validated");
1196
1212
  this.#semanticExpectedPaneIds = expectedPaneIds;
1213
+ this.#leasesWholeSession = expectedPaneIds.every((pane) => this.#panes.has(pane));
1197
1214
  this.#semanticRuntimeSessionId = authority.runtimeSessionId;
1198
1215
  this.#semanticWindowLinks = authority.windowLinks;
1199
1216
  this.#semanticTopologyEpoch = authority.topologyEpoch;
@@ -1214,6 +1231,60 @@ export class PaneStreamLiveConnection {
1214
1231
  const visibleAtDelivery = new Set(authority.layouts.flatMap((layout) => layout.currentWindow ? layout.panes.map((pane) => pane.semanticPaneId) : []));
1215
1232
  opened.sort((left, right) => Number(visibleAtDelivery.has(right.channel.semanticPaneId)) -
1216
1233
  Number(visibleAtDelivery.has(left.channel.semanticPaneId)));
1234
+ await this.#publishOpenedDeliveries(opened);
1235
+ this.#closeIfAllPanesGone();
1236
+ }
1237
+ /** Open one pane's delivery; its messages wait until the pane is announced. */
1238
+ async #openPaneDelivery(binding, offer, channel) {
1239
+ const pending = [];
1240
+ let ready = false;
1241
+ let negotiated = false;
1242
+ // #585: a failed open is tried again (150 ms, 400 ms) before the stream
1243
+ // closes; this applies to a pane added in place too.
1244
+ const delivery = await this.#retryOpenStep("pane-delivery-open", () => {
1245
+ // A try that failed may have delivered something; start clean.
1246
+ pending.length = 0;
1247
+ return binding.openTerminalDelivery(channel.semanticPaneId, offer, (message) => {
1248
+ if (!ready && !(negotiated && message.type === "terminal.delivery.fault"))
1249
+ pending.push(message);
1250
+ else
1251
+ return this.#sendTerminalDelivery(channel.semanticPaneId, message);
1252
+ }, this.#descriptor.workspaceName);
1253
+ });
1254
+ return {
1255
+ channel,
1256
+ delivery,
1257
+ pending,
1258
+ markNegotiated: () => {
1259
+ negotiated = true;
1260
+ },
1261
+ markReady: () => {
1262
+ ready = true;
1263
+ },
1264
+ };
1265
+ }
1266
+ #deliveryIdentityChanged({ channel, delivery, pending }) {
1267
+ if (!delivery.negotiation.accepted)
1268
+ return true;
1269
+ const negotiated = delivery.negotiation.negotiated;
1270
+ if (negotiated.generation !== this.#binding.daemonInstanceId)
1271
+ return true;
1272
+ let incarnation = null;
1273
+ for (const message of pending) {
1274
+ if (message.type !== "terminal.delivery" && message.type !== "terminal.projection")
1275
+ continue;
1276
+ if (message.workspaceName !== this.#descriptor.workspaceName ||
1277
+ message.semanticPaneId !== channel.semanticPaneId ||
1278
+ message.generation !== negotiated.generation ||
1279
+ message.deliveryNonce !== negotiated.deliveryNonce ||
1280
+ (incarnation !== null && message.incarnation !== incarnation))
1281
+ return true;
1282
+ incarnation = message.incarnation;
1283
+ }
1284
+ return false;
1285
+ }
1286
+ /** Announce validated deliveries, then replay what each collected meanwhile. */
1287
+ async #publishOpenedDeliveries(opened) {
1217
1288
  for (const { channel, delivery, markNegotiated } of opened) {
1218
1289
  if (this.#closed || channel.closed) {
1219
1290
  await delivery.close();
@@ -1260,9 +1331,43 @@ export class PaneStreamLiveConnection {
1260
1331
  markReady();
1261
1332
  this.#startGraphics(channel);
1262
1333
  }
1263
- this.#closeIfAllPanesGone();
1264
1334
  }
1335
+ /**
1336
+ * A tombstone ends a pane's delivery for good: the hub drops the pane and
1337
+ * sends nothing more. Without capability 119 the pane's removal closes the
1338
+ * stream anyway. With it, the removal arrives as a `topology` frame within
1339
+ * moments; if none comes, the pane is still in the session and would stay
1340
+ * blank for ever, so the stream closes as it would without the capability
1341
+ * and the client takes a new one.
1342
+ */
1343
+ #watchTombstone(pane) {
1344
+ const channel = this.#panes.get(pane);
1345
+ if (!this.#topologyInPlace || !channel || channel.closed)
1346
+ return;
1347
+ const timer = setTimeout(() => {
1348
+ if (this.#closed || channel.retiredInPlace || this.#panes.get(pane) !== channel)
1349
+ return;
1350
+ // A change being applied may be the one that removes this pane (kill-pane
1351
+ // plus split: the new pane's delivery can take longer to open than the
1352
+ // settle time). Decide again once it is done, with a fresh settle time.
1353
+ if (this.#topologyReconciling) {
1354
+ this.#tombstonesAfterChange.add(channel);
1355
+ return;
1356
+ }
1357
+ this.#failTopologyChanged("a pane that stays lost its source");
1358
+ }, PANE_STREAM_TOPOLOGY_SETTLE_MS);
1359
+ timer.unref?.();
1360
+ }
1361
+ /**
1362
+ * Tombstoned channels whose guard came due while a change was being applied.
1363
+ * The channel, not the pane id: a pane that left and came back within the
1364
+ * change has a fresh channel, which this tombstone is not about.
1365
+ */
1366
+ #tombstonesAfterChange = new Set();
1265
1367
  async #sendTerminalDelivery(pane, message) {
1368
+ if ((message.type === "terminal.delivery" || message.type === "terminal.projection") &&
1369
+ message.frame === "tombstone")
1370
+ this.#watchTombstone(pane);
1266
1371
  if (message.type === "terminal.projection") {
1267
1372
  const channel = this.#panes.get(pane);
1268
1373
  if (channel?.deliveryAddress)
@@ -1406,7 +1511,8 @@ export class PaneStreamLiveConnection {
1406
1511
  // when served.
1407
1512
  const zlib = this.#descriptor.terminalDelivery?.protocolVersions.some((version) => version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION ||
1408
1513
  version === PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION ||
1409
- version === PANE_STREAM_READER_CAPABILITY_VERSION) === true;
1514
+ version === PANE_STREAM_READER_CAPABILITY_VERSION ||
1515
+ version === PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION) === true;
1410
1516
  channel.graphicsZlib = zlib;
1411
1517
  channel.graphicsLocal =
1412
1518
  !!this.#localImages &&
@@ -1803,14 +1909,23 @@ export class PaneStreamLiveConnection {
1803
1909
  #onLayoutAuthority(snapshot) {
1804
1910
  if (this.#closed || !this.#semanticExpectedPaneIds || !this.#semanticRuntimeSessionId)
1805
1911
  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) {
1912
+ if (this.#topologyReconciling) {
1913
+ // One change at a time, and only the newest state is worth announcing.
1914
+ this.#topologyPending = snapshot;
1915
+ this.#topologyWaiter?.();
1916
+ return;
1917
+ }
1918
+ if (!this.#layoutAuthorityAdmissible(snapshot)) {
1810
1919
  this.#failTopologyChanged();
1811
1920
  return;
1812
1921
  }
1813
1922
  const frames = this.#validateInitialLayout(snapshot.layouts, this.#semanticExpectedPaneIds);
1923
+ if (!frames && this.#topologyInPlace) {
1924
+ // The layout does not fit the pane set this stream knows. With
1925
+ // capability 119 that is a change to follow, not a reason to close.
1926
+ void this.#reconcileTopology(snapshot);
1927
+ return;
1928
+ }
1814
1929
  if (!frames ||
1815
1930
  !PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
1816
1931
  type: "layout-snapshot",
@@ -1821,27 +1936,258 @@ export class PaneStreamLiveConnection {
1821
1936
  this.#failTopologyChanged();
1822
1937
  return;
1823
1938
  }
1939
+ if (!this.#windowLinksAdmissible(snapshot)) {
1940
+ this.#failTopologyChanged();
1941
+ return;
1942
+ }
1943
+ this.#semanticWindowLinks = snapshot.windowLinks;
1944
+ this.#semanticTopologyEpoch = snapshot.topologyEpoch;
1945
+ this.#semanticLayouts.clear();
1946
+ for (const event of snapshot.layouts)
1947
+ this.#semanticLayouts.set(event.semanticWindowId, event);
1948
+ this.#sendFrame(null, {
1949
+ type: "layout-snapshot",
1950
+ topologyEpoch: snapshot.topologyEpoch,
1951
+ layouts: frames,
1952
+ windowLinks: snapshot.windowLinks,
1953
+ });
1954
+ }
1955
+ /** The same session and runtime, a newer epoch, a layout a stream can carry. */
1956
+ #layoutAuthorityAdmissible(snapshot) {
1957
+ return (snapshot.session === this.#descriptor.sessionName &&
1958
+ snapshot.runtimeSessionId === this.#semanticRuntimeSessionId &&
1959
+ snapshot.topologyEpoch > this.#semanticTopologyEpoch &&
1960
+ snapshot.layouts.length <= PANE_STREAM_MAX_PANES);
1961
+ }
1962
+ #windowLinksAdmissible(snapshot) {
1824
1963
  const previousLinks = this.#semanticWindowLinks;
1825
- if (!previousLinks ||
1964
+ return !(!previousLinks ||
1826
1965
  snapshot.windowLinks.liveSessionId !== previousLinks.liveSessionId ||
1827
1966
  snapshot.windowLinks.linkRevision < previousLinks.linkRevision ||
1828
1967
  (snapshot.windowLinks.linkRevision === previousLinks.linkRevision &&
1829
1968
  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;
1969
+ JSON.stringify([...previousLinks.links].sort((a, b) => a.linkId.localeCompare(b.linkId)))));
1970
+ }
1971
+ /**
1972
+ * Capability 119 (#723). Follow a changed pane set without closing: one
1973
+ * change at a time, newest state only. Every doubt ends where a stream
1974
+ * without the capability ends, in `#failTopologyChanged()`.
1975
+ */
1976
+ async #reconcileTopology(first) {
1977
+ this.#topologyReconciling = true;
1978
+ let snapshot = first;
1979
+ try {
1980
+ for (;;) {
1981
+ this.#topologyPending = null;
1982
+ const outcome = await this.#applyTopology(snapshot);
1983
+ if (this.#closed)
1984
+ return;
1985
+ if (outcome === "failed")
1986
+ return this.#failTopologyChanged(this.#topologyFailure);
1987
+ let next = this.#topologyPending;
1988
+ if (outcome === "stale" && !next) {
1989
+ // The inventory was read after a further change: its layout follows.
1990
+ next = await this.#nextTopologySnapshot();
1991
+ if (this.#closed)
1992
+ return;
1993
+ if (!next)
1994
+ return this.#failTopologyChanged();
1995
+ }
1996
+ if (!next)
1997
+ return;
1998
+ if (!this.#layoutAuthorityAdmissible(next))
1999
+ return this.#failTopologyChanged();
2000
+ snapshot = next;
2001
+ }
2002
+ }
2003
+ finally {
2004
+ this.#topologyReconciling = false;
2005
+ this.#topologyPending = null;
2006
+ const tombstoned = [...this.#tombstonesAfterChange];
2007
+ this.#tombstonesAfterChange.clear();
2008
+ for (const channel of tombstoned)
2009
+ if (this.#panes.get(channel.semanticPaneId) === channel)
2010
+ this.#watchTombstone(channel.semanticPaneId);
2011
+ }
2012
+ }
2013
+ #nextTopologySnapshot() {
2014
+ if (this.#topologyPending)
2015
+ return Promise.resolve(this.#topologyPending);
2016
+ return new Promise((resolve) => {
2017
+ const finish = () => {
2018
+ clearTimeout(timer);
2019
+ this.#topologyWaiter = null;
2020
+ resolve(this.#topologyPending);
2021
+ };
2022
+ const timer = setTimeout(finish, PANE_STREAM_TOPOLOGY_SETTLE_MS);
2023
+ timer.unref?.();
2024
+ this.#topologyWaiter = finish;
2025
+ });
2026
+ }
2027
+ /**
2028
+ * "applied": the client was told and the stream goes on. "stale": this
2029
+ * layout does not fit the session's inventory as read now; a newer layout
2030
+ * decides. "failed": close.
2031
+ */
2032
+ async #applyTopology(snapshot) {
2033
+ const binding = this.#sessionRuntimeBinding;
2034
+ const offer = this.#descriptor.terminalDelivery;
2035
+ if (!binding ||
2036
+ !offer ||
2037
+ !this.#semanticExpectedPaneIds ||
2038
+ !this.#windowLinksAdmissible(snapshot))
2039
+ return this.#topologyFailed("not a semantic stream, or its window links changed");
2040
+ // A zoomed window lists one pane, so the layout alone cannot tell which
2041
+ // panes exist: the trusted inventory does.
2042
+ // The inventory is read by session NAME. Only an inventory that states
2043
+ // the runtime session this stream was issued for may extend the grant: a
2044
+ // session replaced under the same name is another session.
2045
+ let described;
2046
+ let inventoryIsThisSession = false;
2047
+ try {
2048
+ if (this.#mirror.describeSessionAuthority) {
2049
+ const authority = await this.#mirror.describeSessionAuthority(this.#descriptor.sessionName);
2050
+ if (authority.runtimeSessionId !== this.#semanticRuntimeSessionId)
2051
+ return this.#topologyFailed("inventory is of another runtime session");
2052
+ described = authority.description;
2053
+ inventoryIsThisSession = true;
2054
+ }
2055
+ else {
2056
+ described = await this.#mirror.describeSession(this.#descriptor.sessionName);
2057
+ }
2058
+ }
2059
+ catch (error) {
2060
+ return this.#topologyFailed("session inventory unavailable", error);
2061
+ }
2062
+ if (this.#closed)
2063
+ return this.#topologyFailed("closed");
2064
+ const next = [...new Set(described.panes.map((pane) => pane.semanticPaneId))].sort();
2065
+ if (next.length === 0)
2066
+ return this.#topologyFailed("session has no panes");
2067
+ const frames = this.#validateInitialLayout(snapshot.layouts, next);
2068
+ if (!frames)
2069
+ return "stale";
2070
+ if (!PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
2071
+ type: "layout-snapshot",
2072
+ topologyEpoch: snapshot.topologyEpoch,
2073
+ layouts: frames,
2074
+ windowLinks: snapshot.windowLinks,
2075
+ }).success)
2076
+ return this.#topologyFailed("layout snapshot invalid");
2077
+ const live = [...this.#panes.values()].filter((channel) => !channel.closed);
2078
+ const removed = live.filter((channel) => !next.includes(channel.semanticPaneId));
2079
+ // A stream issued for the whole session follows it; one issued for some
2080
+ // panes keeps exactly those.
2081
+ const liveIds = new Set(live.map((channel) => channel.semanticPaneId));
2082
+ const added = this.#leasesWholeSession ? next.filter((pane) => !liveIds.has(pane)) : [];
2083
+ if (added.length > 0 && !inventoryIsThisSession)
2084
+ return this.#topologyFailed("inventory cannot prove the runtime session");
2085
+ const remaining = live.length - removed.length + added.length;
2086
+ if (remaining === 0 || remaining > PANE_STREAM_MAX_PANES)
2087
+ return this.#topologyFailed("pane count outside the stream limit");
2088
+ // The transport's pane grant is exact. The daemon amends it from its own
2089
+ // inventory of this session before a new pane's delivery can open.
2090
+ if (added.length > 0) {
2091
+ try {
2092
+ if (!binding.amendPaneGrant)
2093
+ return this.#topologyFailed("transport cannot amend its grant");
2094
+ binding.amendPaneGrant({ added, removed: [] });
2095
+ }
2096
+ catch (error) {
2097
+ return this.#topologyFailed("pane grant refused", error);
2098
+ }
2099
+ }
2100
+ const channels = added.map(newPaneChannel);
2101
+ const settled = await Promise.allSettled(channels.map((channel) => this.#openPaneDelivery(binding, offer, channel)));
2102
+ const opened = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
2103
+ if (this.#closed ||
2104
+ opened.length !== channels.length ||
2105
+ opened.some((entry) => this.#deliveryIdentityChanged(entry))) {
2106
+ await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
2107
+ if (added.length > 0) {
2108
+ try {
2109
+ binding.amendPaneGrant?.({ added: [], removed: added });
2110
+ }
2111
+ catch {
2112
+ // The stream closes; its binding and grant go with it.
2113
+ }
2114
+ }
2115
+ const rejected = settled.find((result) => result.status === "rejected");
2116
+ return this.#topologyFailed(this.#closed
2117
+ ? "closed while opening"
2118
+ : rejected
2119
+ ? "delivery open rejected"
2120
+ : opened.some((entry) => !entry.delivery.negotiation.accepted)
2121
+ ? "delivery negotiation refused"
2122
+ : "delivery identity changed", rejected?.status === "rejected" ? rejected.reason : undefined);
2123
+ }
2124
+ // Commit. From here on nothing can fail the change.
2125
+ if (removed.length > 0) {
2126
+ try {
2127
+ binding.amendPaneGrant?.({
2128
+ added: [],
2129
+ removed: removed.map((channel) => channel.semanticPaneId),
2130
+ });
2131
+ }
2132
+ catch {
2133
+ // A pane that is gone cannot be used through a grant that lingers.
2134
+ }
1833
2135
  }
2136
+ for (const channel of removed)
2137
+ this.#retirePaneInPlace(channel);
2138
+ for (const channel of channels)
2139
+ this.#panes.set(channel.semanticPaneId, channel);
2140
+ this.#semanticExpectedPaneIds = next;
1834
2141
  this.#semanticWindowLinks = snapshot.windowLinks;
1835
2142
  this.#semanticTopologyEpoch = snapshot.topologyEpoch;
1836
2143
  this.#semanticLayouts.clear();
1837
2144
  for (const event of snapshot.layouts)
1838
2145
  this.#semanticLayouts.set(event.semanticWindowId, event);
2146
+ this.#sendFrame(null, {
2147
+ type: "topology",
2148
+ topologyEpoch: snapshot.topologyEpoch,
2149
+ panes: [...this.#panes.values()]
2150
+ .filter((channel) => !channel.closed)
2151
+ .map((channel) => channel.semanticPaneId),
2152
+ removed: removed.map((channel) => channel.semanticPaneId),
2153
+ added,
2154
+ });
1839
2155
  this.#sendFrame(null, {
1840
2156
  type: "layout-snapshot",
1841
2157
  topologyEpoch: snapshot.topologyEpoch,
1842
2158
  layouts: frames,
1843
2159
  windowLinks: snapshot.windowLinks,
1844
2160
  });
2161
+ await this.#publishOpenedDeliveries(opened);
2162
+ return "applied";
2163
+ }
2164
+ #topologyFailure = "";
2165
+ #topologyFailed(why, error) {
2166
+ this.#topologyFailure = error === undefined ? why : `${why}: ${String(error).slice(0, 200)}`;
2167
+ return "failed";
2168
+ }
2169
+ /** A pane that left the session: its delivery ends, the stream does not. */
2170
+ #retirePaneInPlace(channel) {
2171
+ const sub = channel.sub;
2172
+ const delivery = channel.delivery;
2173
+ channel.sub = null;
2174
+ channel.delivery = null;
2175
+ channel.closed = true;
2176
+ channel.retiredInPlace = true;
2177
+ // The channel stays only so late client frames for it are dropped; a long
2178
+ // stream under an agent that splits often must not keep each pane's buffers.
2179
+ channel.deliveryAddress = null;
2180
+ channel.batch = null;
2181
+ channel.graphicsQueue = [];
2182
+ channel.graphicsServed = new Map();
2183
+ channel.graphicsState = null;
2184
+ this.#surfaceDemands.get(channel.semanticPaneId)?.close();
2185
+ this.#surfaceDemands.delete(channel.semanticPaneId);
2186
+ if (sub)
2187
+ void sub.close().catch(() => undefined);
2188
+ if (delivery)
2189
+ void delivery.close().catch(() => undefined);
2190
+ this.#ledger.forgetPane(this.#clientId, channel.semanticPaneId);
1845
2191
  }
1846
2192
  #onLayout(event) {
1847
2193
  if (this.#closed)
@@ -1868,7 +2214,14 @@ export class PaneStreamLiveConnection {
1868
2214
  this.#sendFrame(null, frame);
1869
2215
  }
1870
2216
  #offers(version) {
1871
- return this.#descriptor.terminalDelivery?.protocolVersions.includes(version) === true;
2217
+ const offered = this.#descriptor.terminalDelivery?.protocolVersions;
2218
+ if (!offered)
2219
+ return false;
2220
+ // 120 stands for 118 and 119 together.
2221
+ return (offered.includes(version) ||
2222
+ ((version === PANE_STREAM_READER_CAPABILITY_VERSION ||
2223
+ version === PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION) &&
2224
+ offered.includes(PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION)));
1872
2225
  }
1873
2226
  #layoutFrame(event) {
1874
2227
  const frame = {
@@ -1938,9 +2291,12 @@ export class PaneStreamLiveConnection {
1938
2291
  return null;
1939
2292
  return frames;
1940
2293
  }
1941
- #failTopologyChanged() {
2294
+ /** `inPlaceFailure`: why a capability-119 stream could not follow the change. */
2295
+ #failTopologyChanged(inPlaceFailure) {
1942
2296
  if (this.#closed)
1943
2297
  return;
2298
+ if (inPlaceFailure)
2299
+ this.#closeCause = { cause: `topology-in-place: ${inPlaceFailure}` };
1944
2300
  this.#sendFrame(null, {
1945
2301
  type: "error",
1946
2302
  protocolVersion: PANE_STREAM_PROTOCOL_VERSION,
@@ -2144,22 +2500,28 @@ export class PaneStreamLiveConnection {
2144
2500
  if (!this.#acceptAuthorityGeneration(frame.generation))
2145
2501
  return;
2146
2502
  this.#usesExplicitAuthority = true;
2147
- if (!this.#sessionRuntimeBinding?.updatePresence)
2503
+ const binding = this.#sessionRuntimeBinding;
2504
+ if (!binding?.updatePresence)
2148
2505
  return this.#failProtocol("protocol-error");
2149
- const snapshot = this.#sessionRuntimeBinding.updatePresence(frame.state);
2150
- if (!this.#sessionRuntimeBinding.onAuthoritySnapshot)
2151
- this.#sendAuthoritySnapshot(snapshot);
2506
+ this.#afterHeldFrames(() => {
2507
+ const snapshot = binding.updatePresence(frame.state);
2508
+ if (!binding.onAuthoritySnapshot)
2509
+ this.#sendAuthoritySnapshot(snapshot);
2510
+ });
2152
2511
  return;
2153
2512
  }
2154
2513
  if (frame.type === "activity") {
2155
2514
  if (!this.#acceptAuthorityGeneration(frame.generation))
2156
2515
  return;
2157
2516
  this.#usesExplicitAuthority = true;
2158
- if (!this.#sessionRuntimeBinding?.noteActivity)
2517
+ const binding = this.#sessionRuntimeBinding;
2518
+ if (!binding?.noteActivity)
2159
2519
  return this.#failProtocol("protocol-error");
2160
- const snapshot = this.#sessionRuntimeBinding.noteActivity(frame.activity);
2161
- if (!this.#sessionRuntimeBinding.onAuthoritySnapshot)
2162
- this.#sendAuthoritySnapshot(snapshot);
2520
+ this.#afterHeldFrames(() => {
2521
+ const snapshot = binding.noteActivity(frame.activity);
2522
+ if (!binding.onAuthoritySnapshot)
2523
+ this.#sendAuthoritySnapshot(snapshot);
2524
+ });
2163
2525
  return;
2164
2526
  }
2165
2527
  if (frame.type === "authority-request") {
@@ -2169,44 +2531,57 @@ export class PaneStreamLiveConnection {
2169
2531
  if (!this.#sessionRuntimeBinding?.requestAuthority ||
2170
2532
  !this.#sessionRuntimeBinding.authoritySnapshot)
2171
2533
  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
- });
2534
+ const binding = this.#sessionRuntimeBinding;
2535
+ // While ownership is read again the request waits for it, in order with
2536
+ // input, instead of being rejected: a rejected request left a new stream
2537
+ // without input until the client gave up on it.
2538
+ const request = () => {
2539
+ let lease = null;
2540
+ try {
2541
+ lease = binding.requestAuthority(frame.authority);
2542
+ }
2543
+ catch (error) {
2544
+ if (this.#holdForWindowOwnership(error, request))
2545
+ return;
2546
+ // Topology changes can temporarily prevent ownership. Reject this
2547
+ // request without letting an expected conflict terminate the daemon.
2548
+ if (!(error instanceof SessionRuntimeControllerLeaseError) ||
2549
+ error.code !== "controller-conflict")
2550
+ return this.#failProtocol("input-rejected");
2551
+ }
2552
+ if (lease)
2553
+ this.#requestedAuthorities.add(frame.authority);
2554
+ this.#sendFrame(null, {
2555
+ type: "authority-receipt",
2556
+ requestId: frame.requestId,
2557
+ authority: frame.authority,
2558
+ status: lease ? "granted" : "rejected",
2559
+ lease,
2560
+ snapshot: binding.authoritySnapshot(),
2561
+ });
2562
+ };
2563
+ this.#afterWindowOwnership(request);
2193
2564
  return;
2194
2565
  }
2195
2566
  if (frame.type === "authority-release") {
2196
2567
  if (!this.#acceptAuthorityGeneration(frame.generation))
2197
2568
  return;
2198
2569
  this.#usesExplicitAuthority = true;
2199
- this.#requestedAuthorities.delete(frame.authority);
2200
- if (!this.#sessionRuntimeBinding?.releaseAuthority)
2570
+ const binding = this.#sessionRuntimeBinding;
2571
+ if (!binding?.releaseAuthority)
2201
2572
  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,
2573
+ // After any held request or input: a release must not overtake them.
2574
+ this.#afterHeldFrames(() => {
2575
+ this.#requestedAuthorities.delete(frame.authority);
2576
+ const snapshot = binding.releaseAuthority(frame.authority);
2577
+ this.#sendFrame(null, {
2578
+ type: "authority-receipt",
2579
+ requestId: frame.requestId,
2580
+ authority: frame.authority,
2581
+ status: "released",
2582
+ lease: null,
2583
+ snapshot,
2584
+ });
2210
2585
  });
2211
2586
  return;
2212
2587
  }
@@ -2256,7 +2631,7 @@ export class PaneStreamLiveConnection {
2256
2631
  return;
2257
2632
  }
2258
2633
  if (frame.type === "semantic-intent") {
2259
- this.#acceptSemanticIntent(frame.operationId, frame.intent);
2634
+ this.#afterHeldFrames(() => this.#acceptSemanticIntent(frame.operationId, frame.intent));
2260
2635
  return;
2261
2636
  }
2262
2637
  if (frame.type === "terminal-surface-watch") {
@@ -2413,35 +2788,40 @@ export class PaneStreamLiveConnection {
2413
2788
  if (!this.#prepareInputAuthority(true))
2414
2789
  return;
2415
2790
  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")) {
2791
+ const fit = () => {
2792
+ try {
2793
+ if (frame.semanticWindowId === undefined)
2794
+ this.#sessionRuntimeBinding.fitViewport(frame.authorityLease, frame.cols, frame.rows);
2795
+ else
2796
+ this.#sessionRuntimeBinding.fitViewport(frame.authorityLease, frame.cols, frame.rows, frame.semanticWindowId);
2433
2797
  this.#sendFrame(null, {
2434
2798
  type: "viewport-ack",
2435
2799
  seq: frame.seq,
2436
2800
  cols: frame.cols,
2437
2801
  rows: frame.rows,
2438
- outcome: "geometry-authority-conflict",
2802
+ outcome: "ok",
2439
2803
  authorityLease: frame.authorityLease,
2440
2804
  });
2441
- return;
2442
2805
  }
2443
- this.#failProtocol("input-rejected");
2444
- }
2806
+ catch (error) {
2807
+ if (error instanceof SessionRuntimeControllerLeaseError &&
2808
+ (error.code === "invalid-client-capability" || error.code === "stale-controller-lease")) {
2809
+ this.#sendFrame(null, {
2810
+ type: "viewport-ack",
2811
+ seq: frame.seq,
2812
+ cols: frame.cols,
2813
+ rows: frame.rows,
2814
+ outcome: "geometry-authority-conflict",
2815
+ authorityLease: frame.authorityLease,
2816
+ });
2817
+ return;
2818
+ }
2819
+ if (this.#holdForWindowOwnership(error, fit))
2820
+ return;
2821
+ this.#failProtocol("input-rejected");
2822
+ }
2823
+ };
2824
+ this.#afterWindowOwnership(fit);
2445
2825
  return;
2446
2826
  }
2447
2827
  this.#acceptInput(frame.pane, frame.seq, frame.kind, frame.data, byteLength, frame.performanceTraceId, frame.causalProbe, ingressAtMicros, callbackAtSharedMicros, ingressAtSharedMicros, frame.expectedLifetime);
@@ -2500,6 +2880,8 @@ export class PaneStreamLiveConnection {
2500
2880
  }
2501
2881
  #deliveryChannel(address) {
2502
2882
  const channel = this.#panes.get(address.semanticPaneId);
2883
+ if (channel?.retiredInPlace)
2884
+ return null;
2503
2885
  const expected = channel?.deliveryAddress;
2504
2886
  if (!channel?.delivery ||
2505
2887
  !expected ||
@@ -2583,6 +2965,8 @@ export class PaneStreamLiveConnection {
2583
2965
  }
2584
2966
  #acceptConsumed(pane, seq) {
2585
2967
  const channel = this.#panes.get(pane);
2968
+ if (channel?.retiredInPlace)
2969
+ return;
2586
2970
  if (!this.#deliveryAcks ||
2587
2971
  !channel ||
2588
2972
  seq <= channel.consumedSeq ||
@@ -2613,6 +2997,8 @@ export class PaneStreamLiveConnection {
2613
2997
  return;
2614
2998
  }
2615
2999
  const channel = this.#panes.get(pane);
3000
+ if (channel?.retiredInPlace)
3001
+ return;
2616
3002
  const semanticDelivery = this.#descriptor.terminalDelivery !== null;
2617
3003
  if (!channel ||
2618
3004
  channel.closed ||
@@ -2676,91 +3062,218 @@ export class PaneStreamLiveConnection {
2676
3062
  this.#inputWindowFrames += 1;
2677
3063
  this.#inputWindowBytes += frameBytes;
2678
3064
  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
- });
3065
+ const deliver = () => {
3066
+ // Held for an ownership read (#394) while the pane left the stream in
3067
+ // place: dropped like any other late frame for it, not delivered.
3068
+ if (channel.retiredInPlace)
3069
+ return;
3070
+ try {
3071
+ this.#sessionRuntimeBinding.assertController(pane);
3072
+ if (semanticDelivery)
3073
+ this.#sessionRuntimeBinding.sendInput(pane, { kind, data }, performanceTraceId, causalProbe, causalProbe
3074
+ ? (result) => {
3075
+ if (this.#closed)
3076
+ return;
3077
+ if (result.status === "proved") {
3078
+ this.#sendFrame(null, { type: "causal-cell-proof", proof: result.proof });
3079
+ }
3080
+ else {
3081
+ this.#sendFrame(null, {
3082
+ type: "causal-cell-failure",
3083
+ failure: {
3084
+ version: 1,
3085
+ capability: "causal-cell-v1",
3086
+ traceId: result.traceId,
3087
+ reason: result.reason,
3088
+ ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
3089
+ },
3090
+ });
3091
+ }
2700
3092
  }
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) {
3093
+ : undefined, expectedLifetime);
3094
+ else if (kind === "text")
3095
+ channel.sub.sendText(data);
3096
+ else if (kind === "key")
3097
+ channel.sub.sendKey(data);
3098
+ else
3099
+ throw new Error("Byte input requires semantic runtime");
3100
+ let ackStartedAtMicros = null;
3101
+ let ackStartedAtSharedMicros = null;
3102
+ if (trace) {
2719
3103
  try {
2720
- ackStartedAtSharedMicros = this.#sharedMicros();
3104
+ ackStartedAtMicros = this.#observability.nowMicros();
2721
3105
  }
2722
3106
  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();
3107
+ // Diagnostics cannot alter protocol truth.
2740
3108
  }
2741
- catch {
2742
- // Preserve process-local ACK diagnostics.
3109
+ if (this.#diagnosticSharedRawMicros) {
3110
+ try {
3111
+ ackStartedAtSharedMicros = this.#sharedMicros();
3112
+ }
3113
+ catch {
3114
+ // Preserve process-local ACK diagnostics.
3115
+ }
2743
3116
  }
2744
3117
  }
2745
- if (ackEndedAtMicros !== null) {
3118
+ sendControl(this.#socket, { type: "input-ack", pane, seq });
3119
+ if (trace && ackStartedAtMicros !== null) {
3120
+ let ackEndedAtMicros = null;
2746
3121
  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
- });
3122
+ ackEndedAtMicros = this.#observability.nowMicros();
2753
3123
  }
2754
3124
  catch {
2755
3125
  // Diagnostics cannot alter protocol truth.
2756
3126
  }
3127
+ let ackEndedAtSharedMicros = null;
3128
+ if (ackStartedAtSharedMicros !== null) {
3129
+ try {
3130
+ ackEndedAtSharedMicros = this.#sharedMicros();
3131
+ }
3132
+ catch {
3133
+ // Preserve process-local ACK diagnostics.
3134
+ }
3135
+ }
3136
+ if (ackEndedAtMicros !== null) {
3137
+ try {
3138
+ this.#observability.recordSpan("transport", "pane-stream-input-ack-socket-send", ackStartedAtMicros, ackEndedAtMicros, trace, ackStartedAtSharedMicros === null || ackEndedAtSharedMicros === null
3139
+ ? undefined
3140
+ : {
3141
+ startedAtMicros: ackStartedAtSharedMicros,
3142
+ endedAtMicros: ackEndedAtSharedMicros,
3143
+ });
3144
+ }
3145
+ catch {
3146
+ // Diagnostics cannot alter protocol truth.
3147
+ }
3148
+ }
2757
3149
  }
2758
3150
  }
3151
+ catch (error) {
3152
+ if (this.#holdForWindowOwnership(error, deliver))
3153
+ return;
3154
+ if (error instanceof SessionRuntimeInputLifetimeEndedError) {
3155
+ // Fenced to a lifetime that ended: not delivered, not acknowledged.
3156
+ // The pane's delivery tells the client its lifetime ended.
3157
+ this.#noteInputLifetimeEnded(pane, error);
3158
+ return;
3159
+ }
3160
+ this.#fail("control-frame-handler-failed", error);
3161
+ }
3162
+ };
3163
+ this.#afterWindowOwnership(deliver);
3164
+ }
3165
+ /**
3166
+ * Input and geometry frames that arrive while registered-window ownership is
3167
+ * being read again (another session was created or killed) wait for that
3168
+ * read, in arrival order, instead of closing the stream. The mirror refuses
3169
+ * them meanwhile; before, the stream closed with 1011 and the client had to
3170
+ * reconnect. Bounded: a read that does not settle in time closes as before.
3171
+ */
3172
+ #ownershipHeld = [];
3173
+ #ownershipDraining = false;
3174
+ /** Ends the drain's wait when the stream closes. */
3175
+ #ownershipWake = null;
3176
+ #afterWindowOwnership(run) {
3177
+ if (this.#ownershipHeld.length === 0 && !this.#mirror.windowOwnershipPending?.()) {
3178
+ run();
3179
+ return;
2759
3180
  }
2760
- catch (error) {
2761
- this.#fail("control-frame-handler-failed", error);
3181
+ this.#holdUntilWindowOwnership(run);
3182
+ }
3183
+ /**
3184
+ * Frames whose effect depends on authority order (release, presence,
3185
+ * activity, intents) are not held for the read themselves, but must not
3186
+ * overtake frames that are.
3187
+ */
3188
+ #afterHeldFrames(run) {
3189
+ if (this.#ownershipHeld.length === 0) {
3190
+ run();
3191
+ return;
3192
+ }
3193
+ this.#holdUntilWindowOwnership(run);
3194
+ }
3195
+ /** A refusal while ownership is pending holds the frame; anything else is the caller's. */
3196
+ #holdForWindowOwnership(error, run) {
3197
+ if (!(error instanceof SessionRuntimeControllerLeaseError) ||
3198
+ error.code !== "controller-conflict" ||
3199
+ !this.#mirror.windowOwnershipPending?.())
3200
+ return false;
3201
+ this.#ownershipHeld.unshift(run);
3202
+ if (!this.#ownershipDraining)
3203
+ void this.#drainWindowOwnership();
3204
+ return true;
3205
+ }
3206
+ #holdUntilWindowOwnership(run) {
3207
+ if (this.#ownershipHeld.length >= PANE_STREAM_OWNERSHIP_HELD_FRAMES) {
3208
+ this.#ownershipHeld.length = 0;
3209
+ this.#fail("window-ownership-held-overflow");
3210
+ return;
3211
+ }
3212
+ this.#ownershipHeld.push(run);
3213
+ if (!this.#ownershipDraining)
3214
+ void this.#drainWindowOwnership();
3215
+ }
3216
+ async #drainWindowOwnership() {
3217
+ this.#ownershipDraining = true;
3218
+ try {
3219
+ await this.#drainWindowOwnershipOnce();
3220
+ }
3221
+ finally {
3222
+ this.#ownershipDraining = false;
3223
+ }
3224
+ }
3225
+ async #drainWindowOwnershipOnce() {
3226
+ const deadline = Date.now() + this.#ownershipWaitMs;
3227
+ while (!this.#closed && this.#ownershipHeld.length > 0) {
3228
+ if (this.#mirror.windowOwnershipPending?.()) {
3229
+ const left = deadline - Date.now();
3230
+ if (left <= 0) {
3231
+ this.#ownershipHeld.length = 0;
3232
+ this.#fail("window-ownership-unverified");
3233
+ return;
3234
+ }
3235
+ const timers = [];
3236
+ const wait = (ms) => new Promise((resolve) => {
3237
+ const timer = setTimeout(resolve, ms);
3238
+ timer.unref?.();
3239
+ timers.push(timer);
3240
+ });
3241
+ const read = this.#mirror.verifyWindowOwnership?.();
3242
+ await Promise.race([
3243
+ // Without a read to wait on, poll instead of spinning.
3244
+ read ? read.catch(() => wait(25)) : wait(25),
3245
+ wait(left),
3246
+ new Promise((resolve) => {
3247
+ this.#ownershipWake = resolve;
3248
+ }),
3249
+ ]);
3250
+ this.#ownershipWake = null;
3251
+ for (const timer of timers)
3252
+ clearTimeout(timer);
3253
+ continue;
3254
+ }
3255
+ const run = this.#ownershipHeld.shift();
3256
+ const before = this.#ownershipHeld.length;
3257
+ run();
3258
+ // A refusal inside run() put it back at the front: wait again.
3259
+ if (this.#ownershipHeld.length > before)
3260
+ continue;
2762
3261
  }
2763
3262
  }
3263
+ #inputLifetimeEndedLogged = new Set();
3264
+ #inputLifetimeEndedDropped = 0;
3265
+ #noteInputLifetimeEnded(pane, error) {
3266
+ this.#inputLifetimeEndedDropped += 1;
3267
+ if (this.#inputLifetimeEndedLogged.has(pane))
3268
+ return;
3269
+ this.#inputLifetimeEndedLogged.add(pane);
3270
+ logger.info("pane-stream", "input for an ended pane lifetime not delivered", {
3271
+ session: this.#descriptor.sessionName,
3272
+ clientId: this.#clientId,
3273
+ pane,
3274
+ error: error.message.slice(0, 200),
3275
+ });
3276
+ }
2764
3277
  #failProtocol(code) {
2765
3278
  try {
2766
3279
  sendControl(this.#socket, {
@@ -2787,6 +3300,26 @@ export class PaneStreamLiveConnection {
2787
3300
  }
2788
3301
  #onSocketClose = () => this.close(1000, "peer-closed");
2789
3302
  }
3303
+ function newPaneChannel(pane) {
3304
+ return {
3305
+ semanticPaneId: pane,
3306
+ sub: null,
3307
+ delivery: null,
3308
+ deliveryAddress: null,
3309
+ serverSeq: 0,
3310
+ sentPaneFrames: 0,
3311
+ consumedSeq: 0,
3312
+ nextInputSeq: 1,
3313
+ frozenByWire: false,
3314
+ closed: false,
3315
+ batch: null,
3316
+ graphicsAnnounced: false,
3317
+ graphicsQueue: [],
3318
+ graphicsSending: false,
3319
+ graphicsServed: new Map(),
3320
+ graphicsState: null,
3321
+ };
3322
+ }
2790
3323
  function concatBytes(chunks) {
2791
3324
  if (chunks.length === 0)
2792
3325
  return new Uint8Array(0);