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
@@ -24,6 +24,9 @@ import {
24
24
  PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION,
25
25
  PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION,
26
26
  PANE_STREAM_READER_CAPABILITY_VERSION,
27
+ PANE_STREAM_BROWSER_KIND_CAPABILITY_VERSION,
28
+ PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION,
29
+ PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION,
27
30
  type PaneStreamInputLifetime,
28
31
  } from "@tmux-ide/contracts";
29
32
  import { inflateSync } from "node:zlib";
@@ -102,7 +105,10 @@ import {
102
105
  } from "../attachments/admission-util.ts";
103
106
  import type { DirectTerminalSocket } from "../attachments/direct-websocket.ts";
104
107
  import type { SessionRuntimeObservability } from "../session-runtime/runtime-observability.ts";
105
- import { SessionRuntimeControllerLeaseError } from "../session-runtime/registry.ts";
108
+ import {
109
+ SessionRuntimeControllerLeaseError,
110
+ SessionRuntimeInputLifetimeEndedError,
111
+ } from "../session-runtime/registry.ts";
106
112
  import { terminalDeliveryObservationOrdinal } from "../session-runtime/terminal-delivery-observation-identity.ts";
107
113
  import {
108
114
  PaneStreamLeaseError,
@@ -221,6 +227,9 @@ const BindingIdSchemaZ = z
221
227
  /** The mirror surface the endpoint consumes (MirrorService satisfies it). */
222
228
  export interface PaneStreamMirror {
223
229
  describeSession(session: string): Promise<MirrorSessionDescription>;
230
+ /** Registered-window ownership is being read again (a session came or went). */
231
+ windowOwnershipPending?(): boolean;
232
+ verifyWindowOwnership?(): Promise<void>;
224
233
  describeSessionAuthority?(
225
234
  session: string,
226
235
  expectedSemanticPaneIds?: readonly string[],
@@ -332,6 +341,10 @@ export interface PaneStreamAdmissionCoordinatorOptions {
332
341
  readonly flowBudgets?: PaneStreamFlowBudgets;
333
342
  /** Cadence of the send-buffer drain check while frames are in flight. */
334
343
  readonly drainTickMs?: number;
344
+ /** Waits between tries of a step of a stream's opening that failed (#585). */
345
+ readonly openRetryDelaysMs?: readonly number[];
346
+ /** How long input waits for registered-window ownership to be read again. */
347
+ readonly ownershipWaitMs?: number;
335
348
  /** Hard whole-socket ceiling; the ledger should stall panes far earlier. */
336
349
  readonly maxSocketBufferedBytes?: number;
337
350
  /** Input flood budget for one rolling admission window, never a lifetime quota. */
@@ -356,6 +369,15 @@ export interface SessionRuntimePaneStreamTransportBinding {
356
369
  readonly explicitAuthority?: boolean;
357
370
  readonly deliveryLaneId?: string;
358
371
  readonly deliveryRequestId?: string;
372
+ /**
373
+ * Amend the transport's exact pane grant when the session's pane set changes
374
+ * under a live stream (#723). Called by the daemon with panes from its own
375
+ * inventory; a binding without it cannot take a new pane in place.
376
+ */
377
+ amendPaneGrant?(change: {
378
+ readonly added: readonly string[];
379
+ readonly removed: readonly string[];
380
+ }): void;
359
381
  /** Optional only for the bounded v1 transport adapter. New clients require these methods. */
360
382
  authoritySnapshot?(): SessionRuntimeAuthoritySnapshot;
361
383
  activateLegacyAuthority?(geometry: boolean): SessionRuntimeAuthoritySnapshot;
@@ -402,6 +424,8 @@ export interface SessionRuntimeTerminalDeliveryConnection {
402
424
  materialize?(request: TerminalProjectionMaterialize): void;
403
425
  nack(nack: TerminalDeliveryNack): void;
404
426
  setVisibility(visibility: TerminalDeliveryVisibility): void;
427
+ /** The client typed into this pane: send its deliveries first. */
428
+ prioritize?(): void;
405
429
  close(): Promise<void>;
406
430
  readonly graphics?: TerminalDeliveryGraphics;
407
431
  }
@@ -477,6 +501,8 @@ export class PaneStreamAdmissionCoordinator {
477
501
  readonly #redemptionTimeoutMs: number;
478
502
  readonly #flowBudgets: PaneStreamFlowBudgets;
479
503
  readonly #drainTickMs: number;
504
+ readonly #openRetryDelaysMs: readonly number[];
505
+ readonly #ownershipWaitMs: number;
480
506
  readonly #maxSocketBufferedBytes: number;
481
507
  readonly #maxInputFrames: number;
482
508
  readonly #maxInputBytes: number;
@@ -517,6 +543,8 @@ export class PaneStreamAdmissionCoordinator {
517
543
  this.#flowBudgets = options.flowBudgets ?? DEFAULT_PANE_STREAM_FLOW_BUDGETS;
518
544
  this.#ledger = new PaneStreamWireLedger(this.#flowBudgets);
519
545
  this.#drainTickMs = boundedInteger(options.drainTickMs, 15, 1_000);
546
+ this.#openRetryDelaysMs = options.openRetryDelaysMs ?? PANE_STREAM_OPEN_RETRY_DELAYS_MS;
547
+ this.#ownershipWaitMs = options.ownershipWaitMs ?? PANE_STREAM_OWNERSHIP_WAIT_MS;
520
548
  this.#maxSocketBufferedBytes = boundedInteger(
521
549
  options.maxSocketBufferedBytes,
522
550
  32 << 20,
@@ -611,6 +639,23 @@ export class PaneStreamAdmissionCoordinator {
611
639
  );
612
640
  }
613
641
  }
642
+ // #806: a stream for one window is issued for exactly that window's
643
+ // panes, as the trusted inventory places them now.
644
+ if (request.semanticWindowId !== undefined) {
645
+ const windowPanes = new Set(
646
+ described.panes
647
+ .filter((pane) => pane.semanticWindowId === request.semanticWindowId)
648
+ .map((pane) => pane.semanticPaneId),
649
+ );
650
+ if (
651
+ windowPanes.size !== request.panes.length ||
652
+ request.panes.some((pane) => !windowPanes.has(pane))
653
+ )
654
+ throw new PaneStreamAdmissionError(
655
+ "pane-not-found",
656
+ "The panes are not exactly the panes of that window of the workspace session.",
657
+ );
658
+ }
614
659
 
615
660
  const issued = await this.#leaseManager.issue(request, {
616
661
  requestId,
@@ -905,6 +950,8 @@ export class PaneStreamAdmissionCoordinator {
905
950
  leaseManager: this.#leaseManager,
906
951
  ledger: this.#ledger,
907
952
  drainTickMs: this.#drainTickMs,
953
+ openRetryDelaysMs: this.#openRetryDelaysMs,
954
+ ownershipWaitMs: this.#ownershipWaitMs,
908
955
  maxSocketBufferedBytes: this.#maxSocketBufferedBytes,
909
956
  maxInputFrames: this.#maxInputFrames,
910
957
  maxInputBytes: this.#maxInputBytes,
@@ -1127,6 +1174,8 @@ interface LiveConnectionOptions {
1127
1174
  readonly leaseManager: PaneStreamLeaseAuthority;
1128
1175
  readonly ledger: PaneStreamWireLedger;
1129
1176
  readonly drainTickMs: number;
1177
+ readonly openRetryDelaysMs: readonly number[];
1178
+ readonly ownershipWaitMs: number;
1130
1179
  readonly maxSocketBufferedBytes: number;
1131
1180
  readonly maxInputFrames: number;
1132
1181
  readonly maxInputBytes: number;
@@ -1146,8 +1195,38 @@ interface SeedBatch {
1146
1195
  guardArmed: boolean;
1147
1196
  }
1148
1197
 
1198
+ /**
1199
+ * How long an in-place topology change waits for the layout that matches the
1200
+ * session's inventory, when the inventory read was newer than the layout in
1201
+ * hand (a split and a close in quick succession). After it the stream closes
1202
+ * as it would without capability 119.
1203
+ */
1204
+ export const PANE_STREAM_TOPOLOGY_SETTLE_MS = 500;
1205
+
1206
+ /** One pane's delivery, opened and negotiated but not yet announced to the client. */
1207
+ interface OpenedPaneDelivery {
1208
+ readonly channel: PaneChannel;
1209
+ readonly delivery: SessionRuntimeTerminalDeliveryConnection;
1210
+ readonly pending: TerminalDeliveryServerMessage[];
1211
+ readonly markNegotiated: () => void;
1212
+ readonly markReady: () => void;
1213
+ }
1214
+
1215
+ /** About half a second in all: long enough for one slow tmux answer, short for a user. */
1216
+ export const PANE_STREAM_OPEN_RETRY_DELAYS_MS: readonly number[] = [150, 400];
1217
+ /** Input waits this long for ownership to be read again before the stream closes. */
1218
+ export const PANE_STREAM_OWNERSHIP_WAIT_MS = 2_000;
1219
+ /** At most this many input and geometry frames wait for it. */
1220
+ export const PANE_STREAM_OWNERSHIP_HELD_FRAMES = 256;
1221
+
1149
1222
  interface PaneChannel {
1150
1223
  readonly semanticPaneId: string;
1224
+ /**
1225
+ * The pane left the session under a capability-119 stream. A client frame
1226
+ * that was already on its way for this pane (an ack, input) is dropped, not
1227
+ * a protocol error: the client could not know yet.
1228
+ */
1229
+ retiredInPlace?: boolean;
1151
1230
  sub: MirrorSubscription | null;
1152
1231
  delivery: SessionRuntimeTerminalDeliveryConnection | null;
1153
1232
  deliveryAddress: {
@@ -1228,6 +1307,8 @@ export class PaneStreamLiveConnection {
1228
1307
  readonly #leaseManager: PaneStreamLeaseAuthority;
1229
1308
  readonly #ledger: PaneStreamWireLedger;
1230
1309
  readonly #drainTickMs: number;
1310
+ readonly #openRetryDelaysMs: readonly number[];
1311
+ readonly #ownershipWaitMs: number;
1231
1312
  readonly #maxSocketBufferedBytes: number;
1232
1313
  readonly #maxInputFrames: number;
1233
1314
  readonly #maxInputBytes: number;
@@ -1241,6 +1322,13 @@ export class PaneStreamLiveConnection {
1241
1322
  readonly #panes = new Map<string, PaneChannel>();
1242
1323
  readonly #semanticLayouts = new Map<string, MirrorLayoutEvent>();
1243
1324
  #semanticExpectedPaneIds: readonly string[] | null = null;
1325
+ /** Capability 119 (#723): a changed pane set is announced, not a reason to close. */
1326
+ readonly #topologyInPlace: boolean;
1327
+ /** The stream was issued for every pane of its session: new panes join it. */
1328
+ #leasesWholeSession = false;
1329
+ #topologyReconciling = false;
1330
+ #topologyPending: MirrorLayoutAuthoritySnapshot | null = null;
1331
+ #topologyWaiter: (() => void) | null = null;
1244
1332
  #semanticRuntimeSessionId: string | null = null;
1245
1333
  #semanticWindowLinks: WindowLinkTopology | null = null;
1246
1334
  #semanticTopologyEpoch = -1;
@@ -1364,6 +1452,8 @@ export class PaneStreamLiveConnection {
1364
1452
  this.#leaseManager = options.leaseManager;
1365
1453
  this.#ledger = options.ledger;
1366
1454
  this.#drainTickMs = options.drainTickMs;
1455
+ this.#openRetryDelaysMs = options.openRetryDelaysMs;
1456
+ this.#ownershipWaitMs = options.ownershipWaitMs ?? PANE_STREAM_OWNERSHIP_WAIT_MS;
1367
1457
  this.#maxSocketBufferedBytes = options.maxSocketBufferedBytes;
1368
1458
  this.#maxInputFrames = options.maxInputFrames;
1369
1459
  this.#maxInputBytes = options.maxInputBytes;
@@ -1378,26 +1468,13 @@ export class PaneStreamLiveConnection {
1378
1468
  : undefined;
1379
1469
  this.#diagnosticAfterFrameParse = options.diagnosticAfterFrameParse;
1380
1470
  this.#onRetire = options.onRetire;
1381
- for (const pane of options.descriptor.panes) {
1382
- this.#panes.set(pane, {
1383
- semanticPaneId: pane,
1384
- sub: null,
1385
- delivery: null,
1386
- deliveryAddress: null,
1387
- serverSeq: 0,
1388
- sentPaneFrames: 0,
1389
- consumedSeq: 0,
1390
- nextInputSeq: 1,
1391
- frozenByWire: false,
1392
- closed: false,
1393
- batch: null,
1394
- graphicsAnnounced: false,
1395
- graphicsQueue: [],
1396
- graphicsSending: false,
1397
- graphicsServed: new Map(),
1398
- graphicsState: null,
1399
- });
1400
- }
1471
+ this.#topologyInPlace =
1472
+ options.descriptor.terminalDelivery?.protocolVersions.some(
1473
+ (version) =>
1474
+ version === PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION ||
1475
+ version === PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION,
1476
+ ) === true;
1477
+ for (const pane of options.descriptor.panes) this.#panes.set(pane, newPaneChannel(pane));
1401
1478
  }
1402
1479
 
1403
1480
  get clientId(): string {
@@ -1427,6 +1504,7 @@ export class PaneStreamLiveConnection {
1427
1504
  )
1428
1505
  ? { inputBytes: true as const }
1429
1506
  : {}),
1507
+ ...(this.#topologyInPlace ? { topologyInPlace: true as const } : {}),
1430
1508
  protocolVersion: PANE_STREAM_PROTOCOL_VERSION,
1431
1509
  daemonInstanceId: this.#binding.daemonInstanceId,
1432
1510
  requestId: this.#binding.requestId,
@@ -1440,7 +1518,12 @@ export class PaneStreamLiveConnection {
1440
1518
  : {}),
1441
1519
  });
1442
1520
  this.#recordDiagnosticLifecycle("pane-stream-server-ready");
1443
- } catch {
1521
+ } catch (error) {
1522
+ // The one 1011 that still closed without a cause in the log.
1523
+ this.#closeCause = {
1524
+ cause: "ready-frame-failed",
1525
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
1526
+ };
1444
1527
  this.close(1011, "stream-unavailable-describe");
1445
1528
  return;
1446
1529
  }
@@ -1480,8 +1563,14 @@ export class PaneStreamLiveConnection {
1480
1563
  // Whether this connection held input when it went: the next stream of
1481
1564
  // the same client can only be granted input once that is released.
1482
1565
  ...(this.#heldInput === null ? {} : { heldInput: this.#heldInput }),
1566
+ // Keys not delivered because their pane lifetime had ended (#397).
1567
+ ...(this.#inputLifetimeEndedDropped > 0
1568
+ ? { droppedEndedLifetimeInputs: this.#inputLifetimeEndedDropped }
1569
+ : {}),
1483
1570
  });
1484
1571
  this.#closed = true;
1572
+ this.#ownershipHeld.length = 0;
1573
+ this.#ownershipWake?.();
1485
1574
  for (const demand of this.#surfaceDemands.values()) demand.close();
1486
1575
  this.#surfaceDemands.clear();
1487
1576
  this.#surfaceViewer?.close();
@@ -1548,7 +1637,9 @@ export class PaneStreamLiveConnection {
1548
1637
  // is absence; a describe FAILURE is not and fails the connection).
1549
1638
  let described: MirrorSessionDescription;
1550
1639
  try {
1551
- described = await this.#mirror.describeSession(this.#descriptor.sessionName);
1640
+ described = await this.#retryOpenStep("describe-session", () =>
1641
+ this.#mirror.describeSession(this.#descriptor.sessionName),
1642
+ );
1552
1643
  } catch (error) {
1553
1644
  this.#fail("describe-session-failed", error);
1554
1645
  return;
@@ -1603,6 +1694,42 @@ export class PaneStreamLiveConnection {
1603
1694
  this.#closeIfAllPanesGone();
1604
1695
  }
1605
1696
 
1697
+ /**
1698
+ * One step of a stream's opening, tried again after a failure (#585): on a
1699
+ * loaded host one slow tmux answer failed the step, the step closed the whole
1700
+ * stream with 1011, and nothing was tried twice. A refusal of authority is a
1701
+ * decision, not a failure, and is never repeated. Each repeat is logged.
1702
+ */
1703
+ async #retryOpenStep<T>(
1704
+ step: string,
1705
+ run: () => Promise<T>,
1706
+ final: (error: unknown) => boolean = () => false,
1707
+ ): Promise<T> {
1708
+ for (let attempt = 0; ; attempt += 1) {
1709
+ try {
1710
+ return await run();
1711
+ } catch (error) {
1712
+ const delayMs = this.#openRetryDelaysMs[attempt];
1713
+ if (
1714
+ delayMs === undefined ||
1715
+ this.#closed ||
1716
+ error instanceof SessionRuntimeControllerLeaseError ||
1717
+ final(error)
1718
+ )
1719
+ throw error;
1720
+ logger.info("pane-stream", "stream open step failed; trying again", {
1721
+ session: this.#descriptor.sessionName,
1722
+ clientId: this.#clientId,
1723
+ step,
1724
+ attempt: attempt + 1,
1725
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
1726
+ });
1727
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
1728
+ if (this.#closed) throw error;
1729
+ }
1730
+ }
1731
+ }
1732
+
1606
1733
  async #subscribeSemantic(known: ReadonlySet<string>): Promise<void> {
1607
1734
  const binding = this.#sessionRuntimeBinding;
1608
1735
  const offer = this.#descriptor.terminalDelivery;
@@ -1623,24 +1750,38 @@ export class PaneStreamLiveConnection {
1623
1750
  let stagedAuthority: MirrorLayoutAuthoritySnapshot | null = null;
1624
1751
  let authorityMalformed = false;
1625
1752
  let layoutActivated = false;
1753
+ let layoutAttempt = 0;
1626
1754
  // Establish the single session layout observer first. MirrorService owns
1627
1755
  // this lifecycle and may share native control state with delivery setup;
1628
1756
  // only the independent pane delivery opens below are parallelized.
1629
1757
  try {
1630
- if (!this.#mirror.subscribeLayout) throw new Error("authoritative layout is unavailable");
1631
- const subscription = await this.#mirror.subscribeLayout(
1632
- this.#descriptor.sessionName,
1633
- () => undefined,
1634
- {
1635
- expectedSemanticPaneIds: expectedPaneIds,
1636
- expectedRuntimeSessionId: this.#descriptor.runtimeSessionId!,
1637
- onAuthority: (snapshot) => {
1638
- this.#recordDiagnosticLifecycle("pane-stream-layout-staged");
1639
- if (snapshot.layouts.length > PANE_STREAM_MAX_PANES) authorityMalformed = true;
1640
- else if (!layoutActivated) stagedAuthority = snapshot;
1641
- else this.#onLayoutAuthority(snapshot);
1642
- },
1758
+ const subscribeLayout = this.#mirror.subscribeLayout?.bind(this.#mirror);
1759
+ if (!subscribeLayout) throw new Error("authoritative layout is unavailable");
1760
+ // The session's trusted inventory can be unsettled for a moment after a
1761
+ // pane change ("lacks verified identity"): a stream re-issued at once
1762
+ // closed 1011 while the next, 100 ms later, opened. Try again, as the
1763
+ // other opening steps do (#585). A changed pane set is a decision, not
1764
+ // a failure, and still closes 1012 at once. A try that failed is
1765
+ // disowned: its authority callback is ignored.
1766
+ const subscription = await this.#retryOpenStep(
1767
+ "semantic-layout-subscribe",
1768
+ () => {
1769
+ const attempt = ++layoutAttempt;
1770
+ stagedAuthority = null;
1771
+ authorityMalformed = false;
1772
+ return subscribeLayout(this.#descriptor.sessionName, () => undefined, {
1773
+ expectedSemanticPaneIds: expectedPaneIds,
1774
+ expectedRuntimeSessionId: this.#descriptor.runtimeSessionId!,
1775
+ onAuthority: (snapshot) => {
1776
+ if (attempt !== layoutAttempt) return;
1777
+ this.#recordDiagnosticLifecycle("pane-stream-layout-staged");
1778
+ if (snapshot.layouts.length > PANE_STREAM_MAX_PANES) authorityMalformed = true;
1779
+ else if (!layoutActivated) stagedAuthority = snapshot;
1780
+ else this.#onLayoutAuthority(snapshot);
1781
+ },
1782
+ });
1643
1783
  },
1784
+ (error) => error instanceof Error && error.name === "MirrorTopologyChangedError",
1644
1785
  );
1645
1786
  if (this.#closed) {
1646
1787
  await subscription.close().catch(() => undefined);
@@ -1696,32 +1837,7 @@ export class PaneStreamLiveConnection {
1696
1837
  // removes N x attachment latency without allowing a fast pane to make the
1697
1838
  // session look ready while a sibling is still missing. allSettled is
1698
1839
  // deliberate: partial success is always closed before the socket retires.
1699
- const openings = channels.map(async (channel) => {
1700
- const pending: TerminalDeliveryServerMessage[] = [];
1701
- let ready = false;
1702
- let negotiated = false;
1703
- const delivery = await binding.openTerminalDelivery(
1704
- channel.semanticPaneId,
1705
- offer,
1706
- (message) => {
1707
- if (!ready && !(negotiated && message.type === "terminal.delivery.fault"))
1708
- pending.push(message);
1709
- else return this.#sendTerminalDelivery(channel.semanticPaneId, message);
1710
- },
1711
- this.#descriptor.workspaceName,
1712
- );
1713
- return {
1714
- channel,
1715
- delivery,
1716
- pending,
1717
- markNegotiated: () => {
1718
- negotiated = true;
1719
- },
1720
- markReady: () => {
1721
- ready = true;
1722
- },
1723
- };
1724
- });
1840
+ const openings = channels.map((channel) => this.#openPaneDelivery(binding, offer, channel));
1725
1841
  const settled = await Promise.allSettled(openings);
1726
1842
  const opened = settled.flatMap((result) =>
1727
1843
  result.status === "fulfilled" ? [result.value] : [],
@@ -1743,27 +1859,7 @@ export class PaneStreamLiveConnection {
1743
1859
  return;
1744
1860
  }
1745
1861
 
1746
- const deliveryIdentityChanged = opened.some(({ channel, delivery, pending }) => {
1747
- if (!delivery.negotiation.accepted) return true;
1748
- const negotiated = delivery.negotiation.negotiated;
1749
- if (negotiated.generation !== this.#binding.daemonInstanceId) return true;
1750
- let incarnation: string | null = null;
1751
- for (const message of pending) {
1752
- if (message.type !== "terminal.delivery" && message.type !== "terminal.projection")
1753
- continue;
1754
- if (
1755
- message.workspaceName !== this.#descriptor.workspaceName ||
1756
- message.semanticPaneId !== channel.semanticPaneId ||
1757
- message.generation !== negotiated.generation ||
1758
- message.deliveryNonce !== negotiated.deliveryNonce ||
1759
- (incarnation !== null && message.incarnation !== incarnation)
1760
- )
1761
- return true;
1762
- incarnation = message.incarnation;
1763
- }
1764
- return false;
1765
- });
1766
- if (deliveryIdentityChanged) {
1862
+ if (opened.some((entry) => this.#deliveryIdentityChanged(entry))) {
1767
1863
  await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
1768
1864
  this.#failTopologyChanged();
1769
1865
  return;
@@ -1794,6 +1890,7 @@ export class PaneStreamLiveConnection {
1794
1890
  }
1795
1891
  this.#recordDiagnosticLifecycle("pane-stream-layout-validated");
1796
1892
  this.#semanticExpectedPaneIds = expectedPaneIds;
1893
+ this.#leasesWholeSession = expectedPaneIds.every((pane) => this.#panes.has(pane));
1797
1894
  this.#semanticRuntimeSessionId = authority!.runtimeSessionId;
1798
1895
  this.#semanticWindowLinks = authority!.windowLinks;
1799
1896
  this.#semanticTopologyEpoch = authority!.topologyEpoch;
@@ -1822,6 +1919,70 @@ export class PaneStreamLiveConnection {
1822
1919
  Number(visibleAtDelivery.has(right.channel.semanticPaneId)) -
1823
1920
  Number(visibleAtDelivery.has(left.channel.semanticPaneId)),
1824
1921
  );
1922
+ await this.#publishOpenedDeliveries(opened);
1923
+ this.#closeIfAllPanesGone();
1924
+ }
1925
+
1926
+ /** Open one pane's delivery; its messages wait until the pane is announced. */
1927
+ async #openPaneDelivery(
1928
+ binding: SessionRuntimePaneStreamTransportBinding,
1929
+ offer: NonNullable<PaneStreamLeaseDescriptor["terminalDelivery"]>,
1930
+ channel: PaneChannel,
1931
+ ): Promise<OpenedPaneDelivery> {
1932
+ const pending: TerminalDeliveryServerMessage[] = [];
1933
+ let ready = false;
1934
+ let negotiated = false;
1935
+ // #585: a failed open is tried again (150 ms, 400 ms) before the stream
1936
+ // closes; this applies to a pane added in place too.
1937
+ const delivery = await this.#retryOpenStep("pane-delivery-open", () => {
1938
+ // A try that failed may have delivered something; start clean.
1939
+ pending.length = 0;
1940
+ return binding.openTerminalDelivery(
1941
+ channel.semanticPaneId,
1942
+ offer,
1943
+ (message) => {
1944
+ if (!ready && !(negotiated && message.type === "terminal.delivery.fault"))
1945
+ pending.push(message);
1946
+ else return this.#sendTerminalDelivery(channel.semanticPaneId, message);
1947
+ },
1948
+ this.#descriptor.workspaceName,
1949
+ );
1950
+ });
1951
+ return {
1952
+ channel,
1953
+ delivery,
1954
+ pending,
1955
+ markNegotiated: () => {
1956
+ negotiated = true;
1957
+ },
1958
+ markReady: () => {
1959
+ ready = true;
1960
+ },
1961
+ };
1962
+ }
1963
+
1964
+ #deliveryIdentityChanged({ channel, delivery, pending }: OpenedPaneDelivery): boolean {
1965
+ if (!delivery.negotiation.accepted) return true;
1966
+ const negotiated = delivery.negotiation.negotiated;
1967
+ if (negotiated.generation !== this.#binding.daemonInstanceId) return true;
1968
+ let incarnation: string | null = null;
1969
+ for (const message of pending) {
1970
+ if (message.type !== "terminal.delivery" && message.type !== "terminal.projection") continue;
1971
+ if (
1972
+ message.workspaceName !== this.#descriptor.workspaceName ||
1973
+ message.semanticPaneId !== channel.semanticPaneId ||
1974
+ message.generation !== negotiated.generation ||
1975
+ message.deliveryNonce !== negotiated.deliveryNonce ||
1976
+ (incarnation !== null && message.incarnation !== incarnation)
1977
+ )
1978
+ return true;
1979
+ incarnation = message.incarnation;
1980
+ }
1981
+ return false;
1982
+ }
1983
+
1984
+ /** Announce validated deliveries, then replay what each collected meanwhile. */
1985
+ async #publishOpenedDeliveries(opened: readonly OpenedPaneDelivery[]): Promise<void> {
1825
1986
  for (const { channel, delivery, markNegotiated } of opened) {
1826
1987
  if (this.#closed || channel.closed) {
1827
1988
  await delivery.close();
@@ -1868,10 +2029,46 @@ export class PaneStreamLiveConnection {
1868
2029
  markReady();
1869
2030
  this.#startGraphics(channel);
1870
2031
  }
1871
- this.#closeIfAllPanesGone();
1872
2032
  }
1873
2033
 
2034
+ /**
2035
+ * A tombstone ends a pane's delivery for good: the hub drops the pane and
2036
+ * sends nothing more. Without capability 119 the pane's removal closes the
2037
+ * stream anyway. With it, the removal arrives as a `topology` frame within
2038
+ * moments; if none comes, the pane is still in the session and would stay
2039
+ * blank for ever, so the stream closes as it would without the capability
2040
+ * and the client takes a new one.
2041
+ */
2042
+ #watchTombstone(pane: string): void {
2043
+ const channel = this.#panes.get(pane);
2044
+ if (!this.#topologyInPlace || !channel || channel.closed) return;
2045
+ const timer = setTimeout(() => {
2046
+ if (this.#closed || channel.retiredInPlace || this.#panes.get(pane) !== channel) return;
2047
+ // A change being applied may be the one that removes this pane (kill-pane
2048
+ // plus split: the new pane's delivery can take longer to open than the
2049
+ // settle time). Decide again once it is done, with a fresh settle time.
2050
+ if (this.#topologyReconciling) {
2051
+ this.#tombstonesAfterChange.add(channel);
2052
+ return;
2053
+ }
2054
+ this.#failTopologyChanged("a pane that stays lost its source");
2055
+ }, PANE_STREAM_TOPOLOGY_SETTLE_MS);
2056
+ timer.unref?.();
2057
+ }
2058
+
2059
+ /**
2060
+ * Tombstoned channels whose guard came due while a change was being applied.
2061
+ * The channel, not the pane id: a pane that left and came back within the
2062
+ * change has a fresh channel, which this tombstone is not about.
2063
+ */
2064
+ readonly #tombstonesAfterChange = new Set<PaneChannel>();
2065
+
1874
2066
  async #sendTerminalDelivery(pane: string, message: TerminalDeliveryServerMessage): Promise<void> {
2067
+ if (
2068
+ (message.type === "terminal.delivery" || message.type === "terminal.projection") &&
2069
+ message.frame === "tombstone"
2070
+ )
2071
+ this.#watchTombstone(pane);
1875
2072
  if (message.type === "terminal.projection") {
1876
2073
  const channel = this.#panes.get(pane);
1877
2074
  if (channel?.deliveryAddress) channel.deliveryAddress.incarnation = message.incarnation;
@@ -2025,7 +2222,8 @@ export class PaneStreamLiveConnection {
2025
2222
  (version) =>
2026
2223
  version === TERMINAL_GRAPHICS_ZLIB_CAPABILITY_VERSION ||
2027
2224
  version === PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION ||
2028
- version === PANE_STREAM_READER_CAPABILITY_VERSION,
2225
+ version === PANE_STREAM_READER_CAPABILITY_VERSION ||
2226
+ version === PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION,
2029
2227
  ) === true;
2030
2228
  channel.graphicsZlib = zlib;
2031
2229
  channel.graphicsLocal =
@@ -2433,18 +2631,29 @@ export class PaneStreamLiveConnection {
2433
2631
 
2434
2632
  #onLayoutAuthority(snapshot: MirrorLayoutAuthoritySnapshot): void {
2435
2633
  if (this.#closed || !this.#semanticExpectedPaneIds || !this.#semanticRuntimeSessionId) return;
2436
- if (
2437
- snapshot.session !== this.#descriptor.sessionName ||
2438
- snapshot.runtimeSessionId !== this.#semanticRuntimeSessionId ||
2439
- snapshot.topologyEpoch <= this.#semanticTopologyEpoch ||
2440
- snapshot.layouts.length > PANE_STREAM_MAX_PANES
2441
- ) {
2634
+ if (this.#topologyReconciling) {
2635
+ // One change at a time, and only the newest state is worth announcing.
2636
+ this.#topologyPending = snapshot;
2637
+ this.#topologyWaiter?.();
2638
+ return;
2639
+ }
2640
+ if (!this.#layoutAuthorityAdmissible(snapshot)) {
2442
2641
  this.#failTopologyChanged();
2443
2642
  return;
2444
2643
  }
2445
2644
  const frames = this.#validateInitialLayout(snapshot.layouts, this.#semanticExpectedPaneIds);
2645
+ // #806: a pane can also move between windows while the session keeps its
2646
+ // panes; for a stream of one window that changes its pane set.
2647
+ const windowChanged = frames !== null && this.#windowPaneSetChanged(snapshot);
2648
+ if ((!frames || windowChanged) && this.#topologyInPlace) {
2649
+ // The layout does not fit the pane set this stream knows. With
2650
+ // capability 119 that is a change to follow, not a reason to close.
2651
+ void this.#reconcileTopology(snapshot);
2652
+ return;
2653
+ }
2446
2654
  if (
2447
2655
  !frames ||
2656
+ windowChanged ||
2448
2657
  !PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
2449
2658
  type: "layout-snapshot",
2450
2659
  topologyEpoch: snapshot.topologyEpoch,
@@ -2455,8 +2664,50 @@ export class PaneStreamLiveConnection {
2455
2664
  this.#failTopologyChanged();
2456
2665
  return;
2457
2666
  }
2667
+ if (!this.#windowLinksAdmissible(snapshot)) {
2668
+ this.#failTopologyChanged();
2669
+ return;
2670
+ }
2671
+ this.#semanticWindowLinks = snapshot.windowLinks;
2672
+ this.#semanticTopologyEpoch = snapshot.topologyEpoch;
2673
+ this.#semanticLayouts.clear();
2674
+ for (const event of snapshot.layouts)
2675
+ this.#semanticLayouts.set(event.semanticWindowId as string, event);
2676
+ this.#sendFrame(null, {
2677
+ type: "layout-snapshot",
2678
+ topologyEpoch: snapshot.topologyEpoch,
2679
+ layouts: frames,
2680
+ windowLinks: snapshot.windowLinks,
2681
+ });
2682
+ }
2683
+
2684
+ /** #806: the layout no longer shows this stream's window with exactly its panes. */
2685
+ #windowPaneSetChanged(snapshot: MirrorLayoutAuthoritySnapshot): boolean {
2686
+ const window = this.#descriptor.semanticWindowId;
2687
+ if (window === null) return false;
2688
+ const live = [...this.#panes.values()]
2689
+ .filter((channel) => !channel.closed)
2690
+ .map((channel) => channel.semanticPaneId);
2691
+ const shown = snapshot.layouts.find((event) => event.semanticWindowId === window);
2692
+ if (!shown) return true;
2693
+ const panes = shown.panes.map((pane) => pane.semanticPaneId ?? "");
2694
+ if (shown.zoomed) return panes.length !== 1 || !live.includes(panes[0]!);
2695
+ return panes.length !== live.length || panes.some((pane) => !live.includes(pane));
2696
+ }
2697
+
2698
+ /** The same session and runtime, a newer epoch, a layout a stream can carry. */
2699
+ #layoutAuthorityAdmissible(snapshot: MirrorLayoutAuthoritySnapshot): boolean {
2700
+ return (
2701
+ snapshot.session === this.#descriptor.sessionName &&
2702
+ snapshot.runtimeSessionId === this.#semanticRuntimeSessionId &&
2703
+ snapshot.topologyEpoch > this.#semanticTopologyEpoch &&
2704
+ snapshot.layouts.length <= PANE_STREAM_MAX_PANES
2705
+ );
2706
+ }
2707
+
2708
+ #windowLinksAdmissible(snapshot: MirrorLayoutAuthoritySnapshot): boolean {
2458
2709
  const previousLinks = this.#semanticWindowLinks;
2459
- if (
2710
+ return !(
2460
2711
  !previousLinks ||
2461
2712
  snapshot.windowLinks.liveSessionId !== previousLinks.liveSessionId ||
2462
2713
  snapshot.windowLinks.linkRevision < previousLinks.linkRevision ||
@@ -2465,21 +2716,259 @@ export class PaneStreamLiveConnection {
2465
2716
  [...snapshot.windowLinks.links].sort((a, b) => a.linkId.localeCompare(b.linkId)),
2466
2717
  ) !==
2467
2718
  JSON.stringify([...previousLinks.links].sort((a, b) => a.linkId.localeCompare(b.linkId))))
2719
+ );
2720
+ }
2721
+
2722
+ /**
2723
+ * Capability 119 (#723). Follow a changed pane set without closing: one
2724
+ * change at a time, newest state only. Every doubt ends where a stream
2725
+ * without the capability ends, in `#failTopologyChanged()`.
2726
+ */
2727
+ async #reconcileTopology(first: MirrorLayoutAuthoritySnapshot): Promise<void> {
2728
+ this.#topologyReconciling = true;
2729
+ let snapshot = first;
2730
+ try {
2731
+ for (;;) {
2732
+ this.#topologyPending = null;
2733
+ const outcome = await this.#applyTopology(snapshot);
2734
+ if (this.#closed) return;
2735
+ if (outcome === "failed") return this.#failTopologyChanged(this.#topologyFailure);
2736
+ let next: MirrorLayoutAuthoritySnapshot | null = this.#topologyPending;
2737
+ if (outcome === "stale" && !next) {
2738
+ // The inventory was read after a further change: its layout follows.
2739
+ next = await this.#nextTopologySnapshot();
2740
+ if (this.#closed) return;
2741
+ if (!next) return this.#failTopologyChanged();
2742
+ }
2743
+ if (!next) return;
2744
+ if (!this.#layoutAuthorityAdmissible(next)) return this.#failTopologyChanged();
2745
+ snapshot = next;
2746
+ }
2747
+ } finally {
2748
+ this.#topologyReconciling = false;
2749
+ this.#topologyPending = null;
2750
+ const tombstoned = [...this.#tombstonesAfterChange];
2751
+ this.#tombstonesAfterChange.clear();
2752
+ for (const channel of tombstoned)
2753
+ if (this.#panes.get(channel.semanticPaneId) === channel)
2754
+ this.#watchTombstone(channel.semanticPaneId);
2755
+ }
2756
+ }
2757
+
2758
+ #nextTopologySnapshot(): Promise<MirrorLayoutAuthoritySnapshot | null> {
2759
+ if (this.#topologyPending) return Promise.resolve(this.#topologyPending);
2760
+ return new Promise((resolve) => {
2761
+ const finish = (): void => {
2762
+ clearTimeout(timer);
2763
+ this.#topologyWaiter = null;
2764
+ resolve(this.#topologyPending);
2765
+ };
2766
+ const timer = setTimeout(finish, PANE_STREAM_TOPOLOGY_SETTLE_MS);
2767
+ timer.unref?.();
2768
+ this.#topologyWaiter = finish;
2769
+ });
2770
+ }
2771
+
2772
+ /**
2773
+ * "applied": the client was told and the stream goes on. "stale": this
2774
+ * layout does not fit the session's inventory as read now; a newer layout
2775
+ * decides. "failed": close.
2776
+ */
2777
+ async #applyTopology(
2778
+ snapshot: MirrorLayoutAuthoritySnapshot,
2779
+ ): Promise<"applied" | "stale" | "failed"> {
2780
+ const binding = this.#sessionRuntimeBinding;
2781
+ const offer = this.#descriptor.terminalDelivery;
2782
+ if (
2783
+ !binding ||
2784
+ !offer ||
2785
+ !this.#semanticExpectedPaneIds ||
2786
+ !this.#windowLinksAdmissible(snapshot)
2787
+ )
2788
+ return this.#topologyFailed("not a semantic stream, or its window links changed");
2789
+ // A zoomed window lists one pane, so the layout alone cannot tell which
2790
+ // panes exist: the trusted inventory does.
2791
+ // The inventory is read by session NAME. Only an inventory that states
2792
+ // the runtime session this stream was issued for may extend the grant: a
2793
+ // session replaced under the same name is another session.
2794
+ let described: MirrorSessionDescription;
2795
+ let inventoryIsThisSession = false;
2796
+ try {
2797
+ if (this.#mirror.describeSessionAuthority) {
2798
+ const authority = await this.#mirror.describeSessionAuthority(this.#descriptor.sessionName);
2799
+ if (authority.runtimeSessionId !== this.#semanticRuntimeSessionId)
2800
+ return this.#topologyFailed("inventory is of another runtime session");
2801
+ described = authority.description;
2802
+ inventoryIsThisSession = true;
2803
+ } else {
2804
+ described = await this.#mirror.describeSession(this.#descriptor.sessionName);
2805
+ }
2806
+ } catch (error) {
2807
+ return this.#topologyFailed("session inventory unavailable", error);
2808
+ }
2809
+ if (this.#closed) return this.#topologyFailed("closed");
2810
+ const next = [...new Set(described.panes.map((pane) => pane.semanticPaneId))].sort();
2811
+ if (next.length === 0) return this.#topologyFailed("session has no panes");
2812
+ const frames = this.#validateInitialLayout(snapshot.layouts, next);
2813
+ if (!frames) return "stale";
2814
+ if (
2815
+ !PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
2816
+ type: "layout-snapshot",
2817
+ topologyEpoch: snapshot.topologyEpoch,
2818
+ layouts: frames,
2819
+ windowLinks: snapshot.windowLinks,
2820
+ }).success
2821
+ )
2822
+ return this.#topologyFailed("layout snapshot invalid");
2823
+ // #806: a stream issued for one window follows that window's panes, as the
2824
+ // trusted inventory places them, and the same layout must show that window
2825
+ // with exactly those panes (a zoomed window shows one of them).
2826
+ const window = this.#descriptor.semanticWindowId;
2827
+ let windowPanes: string[] | null = null;
2828
+ if (window !== null) {
2829
+ windowPanes = [
2830
+ ...new Set(
2831
+ described.panes
2832
+ .filter((pane) => pane.semanticWindowId === window)
2833
+ .map((pane) => pane.semanticPaneId),
2834
+ ),
2835
+ ].sort();
2836
+ if (windowPanes.length === 0) return this.#topologyFailed("the stream's window is gone");
2837
+ const shown = snapshot.layouts.find((event) => event.semanticWindowId === window);
2838
+ const shownPanes = (shown?.panes ?? []).map((pane) => pane.semanticPaneId ?? "");
2839
+ if (
2840
+ !shown ||
2841
+ (shown.zoomed
2842
+ ? shownPanes.length !== 1 || !windowPanes.includes(shownPanes[0]!)
2843
+ : shownPanes.length !== windowPanes.length ||
2844
+ shownPanes.some((pane) => !windowPanes!.includes(pane)))
2845
+ )
2846
+ return "stale";
2847
+ }
2848
+ const followed = windowPanes ?? next;
2849
+ const live = [...this.#panes.values()].filter((channel) => !channel.closed);
2850
+ const removed = live.filter((channel) => !followed.includes(channel.semanticPaneId));
2851
+ // A stream issued for the whole session follows it, and one issued for a
2852
+ // window follows that window; one issued for some panes keeps exactly those.
2853
+ const liveIds = new Set(live.map((channel) => channel.semanticPaneId));
2854
+ const added =
2855
+ windowPanes !== null || this.#leasesWholeSession
2856
+ ? followed.filter((pane) => !liveIds.has(pane))
2857
+ : [];
2858
+ if (added.length > 0 && !inventoryIsThisSession)
2859
+ return this.#topologyFailed("inventory cannot prove the runtime session");
2860
+ const remaining = live.length - removed.length + added.length;
2861
+ if (remaining === 0 || remaining > PANE_STREAM_MAX_PANES)
2862
+ return this.#topologyFailed("pane count outside the stream limit");
2863
+
2864
+ // The transport's pane grant is exact. The daemon amends it from its own
2865
+ // inventory of this session before a new pane's delivery can open.
2866
+ if (added.length > 0) {
2867
+ try {
2868
+ if (!binding.amendPaneGrant)
2869
+ return this.#topologyFailed("transport cannot amend its grant");
2870
+ binding.amendPaneGrant({ added, removed: [] });
2871
+ } catch (error) {
2872
+ return this.#topologyFailed("pane grant refused", error);
2873
+ }
2874
+ }
2875
+ const channels = added.map(newPaneChannel);
2876
+ const settled = await Promise.allSettled(
2877
+ channels.map((channel) => this.#openPaneDelivery(binding, offer, channel)),
2878
+ );
2879
+ const opened = settled.flatMap((result) =>
2880
+ result.status === "fulfilled" ? [result.value] : [],
2881
+ );
2882
+ if (
2883
+ this.#closed ||
2884
+ opened.length !== channels.length ||
2885
+ opened.some((entry) => this.#deliveryIdentityChanged(entry))
2468
2886
  ) {
2469
- this.#failTopologyChanged();
2470
- return;
2887
+ await Promise.all(opened.map(({ delivery }) => delivery.close().catch(() => undefined)));
2888
+ if (added.length > 0) {
2889
+ try {
2890
+ binding.amendPaneGrant?.({ added: [], removed: added });
2891
+ } catch {
2892
+ // The stream closes; its binding and grant go with it.
2893
+ }
2894
+ }
2895
+ const rejected = settled.find((result) => result.status === "rejected");
2896
+ return this.#topologyFailed(
2897
+ this.#closed
2898
+ ? "closed while opening"
2899
+ : rejected
2900
+ ? "delivery open rejected"
2901
+ : opened.some((entry) => !entry.delivery.negotiation.accepted)
2902
+ ? "delivery negotiation refused"
2903
+ : "delivery identity changed",
2904
+ rejected?.status === "rejected" ? rejected.reason : undefined,
2905
+ );
2906
+ }
2907
+
2908
+ // Commit. From here on nothing can fail the change.
2909
+ if (removed.length > 0) {
2910
+ try {
2911
+ binding.amendPaneGrant?.({
2912
+ added: [],
2913
+ removed: removed.map((channel) => channel.semanticPaneId),
2914
+ });
2915
+ } catch {
2916
+ // A pane that is gone cannot be used through a grant that lingers.
2917
+ }
2471
2918
  }
2919
+ for (const channel of removed) this.#retirePaneInPlace(channel);
2920
+ for (const channel of channels) this.#panes.set(channel.semanticPaneId, channel);
2921
+ this.#semanticExpectedPaneIds = next;
2472
2922
  this.#semanticWindowLinks = snapshot.windowLinks;
2473
2923
  this.#semanticTopologyEpoch = snapshot.topologyEpoch;
2474
2924
  this.#semanticLayouts.clear();
2475
2925
  for (const event of snapshot.layouts)
2476
2926
  this.#semanticLayouts.set(event.semanticWindowId as string, event);
2927
+ this.#sendFrame(null, {
2928
+ type: "topology",
2929
+ topologyEpoch: snapshot.topologyEpoch,
2930
+ panes: [...this.#panes.values()]
2931
+ .filter((channel) => !channel.closed)
2932
+ .map((channel) => channel.semanticPaneId),
2933
+ removed: removed.map((channel) => channel.semanticPaneId),
2934
+ added,
2935
+ });
2477
2936
  this.#sendFrame(null, {
2478
2937
  type: "layout-snapshot",
2479
2938
  topologyEpoch: snapshot.topologyEpoch,
2480
2939
  layouts: frames,
2481
2940
  windowLinks: snapshot.windowLinks,
2482
2941
  });
2942
+ await this.#publishOpenedDeliveries(opened);
2943
+ return "applied";
2944
+ }
2945
+
2946
+ #topologyFailure = "";
2947
+ #topologyFailed(why: string, error?: unknown): "failed" {
2948
+ this.#topologyFailure = error === undefined ? why : `${why}: ${String(error).slice(0, 200)}`;
2949
+ return "failed";
2950
+ }
2951
+
2952
+ /** A pane that left the session: its delivery ends, the stream does not. */
2953
+ #retirePaneInPlace(channel: PaneChannel): void {
2954
+ const sub = channel.sub;
2955
+ const delivery = channel.delivery;
2956
+ channel.sub = null;
2957
+ channel.delivery = null;
2958
+ channel.closed = true;
2959
+ channel.retiredInPlace = true;
2960
+ // The channel stays only so late client frames for it are dropped; a long
2961
+ // stream under an agent that splits often must not keep each pane's buffers.
2962
+ channel.deliveryAddress = null;
2963
+ channel.batch = null;
2964
+ channel.graphicsQueue = [];
2965
+ channel.graphicsServed = new Map();
2966
+ channel.graphicsState = null;
2967
+ this.#surfaceDemands.get(channel.semanticPaneId)?.close();
2968
+ this.#surfaceDemands.delete(channel.semanticPaneId);
2969
+ if (sub) void sub.close().catch(() => undefined);
2970
+ if (delivery) void delivery.close().catch(() => undefined);
2971
+ this.#ledger.forgetPane(this.#clientId, channel.semanticPaneId);
2483
2972
  }
2484
2973
 
2485
2974
  #onLayout(event: MirrorLayoutEvent): void {
@@ -2507,7 +2996,15 @@ export class PaneStreamLiveConnection {
2507
2996
  }
2508
2997
 
2509
2998
  #offers(version: number): boolean {
2510
- return this.#descriptor.terminalDelivery?.protocolVersions.includes(version) === true;
2999
+ const offered = this.#descriptor.terminalDelivery?.protocolVersions;
3000
+ if (!offered) return false;
3001
+ // 120 stands for 118 and 119 together.
3002
+ return (
3003
+ offered.includes(version) ||
3004
+ ((version === PANE_STREAM_READER_CAPABILITY_VERSION ||
3005
+ version === PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION) &&
3006
+ offered.includes(PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION))
3007
+ );
2511
3008
  }
2512
3009
 
2513
3010
  #layoutFrame(event: MirrorLayoutEvent): PaneStreamServerFrame | null {
@@ -2532,6 +3029,9 @@ export class PaneStreamLiveConnection {
2532
3029
  ...(this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
2533
3030
  ? { reader: pane.reader ? { name: pane.reader.name } : null }
2534
3031
  : {}),
3032
+ ...(this.#offers(PANE_STREAM_BROWSER_KIND_CAPABILITY_VERSION)
3033
+ ? { browserKind: pane.browserKind ?? null }
3034
+ : {}),
2535
3035
  left: pane.left,
2536
3036
  top: pane.top,
2537
3037
  width: pane.width,
@@ -2583,8 +3083,10 @@ export class PaneStreamLiveConnection {
2583
3083
  return frames;
2584
3084
  }
2585
3085
 
2586
- #failTopologyChanged(): void {
3086
+ /** `inPlaceFailure`: why a capability-119 stream could not follow the change. */
3087
+ #failTopologyChanged(inPlaceFailure?: string): void {
2587
3088
  if (this.#closed) return;
3089
+ if (inPlaceFailure) this.#closeCause = { cause: `topology-in-place: ${inPlaceFailure}` };
2588
3090
  this.#sendFrame(null, {
2589
3091
  type: "error",
2590
3092
  protocolVersion: PANE_STREAM_PROTOCOL_VERSION,
@@ -2783,17 +3285,23 @@ export class PaneStreamLiveConnection {
2783
3285
  if (frame.type === "presence") {
2784
3286
  if (!this.#acceptAuthorityGeneration(frame.generation)) return;
2785
3287
  this.#usesExplicitAuthority = true;
2786
- if (!this.#sessionRuntimeBinding?.updatePresence) return this.#failProtocol("protocol-error");
2787
- const snapshot = this.#sessionRuntimeBinding.updatePresence(frame.state);
2788
- if (!this.#sessionRuntimeBinding.onAuthoritySnapshot) this.#sendAuthoritySnapshot(snapshot);
3288
+ const binding = this.#sessionRuntimeBinding;
3289
+ if (!binding?.updatePresence) return this.#failProtocol("protocol-error");
3290
+ this.#afterHeldFrames(() => {
3291
+ const snapshot = binding.updatePresence!(frame.state);
3292
+ if (!binding.onAuthoritySnapshot) this.#sendAuthoritySnapshot(snapshot);
3293
+ });
2789
3294
  return;
2790
3295
  }
2791
3296
  if (frame.type === "activity") {
2792
3297
  if (!this.#acceptAuthorityGeneration(frame.generation)) return;
2793
3298
  this.#usesExplicitAuthority = true;
2794
- if (!this.#sessionRuntimeBinding?.noteActivity) return this.#failProtocol("protocol-error");
2795
- const snapshot = this.#sessionRuntimeBinding.noteActivity(frame.activity);
2796
- if (!this.#sessionRuntimeBinding.onAuthoritySnapshot) this.#sendAuthoritySnapshot(snapshot);
3299
+ const binding = this.#sessionRuntimeBinding;
3300
+ if (!binding?.noteActivity) return this.#failProtocol("protocol-error");
3301
+ this.#afterHeldFrames(() => {
3302
+ const snapshot = binding.noteActivity!(frame.activity);
3303
+ if (!binding.onAuthoritySnapshot) this.#sendAuthoritySnapshot(snapshot);
3304
+ });
2797
3305
  return;
2798
3306
  }
2799
3307
  if (frame.type === "authority-request") {
@@ -2804,43 +3312,54 @@ export class PaneStreamLiveConnection {
2804
3312
  !this.#sessionRuntimeBinding.authoritySnapshot
2805
3313
  )
2806
3314
  return this.#failProtocol("protocol-error");
2807
- let lease: SessionRuntimeAuthorityLease | null = null;
2808
- try {
2809
- lease = this.#sessionRuntimeBinding.requestAuthority(frame.authority);
2810
- } catch (error) {
2811
- // Topology changes can temporarily prevent ownership. Reject this
2812
- // request without letting an expected conflict terminate the daemon.
2813
- if (
2814
- !(error instanceof SessionRuntimeControllerLeaseError) ||
2815
- error.code !== "controller-conflict"
2816
- )
2817
- return this.#failProtocol("input-rejected");
2818
- }
2819
- if (lease) this.#requestedAuthorities.add(frame.authority);
2820
- this.#sendFrame(null, {
2821
- type: "authority-receipt",
2822
- requestId: frame.requestId,
2823
- authority: frame.authority,
2824
- status: lease ? "granted" : "rejected",
2825
- lease,
2826
- snapshot: this.#sessionRuntimeBinding.authoritySnapshot(),
2827
- });
3315
+ const binding = this.#sessionRuntimeBinding;
3316
+ // While ownership is read again the request waits for it, in order with
3317
+ // input, instead of being rejected: a rejected request left a new stream
3318
+ // without input until the client gave up on it.
3319
+ const request = (): void => {
3320
+ let lease: SessionRuntimeAuthorityLease | null = null;
3321
+ try {
3322
+ lease = binding.requestAuthority!(frame.authority);
3323
+ } catch (error) {
3324
+ if (this.#holdForWindowOwnership(error, request)) return;
3325
+ // Topology changes can temporarily prevent ownership. Reject this
3326
+ // request without letting an expected conflict terminate the daemon.
3327
+ if (
3328
+ !(error instanceof SessionRuntimeControllerLeaseError) ||
3329
+ error.code !== "controller-conflict"
3330
+ )
3331
+ return this.#failProtocol("input-rejected");
3332
+ }
3333
+ if (lease) this.#requestedAuthorities.add(frame.authority);
3334
+ this.#sendFrame(null, {
3335
+ type: "authority-receipt",
3336
+ requestId: frame.requestId,
3337
+ authority: frame.authority,
3338
+ status: lease ? "granted" : "rejected",
3339
+ lease,
3340
+ snapshot: binding.authoritySnapshot!(),
3341
+ });
3342
+ };
3343
+ this.#afterWindowOwnership(request);
2828
3344
  return;
2829
3345
  }
2830
3346
  if (frame.type === "authority-release") {
2831
3347
  if (!this.#acceptAuthorityGeneration(frame.generation)) return;
2832
3348
  this.#usesExplicitAuthority = true;
2833
- this.#requestedAuthorities.delete(frame.authority);
2834
- if (!this.#sessionRuntimeBinding?.releaseAuthority)
2835
- return this.#failProtocol("protocol-error");
2836
- const snapshot = this.#sessionRuntimeBinding.releaseAuthority(frame.authority);
2837
- this.#sendFrame(null, {
2838
- type: "authority-receipt",
2839
- requestId: frame.requestId,
2840
- authority: frame.authority,
2841
- status: "released",
2842
- lease: null,
2843
- snapshot,
3349
+ const binding = this.#sessionRuntimeBinding;
3350
+ if (!binding?.releaseAuthority) return this.#failProtocol("protocol-error");
3351
+ // After any held request or input: a release must not overtake them.
3352
+ this.#afterHeldFrames(() => {
3353
+ this.#requestedAuthorities.delete(frame.authority);
3354
+ const snapshot = binding.releaseAuthority!(frame.authority);
3355
+ this.#sendFrame(null, {
3356
+ type: "authority-receipt",
3357
+ requestId: frame.requestId,
3358
+ authority: frame.authority,
3359
+ status: "released",
3360
+ lease: null,
3361
+ snapshot,
3362
+ });
2844
3363
  });
2845
3364
  return;
2846
3365
  }
@@ -2883,7 +3402,7 @@ export class PaneStreamLiveConnection {
2883
3402
  return;
2884
3403
  }
2885
3404
  if (frame.type === "semantic-intent") {
2886
- this.#acceptSemanticIntent(frame.operationId, frame.intent);
3405
+ this.#afterHeldFrames(() => this.#acceptSemanticIntent(frame.operationId, frame.intent));
2887
3406
  return;
2888
3407
  }
2889
3408
  if (frame.type === "terminal-surface-watch") {
@@ -3065,41 +3584,45 @@ export class PaneStreamLiveConnection {
3065
3584
  }
3066
3585
  if (!this.#prepareInputAuthority(true)) return;
3067
3586
  this.#nextViewportSeq += 1;
3068
- try {
3069
- if (frame.semanticWindowId === undefined)
3070
- this.#sessionRuntimeBinding!.fitViewport(frame.authorityLease, frame.cols, frame.rows);
3071
- else
3072
- this.#sessionRuntimeBinding!.fitViewport(
3073
- frame.authorityLease,
3074
- frame.cols,
3075
- frame.rows,
3076
- frame.semanticWindowId,
3077
- );
3078
- this.#sendFrame(null, {
3079
- type: "viewport-ack",
3080
- seq: frame.seq,
3081
- cols: frame.cols,
3082
- rows: frame.rows,
3083
- outcome: "ok",
3084
- authorityLease: frame.authorityLease,
3085
- });
3086
- } catch (error) {
3087
- if (
3088
- error instanceof SessionRuntimeControllerLeaseError &&
3089
- (error.code === "invalid-client-capability" || error.code === "stale-controller-lease")
3090
- ) {
3587
+ const fit = (): void => {
3588
+ try {
3589
+ if (frame.semanticWindowId === undefined)
3590
+ this.#sessionRuntimeBinding!.fitViewport(frame.authorityLease, frame.cols, frame.rows);
3591
+ else
3592
+ this.#sessionRuntimeBinding!.fitViewport(
3593
+ frame.authorityLease,
3594
+ frame.cols,
3595
+ frame.rows,
3596
+ frame.semanticWindowId,
3597
+ );
3091
3598
  this.#sendFrame(null, {
3092
3599
  type: "viewport-ack",
3093
3600
  seq: frame.seq,
3094
3601
  cols: frame.cols,
3095
3602
  rows: frame.rows,
3096
- outcome: "geometry-authority-conflict",
3603
+ outcome: "ok",
3097
3604
  authorityLease: frame.authorityLease,
3098
3605
  });
3099
- return;
3606
+ } catch (error) {
3607
+ if (
3608
+ error instanceof SessionRuntimeControllerLeaseError &&
3609
+ (error.code === "invalid-client-capability" || error.code === "stale-controller-lease")
3610
+ ) {
3611
+ this.#sendFrame(null, {
3612
+ type: "viewport-ack",
3613
+ seq: frame.seq,
3614
+ cols: frame.cols,
3615
+ rows: frame.rows,
3616
+ outcome: "geometry-authority-conflict",
3617
+ authorityLease: frame.authorityLease,
3618
+ });
3619
+ return;
3620
+ }
3621
+ if (this.#holdForWindowOwnership(error, fit)) return;
3622
+ this.#failProtocol("input-rejected");
3100
3623
  }
3101
- this.#failProtocol("input-rejected");
3102
- }
3624
+ };
3625
+ this.#afterWindowOwnership(fit);
3103
3626
  return;
3104
3627
  }
3105
3628
  this.#acceptInput(
@@ -3177,6 +3700,7 @@ export class PaneStreamLiveConnection {
3177
3700
  deliveryNonce: string;
3178
3701
  }): PaneChannel | null {
3179
3702
  const channel = this.#panes.get(address.semanticPaneId);
3703
+ if (channel?.retiredInPlace) return null;
3180
3704
  const expected = channel?.deliveryAddress;
3181
3705
  if (
3182
3706
  !channel?.delivery ||
@@ -3265,6 +3789,7 @@ export class PaneStreamLiveConnection {
3265
3789
 
3266
3790
  #acceptConsumed(pane: string, seq: number): void {
3267
3791
  const channel = this.#panes.get(pane);
3792
+ if (channel?.retiredInPlace) return;
3268
3793
  if (
3269
3794
  !this.#deliveryAcks ||
3270
3795
  !channel ||
@@ -3318,6 +3843,7 @@ export class PaneStreamLiveConnection {
3318
3843
  return;
3319
3844
  }
3320
3845
  const channel = this.#panes.get(pane);
3846
+ if (channel?.retiredInPlace) return;
3321
3847
  const semanticDelivery = this.#descriptor.terminalDelivery !== null;
3322
3848
  if (
3323
3849
  !channel ||
@@ -3405,95 +3931,227 @@ export class PaneStreamLiveConnection {
3405
3931
  this.#inputWindowFrames += 1;
3406
3932
  this.#inputWindowBytes += frameBytes;
3407
3933
  channel.nextInputSeq += 1;
3408
- try {
3409
- this.#sessionRuntimeBinding!.assertController(pane);
3410
- if (semanticDelivery)
3411
- this.#sessionRuntimeBinding!.sendInput(
3412
- pane,
3413
- { kind, data },
3414
- performanceTraceId,
3415
- causalProbe,
3416
- causalProbe
3417
- ? (result) => {
3418
- if (this.#closed) return;
3419
- if (result.status === "proved") {
3420
- this.#sendFrame(null, { type: "causal-cell-proof", proof: result.proof });
3421
- } else {
3422
- this.#sendFrame(null, {
3423
- type: "causal-cell-failure",
3424
- failure: {
3425
- version: 1,
3426
- capability: "causal-cell-v1",
3427
- traceId: result.traceId,
3428
- reason: result.reason,
3429
- ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
3430
- },
3431
- });
3934
+ const deliver = (): void => {
3935
+ // Held for an ownership read (#394) while the pane left the stream in
3936
+ // place: dropped like any other late frame for it, not delivered.
3937
+ if (channel.retiredInPlace) return;
3938
+ try {
3939
+ this.#sessionRuntimeBinding!.assertController(pane);
3940
+ if (semanticDelivery)
3941
+ this.#sessionRuntimeBinding!.sendInput(
3942
+ pane,
3943
+ { kind, data },
3944
+ performanceTraceId,
3945
+ causalProbe,
3946
+ causalProbe
3947
+ ? (result) => {
3948
+ if (this.#closed) return;
3949
+ if (result.status === "proved") {
3950
+ this.#sendFrame(null, { type: "causal-cell-proof", proof: result.proof });
3951
+ } else {
3952
+ this.#sendFrame(null, {
3953
+ type: "causal-cell-failure",
3954
+ failure: {
3955
+ version: 1,
3956
+ capability: "causal-cell-v1",
3957
+ traceId: result.traceId,
3958
+ reason: result.reason,
3959
+ ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
3960
+ },
3961
+ });
3962
+ }
3432
3963
  }
3433
- }
3434
- : undefined,
3435
- expectedLifetime,
3436
- );
3437
- else if (kind === "text") channel.sub!.sendText(data);
3438
- else if (kind === "key") channel.sub!.sendKey(data);
3439
- else throw new Error("Byte input requires semantic runtime");
3440
- let ackStartedAtMicros: number | null = null;
3441
- let ackStartedAtSharedMicros: number | null = null;
3442
- if (trace) {
3443
- try {
3444
- ackStartedAtMicros = this.#observability!.nowMicros();
3445
- } catch {
3446
- // Diagnostics cannot alter protocol truth.
3447
- }
3448
- if (this.#diagnosticSharedRawMicros) {
3964
+ : undefined,
3965
+ expectedLifetime,
3966
+ );
3967
+ else if (kind === "text") channel.sub!.sendText(data);
3968
+ else if (kind === "key") channel.sub!.sendKey(data);
3969
+ else throw new Error("Byte input requires semantic runtime");
3970
+ // Its echo goes ahead of the connection's other panes (remote links).
3971
+ channel.delivery?.prioritize?.();
3972
+ let ackStartedAtMicros: number | null = null;
3973
+ let ackStartedAtSharedMicros: number | null = null;
3974
+ if (trace) {
3449
3975
  try {
3450
- ackStartedAtSharedMicros = this.#sharedMicros();
3976
+ ackStartedAtMicros = this.#observability!.nowMicros();
3451
3977
  } catch {
3452
- // Preserve process-local ACK diagnostics.
3978
+ // Diagnostics cannot alter protocol truth.
3453
3979
  }
3454
- }
3455
- }
3456
- sendControl(this.#socket, { type: "input-ack", pane, seq });
3457
- if (trace && ackStartedAtMicros !== null) {
3458
- let ackEndedAtMicros: number | null = null;
3459
- try {
3460
- ackEndedAtMicros = this.#observability!.nowMicros();
3461
- } catch {
3462
- // Diagnostics cannot alter protocol truth.
3463
- }
3464
- let ackEndedAtSharedMicros: number | null = null;
3465
- if (ackStartedAtSharedMicros !== null) {
3466
- try {
3467
- ackEndedAtSharedMicros = this.#sharedMicros();
3468
- } catch {
3469
- // Preserve process-local ACK diagnostics.
3980
+ if (this.#diagnosticSharedRawMicros) {
3981
+ try {
3982
+ ackStartedAtSharedMicros = this.#sharedMicros();
3983
+ } catch {
3984
+ // Preserve process-local ACK diagnostics.
3985
+ }
3470
3986
  }
3471
3987
  }
3472
- if (ackEndedAtMicros !== null) {
3988
+ sendControl(this.#socket, { type: "input-ack", pane, seq });
3989
+ if (trace && ackStartedAtMicros !== null) {
3990
+ let ackEndedAtMicros: number | null = null;
3473
3991
  try {
3474
- this.#observability!.recordSpan(
3475
- "transport",
3476
- "pane-stream-input-ack-socket-send",
3477
- ackStartedAtMicros,
3478
- ackEndedAtMicros,
3479
- trace,
3480
- ackStartedAtSharedMicros === null || ackEndedAtSharedMicros === null
3481
- ? undefined
3482
- : {
3483
- startedAtMicros: ackStartedAtSharedMicros,
3484
- endedAtMicros: ackEndedAtSharedMicros,
3485
- },
3486
- );
3992
+ ackEndedAtMicros = this.#observability!.nowMicros();
3487
3993
  } catch {
3488
3994
  // Diagnostics cannot alter protocol truth.
3489
3995
  }
3996
+ let ackEndedAtSharedMicros: number | null = null;
3997
+ if (ackStartedAtSharedMicros !== null) {
3998
+ try {
3999
+ ackEndedAtSharedMicros = this.#sharedMicros();
4000
+ } catch {
4001
+ // Preserve process-local ACK diagnostics.
4002
+ }
4003
+ }
4004
+ if (ackEndedAtMicros !== null) {
4005
+ try {
4006
+ this.#observability!.recordSpan(
4007
+ "transport",
4008
+ "pane-stream-input-ack-socket-send",
4009
+ ackStartedAtMicros,
4010
+ ackEndedAtMicros,
4011
+ trace,
4012
+ ackStartedAtSharedMicros === null || ackEndedAtSharedMicros === null
4013
+ ? undefined
4014
+ : {
4015
+ startedAtMicros: ackStartedAtSharedMicros,
4016
+ endedAtMicros: ackEndedAtSharedMicros,
4017
+ },
4018
+ );
4019
+ } catch {
4020
+ // Diagnostics cannot alter protocol truth.
4021
+ }
4022
+ }
3490
4023
  }
4024
+ } catch (error) {
4025
+ if (this.#holdForWindowOwnership(error, deliver)) return;
4026
+ if (error instanceof SessionRuntimeInputLifetimeEndedError) {
4027
+ // Fenced to a lifetime that ended: not delivered, not acknowledged.
4028
+ // The pane's delivery tells the client its lifetime ended.
4029
+ this.#noteInputLifetimeEnded(pane, error);
4030
+ return;
4031
+ }
4032
+ this.#fail("control-frame-handler-failed", error);
3491
4033
  }
3492
- } catch (error) {
3493
- this.#fail("control-frame-handler-failed", error);
4034
+ };
4035
+ this.#afterWindowOwnership(deliver);
4036
+ }
4037
+
4038
+ /**
4039
+ * Input and geometry frames that arrive while registered-window ownership is
4040
+ * being read again (another session was created or killed) wait for that
4041
+ * read, in arrival order, instead of closing the stream. The mirror refuses
4042
+ * them meanwhile; before, the stream closed with 1011 and the client had to
4043
+ * reconnect. Bounded: a read that does not settle in time closes as before.
4044
+ */
4045
+ #ownershipHeld: (() => void)[] = [];
4046
+ #ownershipDraining = false;
4047
+ /** Ends the drain's wait when the stream closes. */
4048
+ #ownershipWake: (() => void) | null = null;
4049
+
4050
+ #afterWindowOwnership(run: () => void): void {
4051
+ if (this.#ownershipHeld.length === 0 && !this.#mirror.windowOwnershipPending?.()) {
4052
+ run();
4053
+ return;
4054
+ }
4055
+ this.#holdUntilWindowOwnership(run);
4056
+ }
4057
+
4058
+ /**
4059
+ * Frames whose effect depends on authority order (release, presence,
4060
+ * activity, intents) are not held for the read themselves, but must not
4061
+ * overtake frames that are.
4062
+ */
4063
+ #afterHeldFrames(run: () => void): void {
4064
+ if (this.#ownershipHeld.length === 0) {
4065
+ run();
4066
+ return;
4067
+ }
4068
+ this.#holdUntilWindowOwnership(run);
4069
+ }
4070
+
4071
+ /** A refusal while ownership is pending holds the frame; anything else is the caller's. */
4072
+ #holdForWindowOwnership(error: unknown, run: () => void): boolean {
4073
+ if (
4074
+ !(error instanceof SessionRuntimeControllerLeaseError) ||
4075
+ error.code !== "controller-conflict" ||
4076
+ !this.#mirror.windowOwnershipPending?.()
4077
+ )
4078
+ return false;
4079
+ this.#ownershipHeld.unshift(run);
4080
+ if (!this.#ownershipDraining) void this.#drainWindowOwnership();
4081
+ return true;
4082
+ }
4083
+
4084
+ #holdUntilWindowOwnership(run: () => void): void {
4085
+ if (this.#ownershipHeld.length >= PANE_STREAM_OWNERSHIP_HELD_FRAMES) {
4086
+ this.#ownershipHeld.length = 0;
4087
+ this.#fail("window-ownership-held-overflow");
4088
+ return;
4089
+ }
4090
+ this.#ownershipHeld.push(run);
4091
+ if (!this.#ownershipDraining) void this.#drainWindowOwnership();
4092
+ }
4093
+
4094
+ async #drainWindowOwnership(): Promise<void> {
4095
+ this.#ownershipDraining = true;
4096
+ try {
4097
+ await this.#drainWindowOwnershipOnce();
4098
+ } finally {
4099
+ this.#ownershipDraining = false;
4100
+ }
4101
+ }
4102
+
4103
+ async #drainWindowOwnershipOnce(): Promise<void> {
4104
+ const deadline = Date.now() + this.#ownershipWaitMs;
4105
+ while (!this.#closed && this.#ownershipHeld.length > 0) {
4106
+ if (this.#mirror.windowOwnershipPending?.()) {
4107
+ const left = deadline - Date.now();
4108
+ if (left <= 0) {
4109
+ this.#ownershipHeld.length = 0;
4110
+ this.#fail("window-ownership-unverified");
4111
+ return;
4112
+ }
4113
+ const timers: ReturnType<typeof setTimeout>[] = [];
4114
+ const wait = (ms: number) =>
4115
+ new Promise<void>((resolve) => {
4116
+ const timer = setTimeout(resolve, ms);
4117
+ timer.unref?.();
4118
+ timers.push(timer);
4119
+ });
4120
+ const read = this.#mirror.verifyWindowOwnership?.();
4121
+ await Promise.race([
4122
+ // Without a read to wait on, poll instead of spinning.
4123
+ read ? read.catch(() => wait(25)) : wait(25),
4124
+ wait(left),
4125
+ new Promise<void>((resolve) => {
4126
+ this.#ownershipWake = resolve;
4127
+ }),
4128
+ ]);
4129
+ this.#ownershipWake = null;
4130
+ for (const timer of timers) clearTimeout(timer);
4131
+ continue;
4132
+ }
4133
+ const run = this.#ownershipHeld.shift()!;
4134
+ const before = this.#ownershipHeld.length;
4135
+ run();
4136
+ // A refusal inside run() put it back at the front: wait again.
4137
+ if (this.#ownershipHeld.length > before) continue;
3494
4138
  }
3495
4139
  }
3496
4140
 
4141
+ #inputLifetimeEndedLogged = new Set<string>();
4142
+ #inputLifetimeEndedDropped = 0;
4143
+ #noteInputLifetimeEnded(pane: string, error: Error): void {
4144
+ this.#inputLifetimeEndedDropped += 1;
4145
+ if (this.#inputLifetimeEndedLogged.has(pane)) return;
4146
+ this.#inputLifetimeEndedLogged.add(pane);
4147
+ logger.info("pane-stream", "input for an ended pane lifetime not delivered", {
4148
+ session: this.#descriptor.sessionName,
4149
+ clientId: this.#clientId,
4150
+ pane,
4151
+ error: error.message.slice(0, 200),
4152
+ });
4153
+ }
4154
+
3497
4155
  #failProtocol(code: PaneStreamErrorFrameCode): void {
3498
4156
  try {
3499
4157
  sendControl(this.#socket, {
@@ -3520,6 +4178,27 @@ export class PaneStreamLiveConnection {
3520
4178
  readonly #onSocketClose = (): void => this.close(1000, "peer-closed");
3521
4179
  }
3522
4180
 
4181
+ function newPaneChannel(pane: string): PaneChannel {
4182
+ return {
4183
+ semanticPaneId: pane,
4184
+ sub: null,
4185
+ delivery: null,
4186
+ deliveryAddress: null,
4187
+ serverSeq: 0,
4188
+ sentPaneFrames: 0,
4189
+ consumedSeq: 0,
4190
+ nextInputSeq: 1,
4191
+ frozenByWire: false,
4192
+ closed: false,
4193
+ batch: null,
4194
+ graphicsAnnounced: false,
4195
+ graphicsQueue: [],
4196
+ graphicsSending: false,
4197
+ graphicsServed: new Map(),
4198
+ graphicsState: null,
4199
+ };
4200
+ }
4201
+
3523
4202
  function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
3524
4203
  if (chunks.length === 0) return new Uint8Array(0);
3525
4204
  if (chunks.length === 1) return chunks[0]!;