tmux-ide 2.9.25 → 2.9.27

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 (67) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +1577 -559
  3. package/package.json +3 -2
  4. package/packages/contracts/src/pane-stream.ts +28 -0
  5. package/packages/contracts/src/terminal-delivery.ts +122 -5
  6. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  7. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  8. package/packages/core/src/index.ts +1 -0
  9. package/packages/core/src/terminal-delivery-binary.ts +8 -7
  10. package/packages/core/src/terminal-delivery.ts +174 -3
  11. package/packages/core/src/terminal-partial-history.ts +152 -0
  12. package/packages/core/src/terminal-replica.ts +70 -1
  13. package/packages/daemon/dist/command-center/owner-keep-alive.js +30 -0
  14. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  15. package/packages/daemon/dist/command-center/server.js +3 -0
  16. package/packages/daemon/dist/command-center/tmux-server-attach.js +51 -0
  17. package/packages/daemon/dist/command-center/tmux-servers.js +95 -7
  18. package/packages/daemon/dist/doctor.js +4 -4
  19. package/packages/daemon/dist/lib/app-config.js +7 -0
  20. package/packages/daemon/dist/lib/node-requirement.js +20 -0
  21. package/packages/daemon/dist/lib/require-supported-node.js +8 -0
  22. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  23. package/packages/daemon/dist/lib/tmux-server-session-open.js +38 -12
  24. package/packages/daemon/dist/lib/workspace-promotion.js +4 -4
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  27. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  29. package/packages/daemon/dist/server/pane-stream-upgrade.js +39 -1
  30. package/packages/daemon/dist/terminal/mirror/session-channel.js +6 -1
  31. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  32. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +112 -22
  33. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  34. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  35. package/packages/daemon/dist/terminal/session-runtime/registry.js +2 -0
  36. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +571 -33
  37. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +2 -0
  38. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  39. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +76 -2
  40. package/packages/daemon/dist/tui/mirror/theme.js +8 -1
  41. package/packages/daemon/src/command-center/attach-window-rule.cases.json +84 -0
  42. package/packages/daemon/src/command-center/owner-keep-alive.ts +38 -0
  43. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  44. package/packages/daemon/src/command-center/server.ts +3 -0
  45. package/packages/daemon/src/command-center/tmux-server-attach.ts +75 -0
  46. package/packages/daemon/src/command-center/tmux-servers.ts +103 -6
  47. package/packages/daemon/src/doctor.ts +4 -4
  48. package/packages/daemon/src/lib/app-config.ts +15 -0
  49. package/packages/daemon/src/lib/node-requirement.ts +22 -0
  50. package/packages/daemon/src/lib/require-supported-node.ts +9 -0
  51. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  52. package/packages/daemon/src/lib/tmux-server-session-open.ts +53 -15
  53. package/packages/daemon/src/lib/workspace-promotion.ts +4 -4
  54. package/packages/daemon/src/server/pane-stream-upgrade.ts +41 -1
  55. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  56. package/packages/daemon/src/terminal/mirror/session-channel.ts +8 -1
  57. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  58. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +136 -20
  59. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  60. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  61. package/packages/daemon/src/terminal/session-runtime/registry.ts +2 -0
  62. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +696 -30
  63. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  64. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +2 -0
  65. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
  66. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +82 -2
  67. package/packages/daemon/src/tui/mirror/theme.ts +13 -1
@@ -4,8 +4,8 @@ import { encodeTerminalProjectionCooperatively } from "@tmux-ide/core";
4
4
  import { StockCaptureTabUnavailableError } from "./stock-capture-fidelity.js";
5
5
  import { logger } from "../../lib/log.js";
6
6
  import { MAX_RETAINED_NATIVE_BACKING_BYTES, takeNativeSeedBacking, } from "./native-seed-backing.js";
7
- import { WorkspaceIdSchemaZ, TERMINAL_GRAPHICS_CAPABILITY_VERSION, TERMINAL_DELIVERY_PATCH_TO_SEED_BYTES, TERMINAL_DELIVERY_MAX_REPRESENTATION_BYTES, TerminalDeliveryEnvelopeSchemaZ, TerminalDeliveryAckSchemaZ, TerminalDeliveryNackSchemaZ, TerminalDeliveryOfferSchemaZ, TerminalDeliveryVisibilitySchemaZ, } from "@tmux-ide/contracts";
8
- import { TerminalDeliveryStateTooLargeError, terminalReplicaRowsEqual, TERMINAL_COMPACT_COOPERATIVE_SEED_CELLS, applyTerminalReplicaUpdate, applyTerminalReplicaUpdateCooperatively, terminalReplicaUpdateNeedsCooperativeReduction, encodeBinarySemanticTerminalUpdate, encodeBinarySemanticTerminalUpdateCooperatively, encodeCompactSemanticTerminalUpdate, encodeCompactSemanticTerminalUpdateCooperatively, terminalSemanticUpdateNeedsCooperativeEncoding, encodeAnsiTerminalRepresentation, encodeSemanticTerminalUpdate, hashTerminalDeliveryRepresentation, negotiateTerminalDelivery, preaccountSemanticTerminalUpdateBytes, } from "@tmux-ide/core";
7
+ import { WorkspaceIdSchemaZ, TERMINAL_GRAPHICS_CAPABILITY_VERSION, TERMINAL_DELIVERY_PATCH_TO_SEED_BYTES, TERMINAL_DELIVERY_MAX_REPRESENTATION_BYTES, TerminalDeliveryEnvelopeSchemaZ, TerminalDeliveryAckSchemaZ, TerminalDeliveryNackSchemaZ, TerminalDeliveryOfferSchemaZ, TerminalDeliveryVisibilitySchemaZ, TerminalDeliveryHistoryRequestSchemaZ, TERMINAL_DELIVERY_HISTORY_TAIL_ROWS, TERMINAL_DELIVERY_MAX_PIPELINED, TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION, TERMINAL_HISTORY_EMPTY_DIGEST, } from "@tmux-ide/contracts";
8
+ import { TerminalDeliveryStateTooLargeError, terminalReplicaRowsEqual, TERMINAL_COMPACT_COOPERATIVE_SEED_CELLS, applyTerminalReplicaUpdate, applyTerminalReplicaUpdateCooperatively, terminalReplicaUpdateNeedsCooperativeReduction, encodeBinarySemanticTerminalUpdate, encodeBinarySemanticTerminalUpdateCooperatively, encodeCompactSemanticTerminalUpdate, encodeCompactSemanticTerminalUpdateCooperatively, terminalSemanticUpdateNeedsCooperativeEncoding, encodeAnsiTerminalRepresentation, encodeSemanticTerminalUpdate, hashTerminalDeliveryRepresentation, negotiateTerminalDelivery, preaccountSemanticTerminalUpdateBytes, encodeSemanticTerminalHistory, terminalHistoryPrefixCommitment, dropTerminalHistoryCommitmentPrefix, popTerminalHistoryCommitmentSuffix, } from "@tmux-ide/core";
9
9
  import { SYSTEM_SESSION_RUNTIME_SCHEDULER, } from "./runtime-scheduler.js";
10
10
  import { DISABLED_SESSION_RUNTIME_OBSERVABILITY, } from "./runtime-observability.js";
11
11
  import { registerTerminalDeliveryObservationOrdinal } from "./terminal-delivery-observation-identity.js";
@@ -15,10 +15,38 @@ export const MAX_RAW_JOURNAL_BYTES = 4 * 1024 * 1024;
15
15
  export const MAX_REPRESENTATION_CACHE_ENTRIES = 8;
16
16
  export const MAX_REPRESENTATION_CACHE_BYTES = 16 * 1024 * 1024;
17
17
  export const MAX_CLIENTS = 64;
18
+ /**
19
+ * Capability 122: one history frame's encoded bytes, well under the
20
+ * connection's unacknowledged budget, so history never holds live output.
21
+ */
22
+ export const HISTORY_FRAME_MAX_BYTES = 128 * 1024;
18
23
  const MAX_PANES = 32;
19
24
  const MAX_PENDING_CANONICAL_CELLS = 1_000_000;
20
25
  const MAX_CONNECTIONS = MAX_CLIENTS * MAX_PANES;
21
26
  const BACKGROUND_CADENCE_MS = 100;
27
+ /**
28
+ * One connection's unacknowledged delivery bytes, across its panes, before a
29
+ * pane other than the one it types into waits. A remote link (SSH) queues
30
+ * every sent byte ahead of the next input-ack and echo; this bounds that queue
31
+ * to about this much plus one delivery. Daemon policy only: nothing on the wire.
32
+ */
33
+ export const TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES = 256 * 1024;
34
+ /** No pane is held longer than this: it is then sent behind whatever is in flight. */
35
+ export const TERMINAL_DELIVERY_CONNECTION_HOLD_MS = 250;
36
+ /**
37
+ * A pane is held only once some delivery of its connection has gone this long
38
+ * unacknowledged: a fast link acks bulk within a few round trips, and holding
39
+ * there only bunches panes up behind each other.
40
+ */
41
+ export const TERMINAL_DELIVERY_CONNECTION_CONGESTED_MS = 30;
42
+ /**
43
+ * Capability 124 (TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION): over a
44
+ * long link an echo commits while the previous echo's delivery is still
45
+ * unacknowledged, and waiting for that ACK costs up to one more round trip
46
+ * per key. A visible pane of a client that offers 124 sends up to this many
47
+ * patches before the first is acknowledged. Daemon policy over that capability.
48
+ */
49
+ export { TERMINAL_DELIVERY_MAX_PIPELINED };
22
50
  class DeferredProjectionEncoding extends Error {
23
51
  payload;
24
52
  constructor(payload) {
@@ -28,9 +56,13 @@ class DeferredProjectionEncoding extends Error {
28
56
  }
29
57
  class DeferredSeedEncoding extends Error {
30
58
  payload;
31
- constructor(payload) {
59
+ variant;
60
+ constructor(payload,
61
+ /** Capability 122: the history tail this seed carries, part of its encoding key. */
62
+ variant = "complete") {
32
63
  super("Deferred compact seed encoding");
33
64
  this.payload = payload;
65
+ this.variant = variant;
34
66
  }
35
67
  }
36
68
  class ExactSemanticRepresentationSelectionError extends TerminalDeliveryStateTooLargeError {
@@ -76,6 +108,8 @@ export class SessionRuntimeTerminalDeliveryHub {
76
108
  #observability;
77
109
  #panes = new Map();
78
110
  #clients = new Map();
111
+ /** Per connection: the pane it last typed into. */
112
+ #priority = new Map();
79
113
  #sourceCloseFailures = 0;
80
114
  #pendingSourceCloses = 0;
81
115
  /** Synchronous reservations held while an async pane source is starting. */
@@ -93,10 +127,14 @@ export class SessionRuntimeTerminalDeliveryHub {
93
127
  #deliveryLifecycleOrdinal = 0;
94
128
  #deliveryStatusOrdinal = 0;
95
129
  #closed = false;
130
+ #holdMs;
131
+ #congestedMs;
96
132
  constructor(generation, workspaceName, ownerForPane, options = {}) {
97
133
  this.generation = generation;
98
134
  this.workspaceName = workspaceName;
99
135
  this.#ownerForPane = ownerForPane;
136
+ this.#holdMs = options.connectionHoldMs ?? TERMINAL_DELIVERY_CONNECTION_HOLD_MS;
137
+ this.#congestedMs = options.connectionCongestedMs ?? TERMINAL_DELIVERY_CONNECTION_CONGESTED_MS;
100
138
  this.#scheduler = options.scheduler ?? SYSTEM_SESSION_RUNTIME_SCHEDULER;
101
139
  this.#observability = options.observability ?? DISABLED_SESSION_RUNTIME_OBSERVABILITY;
102
140
  }
@@ -151,7 +189,16 @@ export class SessionRuntimeTerminalDeliveryHub {
151
189
  lastProjectionReceipt: null,
152
190
  lastMaterialize: null,
153
191
  reseedRequired: false,
192
+ historyUnloadedRows: 0,
193
+ historyUnloadedDigest: TERMINAL_HISTORY_EMPTY_DIGEST,
194
+ historyLoadedRows: 0,
195
+ pendingHistoryRows: null,
196
+ historyBytesPerRow: null,
197
+ revisionSinceHistoryRequest: false,
154
198
  inFlight: null,
199
+ pipelining: offer.protocolVersions.includes(TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION),
200
+ pipelined: [],
201
+ droppedTransactions: new Set(),
155
202
  latestRevision: pane.latest?.update.revision ?? null,
156
203
  encoding: null,
157
204
  scheduled: false,
@@ -165,6 +212,9 @@ export class SessionRuntimeTerminalDeliveryHub {
165
212
  lastAck: null,
166
213
  sourceClosedFlight: null,
167
214
  backgroundTimer: null,
215
+ budgetHeld: false,
216
+ budgetHeldSince: null,
217
+ budgetTimer: null,
168
218
  };
169
219
  this.#clients.set(key, client);
170
220
  client.lifecycleOpenRecorded = this.#recordDeliveryLifecycle(client, pane, "open");
@@ -177,6 +227,13 @@ export class SessionRuntimeTerminalDeliveryHub {
177
227
  projectionReceipt: (receipt) => this.#projectionReceipt(client, receipt),
178
228
  materialize: (request) => this.#materialize(client, request),
179
229
  nack: (nack) => this.#nack(client, nack),
230
+ historyRequest: (request) => this.#historyRequest(client, request),
231
+ prioritize: () => {
232
+ if (client.closed)
233
+ return;
234
+ this.#priority.set(client.clientId, client.paneId);
235
+ this.#releaseBudget(client.clientId);
236
+ },
180
237
  setVisibility: (visibilityInput) => {
181
238
  if (client.closed)
182
239
  return;
@@ -320,7 +377,7 @@ export class SessionRuntimeTerminalDeliveryHub {
320
377
  maxSlowClientMs: Math.max(this.#maxSlowClientMs, currentSlow),
321
378
  queueDepth: [...this.#clients.values()].reduce((sum, client) => sum + client.outgoing.length, 0),
322
379
  maxQueueDepth: this.#maxQueueDepth,
323
- inFlightBytes: [...this.#clients.values()].reduce((sum, client) => sum + (client.inFlight?.envelope.representationBytes ?? 0), 0),
380
+ inFlightBytes: [...this.#clients.values()].reduce((sum, client) => sum + this.#unackedBytes(client), 0),
324
381
  });
325
382
  }
326
383
  convergenceSnapshot() {
@@ -352,6 +409,8 @@ export class SessionRuntimeTerminalDeliveryHub {
352
409
  this.#cancelEncoding(client);
353
410
  client.outgoing.length = 0;
354
411
  client.inFlight = null;
412
+ client.pipelined.length = 0;
413
+ client.budgetHeld = false;
355
414
  logDeliveryFault(client, "source-closed", "source-restarted");
356
415
  this.#enqueue(client, {
357
416
  type: "terminal.delivery.fault",
@@ -673,13 +732,134 @@ export class SessionRuntimeTerminalDeliveryHub {
673
732
  pane.rawFloorRevision = Math.max(pane.rawFloorRevision, first[0] + 1);
674
733
  }
675
734
  }
735
+ #overBudget(client) {
736
+ if (this.#priority.get(client.clientId) === client.paneId)
737
+ return false;
738
+ if (client.budgetHeldSince !== null &&
739
+ this.#scheduler.nowMs() - client.budgetHeldSince >= this.#holdMs)
740
+ return false;
741
+ const now = this.#scheduler.nowMs();
742
+ let bytes = 0;
743
+ let oldest = now;
744
+ for (const other of this.#clients.values())
745
+ if (other !== client && other.clientId === client.clientId && other.inFlight) {
746
+ bytes += this.#unackedBytes(other);
747
+ oldest = Math.min(oldest, other.inFlight.sentAt);
748
+ }
749
+ return bytes >= TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES && now - oldest >= this.#congestedMs;
750
+ }
751
+ /** A pane's delivery settled or left: held panes of its connection try again, typed-into pane first. */
752
+ #releaseBudget(clientId) {
753
+ const held = [...this.#clients.values()].filter((other) => other.clientId === clientId && other.budgetHeld);
754
+ const priority = this.#priority.get(clientId);
755
+ held.sort((a, b) => Number(b.paneId === priority) - Number(a.paneId === priority));
756
+ for (const other of held) {
757
+ other.budgetHeld = false;
758
+ this.#schedule(other);
759
+ }
760
+ }
761
+ /** Bytes the client has not acknowledged: every flight, pipelined ones included. */
762
+ #unackedBytes(client) {
763
+ let bytes = client.inFlight?.envelope.representationBytes ?? 0;
764
+ for (const flight of client.pipelined)
765
+ bytes += flight.envelope.representationBytes;
766
+ return bytes;
767
+ }
768
+ /** The revision the client holds once every flight applies (its ACKed baseline if none). */
769
+ #sentRevision(client) {
770
+ const newest = client.pipelined.at(-1) ?? client.inFlight;
771
+ return newest?.envelope.type === "terminal.delivery" && newest.envelope.frame !== "history"
772
+ ? newest.envelope.canonicalRevision
773
+ : client.baselineRevision;
774
+ }
775
+ /**
776
+ * Whether another delivery may go out behind the unacknowledged ones. Only
777
+ * for a client that offers 124, only a visible pane, only behind canonical patches whose chunks have all been
778
+ * handed to the socket (a client takes one envelope's chunks at a time), and
779
+ * within TERMINAL_DELIVERY_MAX_PIPELINED and the connection's unacknowledged
780
+ * byte budget. Seeds, projections, history frames and history requests keep
781
+ * one delivery in flight.
782
+ */
783
+ #canPipeline(client) {
784
+ if (!client.pipelining ||
785
+ !client.inFlight ||
786
+ client.pipelined.length + 1 >= TERMINAL_DELIVERY_MAX_PIPELINED ||
787
+ client.visibility !== "visible" ||
788
+ client.reseedRequired ||
789
+ client.materializeRequested ||
790
+ client.pendingHistoryRows !== null ||
791
+ client.encoding ||
792
+ (client.negotiated.encoding !== "semantic-v1" &&
793
+ client.negotiated.encoding !== "semantic-compact-v1" &&
794
+ client.negotiated.encoding !== "semantic-binary-v1"))
795
+ return false;
796
+ for (const flight of [client.inFlight, ...client.pipelined])
797
+ if (flight.envelope.type !== "terminal.delivery" ||
798
+ flight.projection ||
799
+ flight.envelope.frame !== "patch" ||
800
+ !flight.envelope.canonicalEquivalent ||
801
+ flight.nextChunk < flight.envelope.chunkCount)
802
+ return false;
803
+ return this.#unackedBytes(client) < TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES;
804
+ }
805
+ /**
806
+ * The client as it will be once every flight applies: what its ACKs would
807
+ * set (see #ack). Representations for a pipelined patch are based on it.
808
+ */
809
+ #pipelineBase(client) {
810
+ const newest = client.pipelined.at(-1) ?? client.inFlight;
811
+ const rows = newest.historyRows;
812
+ return {
813
+ ...client,
814
+ baselineRevision: newest.envelope.canonicalRevision,
815
+ baselineHash: newest.envelope.canonicalStateHash,
816
+ projectionBaseline: null,
817
+ lastProjectionReceipt: null,
818
+ reseedRequired: false,
819
+ ...(rows
820
+ ? {
821
+ historyUnloadedRows: rows.unloaded,
822
+ historyUnloadedDigest: rows.digest,
823
+ historyLoadedRows: rows.loaded,
824
+ }
825
+ : {}),
826
+ };
827
+ }
828
+ /** A patch on `base`'s projected state, or null when only a seed (or an encoding job) would do. */
829
+ #pipelinedRepresentation(base, pane, target) {
830
+ if (target.update.type !== "terminal.patch" ||
831
+ target.update.revision <= base.baselineRevision ||
832
+ pane.revisions.get(base.baselineRevision)?.update.incarnation !== target.update.incarnation)
833
+ return null;
834
+ const reseeds = this.#reseeds;
835
+ try {
836
+ const representation = this.#representation(base, pane, target);
837
+ if (representation.frame === "patch" &&
838
+ representation.canonicalEquivalent &&
839
+ !representation.projection)
840
+ return representation;
841
+ }
842
+ catch (error) {
843
+ if (!(error instanceof DeferredSeedEncoding || error instanceof DeferredProjectionEncoding))
844
+ throw error;
845
+ }
846
+ // A seed waits for the ACKs and is then chosen again; it is counted then.
847
+ this.#reseeds = reseeds;
848
+ return null;
849
+ }
850
+ /** Flights behind a NACKed or faulted one: the client gets a reseed; their feedback is inert. */
851
+ #dropPipelined(client) {
852
+ for (const flight of client.pipelined)
853
+ client.droppedTransactions.add(flight.envelope.transactionId);
854
+ client.pipelined.length = 0;
855
+ }
676
856
  #schedule(client) {
677
857
  if (client.closed ||
678
858
  client.captureUnavailable ||
679
- client.inFlight ||
859
+ (client.inFlight && !this.#canPipeline(client)) ||
680
860
  client.encoding ||
681
- client.latestRevision === null ||
682
- client.latestRevision === client.baselineRevision ||
861
+ ((client.latestRevision === null || client.latestRevision === this.#sentRevision(client)) &&
862
+ client.pendingHistoryRows === null) ||
683
863
  client.visibility === "hidden" ||
684
864
  client.visibility === "frozen")
685
865
  return;
@@ -688,7 +868,9 @@ export class SessionRuntimeTerminalDeliveryHub {
688
868
  return;
689
869
  client.backgroundTimer = this.#scheduler.timer(() => {
690
870
  client.backgroundTimer = null;
691
- if (!client.closed && !client.inFlight && client.latestRevision !== null)
871
+ if (!client.closed &&
872
+ !client.inFlight &&
873
+ (client.latestRevision !== null || client.pendingHistoryRows !== null))
692
874
  this.#deliver(client);
693
875
  }, BACKGROUND_CADENCE_MS);
694
876
  return;
@@ -698,23 +880,36 @@ export class SessionRuntimeTerminalDeliveryHub {
698
880
  client.scheduled = true;
699
881
  this.#scheduler.microtask(() => {
700
882
  client.scheduled = false;
701
- if (!client.closed && client.visibility === "visible" && !client.inFlight)
883
+ if (!client.closed &&
884
+ client.visibility === "visible" &&
885
+ (!client.inFlight || this.#canPipeline(client)))
702
886
  this.#deliver(client);
703
887
  });
704
888
  }
705
889
  #deliver(client, completed) {
706
890
  const pane = this.#panes.get(client.paneId);
891
+ if (!completed && pane && this.#historyDue(client)) {
892
+ // History counts against the connection's byte budget like any delivery.
893
+ if (this.#holdForBudget(client))
894
+ return;
895
+ this.#deliverHistory(client, pane);
896
+ return;
897
+ }
707
898
  const target = completed?.target ?? pane?.latest;
899
+ // Behind an unacknowledged delivery only a patch on the client's projected state goes out.
900
+ const pipelining = !completed && client.inFlight !== null;
708
901
  if (!pane ||
709
902
  !target ||
710
903
  client.closed ||
711
904
  client.captureUnavailable ||
712
- client.inFlight ||
905
+ (client.inFlight && (completed || !this.#canPipeline(client))) ||
713
906
  client.encoding ||
714
907
  client.visibility === "hidden" ||
715
908
  client.visibility === "frozen" ||
716
909
  (!completed && target.update.revision !== client.latestRevision))
717
910
  return;
911
+ if (!completed && this.#holdForBudget(client))
912
+ return;
718
913
  const traceStarted = completed?.traceStarted ??
719
914
  (this.#observability.enabled ? this.#observability.nowMicros() : 0);
720
915
  let deferred = false;
@@ -723,7 +918,15 @@ export class SessionRuntimeTerminalDeliveryHub {
723
918
  let deliveryEnvelope = null;
724
919
  let deliveryOrdinal = null;
725
920
  try {
726
- const representation = this.#representation(client, pane, target, completed?.outcome);
921
+ const base = pipelining ? this.#pipelineBase(client) : client;
922
+ const representation = pipelining
923
+ ? this.#pipelinedRepresentation(base, pane, target)
924
+ : this.#representation(client, pane, target, completed?.outcome);
925
+ if (!representation) {
926
+ // Not a patch: it waits for the outstanding ACKs, then goes out as usual.
927
+ deferred = true;
928
+ return;
929
+ }
727
930
  encodedRepresentation = representation;
728
931
  const transactionId = this.#scheduler.createId();
729
932
  const chunkCount = Math.max(1, Math.ceil(representation.bytes.byteLength / (256 * 1024)));
@@ -748,7 +951,7 @@ export class SessionRuntimeTerminalDeliveryHub {
748
951
  ? representation.projectionBaseRevision
749
952
  : representation.frame === "seed"
750
953
  ? null
751
- : Math.max(0, client.baselineRevision),
954
+ : Math.max(0, base.baselineRevision),
752
955
  canonicalRevision: target.update.revision,
753
956
  canonicalStateHash: target.update.stateHash,
754
957
  representationHash: representation.representationHash ??
@@ -757,19 +960,29 @@ export class SessionRuntimeTerminalDeliveryHub {
757
960
  chunkCount,
758
961
  canonicalEquivalent: representation.canonicalEquivalent,
759
962
  history: representation.history,
963
+ ...(representation.historyUnloaded
964
+ ? { historyUnloaded: representation.historyUnloaded }
965
+ : {}),
760
966
  richPlacements: client.negotiated.richPlacements,
761
967
  });
762
968
  deliveryEnvelope = envelope;
763
969
  deliveryOrdinal = ++this.#deliveryOrdinal;
764
970
  registerTerminalDeliveryObservationOrdinal(envelope, deliveryOrdinal);
765
- client.inFlight = {
971
+ if (client.pendingHistoryRows !== null)
972
+ client.revisionSinceHistoryRequest = true;
973
+ const flight = {
766
974
  envelope,
767
975
  projection: representation.projection ?? null,
976
+ historyRows: representation.historyRows ?? null,
768
977
  deliveryOrdinal,
769
978
  bytes: representation.bytes,
770
979
  nextChunk: 0,
771
980
  sentAt: this.#scheduler.nowMs(),
772
981
  };
982
+ if (pipelining)
983
+ client.pipelined.push(flight);
984
+ else
985
+ client.inFlight = flight;
773
986
  this.#enqueue(client, envelope);
774
987
  this.#recordDeliveryStatus(client, pane);
775
988
  if (target.trace?.traceId === pane.pendingDeliveryTrace?.traceId)
@@ -778,7 +991,7 @@ export class SessionRuntimeTerminalDeliveryHub {
778
991
  catch (error) {
779
992
  if (error instanceof DeferredSeedEncoding || error instanceof DeferredProjectionEncoding) {
780
993
  deferred = true;
781
- this.#startEncoding(client, pane, target, error.payload, traceStarted, error instanceof DeferredProjectionEncoding);
994
+ this.#startEncoding(client, pane, target, error.payload, traceStarted, error instanceof DeferredProjectionEncoding, error instanceof DeferredSeedEncoding ? error.variant : "complete");
782
995
  return;
783
996
  }
784
997
  failedSelectionObservation = semanticSelectionObservationFromError(error);
@@ -836,7 +1049,7 @@ export class SessionRuntimeTerminalDeliveryHub {
836
1049
  }
837
1050
  }
838
1051
  }
839
- #startEncoding(client, pane, target, payload, traceStarted, projection = false) {
1052
+ #startEncoding(client, pane, target, payload, traceStarted, projection = false, variant = "complete") {
840
1053
  const key = cacheKey([
841
1054
  target.update.workspaceName,
842
1055
  client.paneId,
@@ -848,7 +1061,7 @@ export class SessionRuntimeTerminalDeliveryHub {
848
1061
  client.negotiated.richPlacements ? "rich" : "plain",
849
1062
  projection
850
1063
  ? `projection:${client.projectionBaseline?.revision ?? -1}:${client.projectionBaseline?.hash ?? "none"}`
851
- : "complete",
1064
+ : variant,
852
1065
  ]);
853
1066
  let job = this.#pendingEncodings.get(key);
854
1067
  let created = false;
@@ -874,6 +1087,7 @@ export class SessionRuntimeTerminalDeliveryHub {
874
1087
  baselineRevision: client.baselineRevision,
875
1088
  baselineHash: client.baselineHash,
876
1089
  reseedRequired: client.reseedRequired,
1090
+ historyUnloadedRows: client.historyUnloadedRows,
877
1091
  traceStarted,
878
1092
  };
879
1093
  owned.clients.add(client);
@@ -923,6 +1137,7 @@ export class SessionRuntimeTerminalDeliveryHub {
923
1137
  client.baselineRevision !== encoding.baselineRevision ||
924
1138
  client.baselineHash !== encoding.baselineHash ||
925
1139
  client.reseedRequired !== encoding.reseedRequired ||
1140
+ client.historyUnloadedRows !== encoding.historyUnloadedRows ||
926
1141
  client.inFlight ||
927
1142
  client.visibility === "hidden" ||
928
1143
  client.visibility === "frozen" ||
@@ -973,6 +1188,8 @@ export class SessionRuntimeTerminalDeliveryHub {
973
1188
  projectionBaseRevision: payload.frame === "seed" ? null : payload.baseRevision,
974
1189
  };
975
1190
  }
1191
+ if (client.negotiated.partialHistory === "tail-v1" && target.state.snapshot)
1192
+ return this.#partialRepresentation(client, pane, target, seedOutcome);
976
1193
  const key = cacheKey([
977
1194
  target.update.workspaceName,
978
1195
  target.update.semanticPaneId,
@@ -1259,6 +1476,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1259
1476
  #ack(client, input) {
1260
1477
  const ack = TerminalDeliveryAckSchemaZ.parse(input);
1261
1478
  const flight = client.inFlight;
1479
+ if (client.droppedTransactions.has(ack.transactionId))
1480
+ return;
1262
1481
  if (!flight) {
1263
1482
  if (client.lastAck && JSON.stringify(client.lastAck) === JSON.stringify(ack))
1264
1483
  return;
@@ -1301,7 +1520,15 @@ export class SessionRuntimeTerminalDeliveryHub {
1301
1520
  client.baselineRevision = ack.canonicalRevision;
1302
1521
  client.baselineHash = ack.canonicalStateHash;
1303
1522
  client.reseedRequired = false;
1304
- client.inFlight = null;
1523
+ if (flight.historyRows) {
1524
+ client.historyUnloadedRows = flight.historyRows.unloaded;
1525
+ client.historyUnloadedDigest = flight.historyRows.digest;
1526
+ client.historyLoadedRows = flight.historyRows.loaded;
1527
+ this.#pushHistoryTail(client);
1528
+ }
1529
+ client.inFlight = client.pipelined.shift() ?? null;
1530
+ client.droppedTransactions.clear();
1531
+ this.#releaseBudget(client.clientId);
1305
1532
  client.lastAck = ack;
1306
1533
  if (client.latestRevision === ack.canonicalRevision)
1307
1534
  client.latestRevision = null;
@@ -1348,6 +1575,264 @@ export class SessionRuntimeTerminalDeliveryHub {
1348
1575
  this.#schedule(client);
1349
1576
  this.#recordDeliveryStatus(client, this.#panes.get(client.paneId));
1350
1577
  }
1578
+ /**
1579
+ * Capability 122: the client's partial view of `target`. Its unloaded rows
1580
+ * follow the baseline's (a trim takes unloaded rows first); a seed carries
1581
+ * the newest TERMINAL_DELIVERY_HISTORY_TAIL_ROWS rows (none on the alternate
1582
+ * screen) or, after a reseed, as many rows as the client held. The full
1583
+ * canonical hash still verifies: the commitment covers the rest.
1584
+ */
1585
+ #partialRepresentation(client, pane, target, seedOutcome) {
1586
+ const full = target.state.snapshot;
1587
+ const baselineRecord = client.reseedRequired || client.baselineRevision < 0
1588
+ ? undefined
1589
+ : pane.revisions.get(client.baselineRevision);
1590
+ const baselineFull = baselineRecord?.state.snapshot ?? null;
1591
+ const tail = full.modes.alternateScreen ? 0 : TERMINAL_DELIVERY_HISTORY_TAIL_ROWS;
1592
+ const loadedDepth = () => Math.max(0, full.history.length -
1593
+ Math.max(tail, client.baselineRevision >= 0 ? client.historyLoadedRows : 0));
1594
+ let unloadedRows;
1595
+ let unloaded = null;
1596
+ let baseline = null;
1597
+ if (baselineFull && baselineRecord.update.incarnation === target.update.incarnation) {
1598
+ baseline =
1599
+ client.historyUnloadedRows === 0
1600
+ ? baselineFull
1601
+ : { ...baselineFull, history: baselineFull.history.slice(client.historyUnloadedRows) };
1602
+ // A trim takes unloaded rows first. The rows still unloaded must be the
1603
+ // same row objects, so their commitment updates in O(trim).
1604
+ const trim = historyTrim(baselineFull.history, full.history);
1605
+ const kept = Math.max(0, client.historyUnloadedRows - trim);
1606
+ let same = kept <= full.history.length;
1607
+ for (let index = 0; same && index < kept; index++)
1608
+ if (baselineFull.history[trim + index] !== full.history[index])
1609
+ same = false;
1610
+ if (same) {
1611
+ unloadedRows = kept;
1612
+ const before = { rows: client.historyUnloadedRows, digest: client.historyUnloadedDigest };
1613
+ unloaded =
1614
+ trim === 0
1615
+ ? before
1616
+ : dropTerminalHistoryCommitmentPrefix(before, baselineFull.history.slice(0, Math.min(trim, client.historyUnloadedRows)));
1617
+ }
1618
+ else {
1619
+ // Not a proved trim (a reflow, a clear): a seed that keeps the depth
1620
+ // the client held. A patch could not grow the unloaded rows.
1621
+ unloadedRows = loadedDepth();
1622
+ baseline = null;
1623
+ }
1624
+ }
1625
+ else {
1626
+ unloadedRows = loadedDepth();
1627
+ }
1628
+ const partial = unloadedRows === 0 ? full : { ...full, history: full.history.slice(unloadedRows) };
1629
+ // A client that holds everything and stays complete keeps the canonical
1630
+ // patch; otherwise diff the partial views (never the full-history patch).
1631
+ const view = unloadedRows === 0 && client.historyUnloadedRows === 0
1632
+ ? target
1633
+ : {
1634
+ ...target,
1635
+ state: { ...target.state, snapshot: partial },
1636
+ update: { ...target.update, type: "terminal.seed" },
1637
+ };
1638
+ const payload = baseline
1639
+ ? semanticPayload(client.baselineRevision, baseline, view, baselineRecord.update.incarnation)
1640
+ : semanticSeed(view);
1641
+ const encode = (value) => {
1642
+ if (value.frame === "seed" &&
1643
+ (client.negotiated.encoding === "semantic-binary-v1" ||
1644
+ terminalSemanticUpdateNeedsCooperativeEncoding(value))) {
1645
+ if (!seedOutcome)
1646
+ throw new DeferredSeedEncoding(value, `partial:${unloadedRows}`);
1647
+ if ("error" in seedOutcome)
1648
+ throw seedOutcome.error;
1649
+ return seedOutcome.bytes;
1650
+ }
1651
+ return client.negotiated.encoding === "semantic-binary-v1"
1652
+ ? encodeBinarySemanticTerminalUpdate(value)
1653
+ : encodeCompactSemanticTerminalUpdate(value);
1654
+ };
1655
+ let frame = payload.frame;
1656
+ let bytes;
1657
+ try {
1658
+ bytes = encode(payload);
1659
+ }
1660
+ catch (error) {
1661
+ if (!(error instanceof TerminalDeliveryStateTooLargeError) || payload.frame !== "patch")
1662
+ throw error;
1663
+ frame = "seed";
1664
+ bytes = encode(semanticSeed(view));
1665
+ }
1666
+ if (frame === "seed")
1667
+ this.#reseeds += client.reseedRequired ? 1 : 0;
1668
+ const commitment = unloaded ?? terminalHistoryPrefixCommitment(full.history, unloadedRows);
1669
+ return {
1670
+ bytes,
1671
+ encoding: client.negotiated.encoding,
1672
+ frame,
1673
+ canonicalEquivalent: true,
1674
+ history: "partial",
1675
+ historyUnloaded: commitment,
1676
+ historyRows: {
1677
+ unloaded: unloadedRows,
1678
+ digest: commitment.digest,
1679
+ loaded: full.history.length - unloadedRows,
1680
+ },
1681
+ };
1682
+ }
1683
+ /** Hold the client while its connection's other panes are congested; true if held. */
1684
+ #holdForBudget(client) {
1685
+ if (this.#overBudget(client)) {
1686
+ client.budgetHeld = true;
1687
+ client.budgetHeldSince ??= this.#scheduler.nowMs();
1688
+ client.budgetTimer ??= this.#scheduler.timer(() => {
1689
+ client.budgetTimer = null;
1690
+ if (client.closed || !client.budgetHeld)
1691
+ return;
1692
+ client.budgetHeld = false;
1693
+ this.#schedule(client);
1694
+ }, this.#holdMs);
1695
+ return true;
1696
+ }
1697
+ client.budgetHeldSince = null;
1698
+ client.budgetTimer?.cancel();
1699
+ client.budgetTimer = null;
1700
+ return false;
1701
+ }
1702
+ /** Capability 122: a history frame goes next if asked for and no newer output waits (or one just went). */
1703
+ #historyDue(client) {
1704
+ return (client.pendingHistoryRows !== null &&
1705
+ !client.inFlight &&
1706
+ !client.encoding &&
1707
+ client.baselineRevision >= 0 &&
1708
+ !client.reseedRequired &&
1709
+ (client.latestRevision === null ||
1710
+ client.latestRevision === client.baselineRevision ||
1711
+ client.revisionSinceHistoryRequest) &&
1712
+ // Live output of another pane held by the connection's budget goes first.
1713
+ ![...this.#clients.values()].some((other) => other !== client && other.clientId === client.clientId && other.budgetHeld));
1714
+ }
1715
+ #deliverHistory(client, pane) {
1716
+ const asked = client.pendingHistoryRows;
1717
+ client.pendingHistoryRows = null;
1718
+ client.revisionSinceHistoryRequest = false;
1719
+ const record = pane.revisions.get(client.baselineRevision);
1720
+ const full = record?.state.snapshot;
1721
+ if (!record || !full || client.historyUnloadedRows === 0) {
1722
+ this.#schedule(client);
1723
+ return;
1724
+ }
1725
+ const encoding = client.negotiated.encoding;
1726
+ const unloadedRows = client.historyUnloadedRows;
1727
+ try {
1728
+ // Bound the frame by its encoded bytes. The event loop pays for every
1729
+ // row encoded, so encode about what is sent: size the frame from the
1730
+ // last frame's bytes per row (or a small sample of the rows next in
1731
+ // line), grow once if it came out well under, shrink until it fits.
1732
+ const limit = Math.max(1, Math.min(asked, unloadedRows));
1733
+ const encode = (count) => {
1734
+ const rows = full.history.slice(unloadedRows - count, unloadedRows);
1735
+ const bytes = encodeSemanticTerminalHistory({ frame: "history", revision: record.update.revision, rows }, encoding);
1736
+ return { count, rows, bytes };
1737
+ };
1738
+ const fit = (bytesPerRow) => Math.max(1, Math.min(limit, Math.floor((HISTORY_FRAME_MAX_BYTES * 0.95) / Math.max(1, bytesPerRow))));
1739
+ let frame = client.historyBytesPerRow === null ? encode(Math.min(limit, 32)) : null;
1740
+ const estimate = client.historyBytesPerRow ?? frame.bytes.byteLength / frame.count;
1741
+ if (!frame || fit(estimate) !== frame.count)
1742
+ frame = encode(fit(estimate));
1743
+ if (frame.count < limit && frame.bytes.byteLength < HISTORY_FRAME_MAX_BYTES * 0.6) {
1744
+ const grown = fit(frame.bytes.byteLength / frame.count);
1745
+ if (grown > frame.count)
1746
+ frame = encode(grown);
1747
+ }
1748
+ let { count, rows, bytes } = frame;
1749
+ while (bytes.byteLength > HISTORY_FRAME_MAX_BYTES && count > 1) {
1750
+ count = Math.max(1, Math.min(count - 1, Math.floor((count * HISTORY_FRAME_MAX_BYTES * 0.9) / bytes.byteLength)));
1751
+ ({ rows, bytes } = encode(count));
1752
+ }
1753
+ client.historyBytesPerRow = bytes.byteLength / count;
1754
+ const chunk = {
1755
+ rows,
1756
+ unloaded: popTerminalHistoryCommitmentSuffix({ rows: unloadedRows, digest: client.historyUnloadedDigest }, rows),
1757
+ };
1758
+ const envelope = TerminalDeliveryEnvelopeSchemaZ.parse({
1759
+ type: "terminal.delivery",
1760
+ workspaceName: client.deliveryWorkspaceName,
1761
+ semanticPaneId: record.update.semanticPaneId,
1762
+ generation: record.update.generation,
1763
+ incarnation: record.update.incarnation,
1764
+ deliveryNonce: client.negotiated.deliveryNonce,
1765
+ transactionId: this.#scheduler.createId(),
1766
+ protocolVersion: 1,
1767
+ encoding,
1768
+ frame: "history",
1769
+ baseRevision: record.update.revision,
1770
+ canonicalRevision: record.update.revision,
1771
+ canonicalStateHash: record.update.stateHash,
1772
+ representationHash: hashTerminalDeliveryRepresentation(bytes),
1773
+ representationBytes: bytes.byteLength,
1774
+ chunkCount: Math.max(1, Math.ceil(bytes.byteLength / (256 * 1024))),
1775
+ canonicalEquivalent: true,
1776
+ history: "partial",
1777
+ historyUnloaded: chunk.unloaded,
1778
+ richPlacements: client.negotiated.richPlacements,
1779
+ });
1780
+ const deliveryOrdinal = ++this.#deliveryOrdinal;
1781
+ registerTerminalDeliveryObservationOrdinal(envelope, deliveryOrdinal);
1782
+ client.inFlight = {
1783
+ envelope,
1784
+ projection: null,
1785
+ historyRows: {
1786
+ unloaded: chunk.unloaded.rows,
1787
+ digest: chunk.unloaded.digest,
1788
+ loaded: full.history.length - chunk.unloaded.rows,
1789
+ },
1790
+ deliveryOrdinal,
1791
+ bytes,
1792
+ nextChunk: 0,
1793
+ sentAt: this.#scheduler.nowMs(),
1794
+ };
1795
+ this.#enqueue(client, envelope);
1796
+ this.#recordDeliveryStatus(client, pane);
1797
+ }
1798
+ catch (error) {
1799
+ this.#fault(client, error instanceof TerminalDeliveryStateTooLargeError
1800
+ ? "state-too-large"
1801
+ : "protocol-violation", error instanceof Error ? error.message : String(error));
1802
+ }
1803
+ }
1804
+ /** Back on the normal screen with less than the tail loaded: send the tail unasked. */
1805
+ #pushHistoryTail(client) {
1806
+ if (client.pendingHistoryRows !== null || client.historyUnloadedRows === 0)
1807
+ return;
1808
+ const full = this.#panes.get(client.paneId)?.revisions.get(client.baselineRevision)
1809
+ ?.state.snapshot;
1810
+ if (!full || full.modes.alternateScreen)
1811
+ return;
1812
+ if (client.historyLoadedRows >= TERMINAL_DELIVERY_HISTORY_TAIL_ROWS)
1813
+ return;
1814
+ client.pendingHistoryRows = Math.min(client.historyUnloadedRows, TERMINAL_DELIVERY_HISTORY_TAIL_ROWS - client.historyLoadedRows);
1815
+ client.revisionSinceHistoryRequest = false;
1816
+ }
1817
+ #historyRequest(client, input) {
1818
+ if (client.closed)
1819
+ return;
1820
+ const parsed = TerminalDeliveryHistoryRequestSchemaZ.safeParse(input);
1821
+ if (!parsed.success ||
1822
+ client.negotiated.partialHistory !== "tail-v1" ||
1823
+ parsed.data.workspaceName !== client.deliveryWorkspaceName ||
1824
+ parsed.data.semanticPaneId !== client.paneId ||
1825
+ parsed.data.generation !== client.negotiated.generation ||
1826
+ parsed.data.deliveryNonce !== client.negotiated.deliveryNonce) {
1827
+ this.#fault(client, "protocol-violation", "History request does not identify this delivery");
1828
+ return;
1829
+ }
1830
+ // The daemon knows what the client holds at its baseline; the newest
1831
+ // request replaces an unserved one and is served from that baseline.
1832
+ client.pendingHistoryRows = parsed.data.maxRows;
1833
+ client.revisionSinceHistoryRequest = false;
1834
+ this.#schedule(client);
1835
+ }
1351
1836
  #projectionReceipt(client, input) {
1352
1837
  const receipt = TerminalProjectionReceiptSchemaZ.parse(input);
1353
1838
  if (client.lastProjectionReceipt &&
@@ -1376,6 +1861,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1376
1861
  client.lastProjectionReceipt = receipt;
1377
1862
  client.reseedRequired = false;
1378
1863
  client.inFlight = null;
1864
+ this.#releaseBudget(client.clientId);
1379
1865
  if (client.latestRevision === receipt.canonicalRevision)
1380
1866
  client.latestRevision = null;
1381
1867
  if (client.materializeRequested)
@@ -1426,6 +1912,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1426
1912
  nack.deliveryNonce === closed.deliveryNonce &&
1427
1913
  nack.transactionId === closed.transactionId)
1428
1914
  return;
1915
+ if (nack.transactionId !== null && client.droppedTransactions.has(nack.transactionId))
1916
+ return;
1429
1917
  const envelope = client.inFlight?.envelope;
1430
1918
  if (!envelope ||
1431
1919
  nack.workspaceName !== envelope.workspaceName ||
@@ -1440,6 +1928,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1440
1928
  this.#nacks += 1;
1441
1929
  client.reseedRequired = true;
1442
1930
  client.inFlight = null;
1931
+ this.#dropPipelined(client);
1932
+ this.#releaseBudget(client.clientId);
1443
1933
  this.#pruneCanonicalRevisions(client.paneId);
1444
1934
  this.#schedule(client);
1445
1935
  this.#recordDeliveryStatus(client, this.#panes.get(client.paneId));
@@ -1482,6 +1972,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1482
1972
  if (reason === "source-closed")
1483
1973
  client.sourceClosedFlight = client.inFlight?.envelope ?? null;
1484
1974
  client.inFlight = null;
1975
+ this.#dropPipelined(client);
1976
+ this.#releaseBudget(client.clientId);
1485
1977
  const fault = {
1486
1978
  type: "terminal.delivery.fault",
1487
1979
  reason,
@@ -1515,10 +2007,15 @@ export class SessionRuntimeTerminalDeliveryHub {
1515
2007
  while (!client.closed) {
1516
2008
  const queued = client.outgoing.shift();
1517
2009
  let next = queued?.();
1518
- const flight = client.inFlight;
2010
+ // Only the newest flight can still have chunks: a pipelined
2011
+ // delivery is created only once every earlier one is fully out.
2012
+ const flight = client.pipelined.at(-1) ?? client.inFlight;
1519
2013
  if (!next && flight && flight.nextChunk < flight.envelope.chunkCount) {
1520
2014
  const index = flight.nextChunk;
1521
2015
  flight.nextChunk += 1;
2016
+ // A newer revision may be waiting for this flight's last chunk.
2017
+ if (flight.nextChunk === flight.envelope.chunkCount && client.latestRevision !== null)
2018
+ this.#schedule(client);
1522
2019
  next = {
1523
2020
  type: "terminal.delivery.chunk",
1524
2021
  transactionId: flight.envelope.transactionId,
@@ -1557,8 +2054,14 @@ export class SessionRuntimeTerminalDeliveryHub {
1557
2054
  if (client.lifecycleOpenRecorded)
1558
2055
  this.#recordDeliveryLifecycle(client, this.#panes.get(client.paneId), "close");
1559
2056
  client.backgroundTimer?.cancel();
2057
+ client.budgetTimer?.cancel();
2058
+ client.budgetTimer = null;
1560
2059
  client.outgoing.length = 0;
1561
2060
  this.#clients.delete(client.key);
2061
+ if (![...this.#clients.values()].some((other) => other.clientId === client.clientId))
2062
+ this.#priority.delete(client.clientId);
2063
+ else
2064
+ this.#releaseBudget(client.clientId);
1562
2065
  this.#pruneCanonicalRevisions(client.paneId);
1563
2066
  if ([...this.#clients.values()].some((candidate) => candidate.paneId === client.paneId))
1564
2067
  return;
@@ -1694,14 +2197,15 @@ export class SessionRuntimeTerminalDeliveryHub {
1694
2197
  const encoding = client.encoding?.target.update;
1695
2198
  if (encoding?.incarnation === latest.incarnation)
1696
2199
  reachable.add(encoding.revision);
1697
- const flight = client.inFlight?.envelope;
1698
- if (flight?.incarnation === latest.incarnation)
1699
- reachable.add(flight.canonicalRevision);
1700
- }
1701
- // A hidden or slow reader owns at most one baseline and one transaction.
1702
- // Historical redraws with no reader cannot help a future delivery: new
1703
- // readers and skipped revisions already receive an atomic current seed.
1704
- // MAX_CLIENTS bounds this set to 2 * MAX_CLIENTS + 1 per pane.
2200
+ for (const flight of [client.inFlight, ...client.pipelined])
2201
+ if (flight?.envelope.incarnation === latest.incarnation)
2202
+ reachable.add(flight.envelope.canonicalRevision);
2203
+ }
2204
+ // A hidden or slow reader owns at most one baseline and its transactions
2205
+ // (one, or TERMINAL_DELIVERY_MAX_PIPELINED for a visible pane). Historical
2206
+ // redraws with no reader cannot help a future delivery: new readers and
2207
+ // skipped revisions already receive an atomic current seed. MAX_CLIENTS
2208
+ // bounds this set to (TERMINAL_DELIVERY_MAX_PIPELINED + 1) * MAX_CLIENTS + 1 per pane.
1705
2209
  for (const revision of pane.revisions.keys())
1706
2210
  if (!reachable.has(revision)) {
1707
2211
  this.#releaseNativeBacking(pane.revisions.get(revision)?.nativeBacking);
@@ -1716,7 +2220,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1716
2220
  const reachable = clients.some((candidate) => cached.cacheBaseRevision === candidate.baselineRevision ||
1717
2221
  (Number.isSafeInteger(cached.cacheTargetRevision) &&
1718
2222
  cached.cacheTargetRevision > candidate.baselineRevision) ||
1719
- cached.cacheTargetRevision === candidate.inFlight?.envelope.canonicalRevision);
2223
+ cached.cacheTargetRevision === candidate.inFlight?.envelope.canonicalRevision ||
2224
+ candidate.pipelined.some((flight) => cached.cacheTargetRevision === flight.envelope.canonicalRevision));
1720
2225
  if (reachable)
1721
2226
  continue;
1722
2227
  this.#cache.delete(key);
@@ -1937,11 +2442,12 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1937
2442
  // append-only history is proved here; trim/reflow and changed dimensions
1938
2443
  // retain the full seed boundary. Equality includes wrapped and all cells.
1939
2444
  const snapshot = target.state.snapshot;
2445
+ const trim = baseline ? historyTrim(baseline.history, snapshot.history) : 0;
1940
2446
  if (baseline &&
1941
2447
  baselineIncarnation === update.incarnation &&
1942
2448
  baseline.cols === snapshot.cols &&
1943
2449
  baseline.rows === snapshot.rows &&
1944
- baseline.history.length <= snapshot.history.length) {
2450
+ baseline.history.length - trim <= snapshot.history.length) {
1945
2451
  // Identity reuse is cheap, but detached equal histories must not turn a
1946
2452
  // cooperative seed into an unbounded synchronous cell comparison.
1947
2453
  let comparisonCells = 0;
@@ -1953,8 +2459,8 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1953
2459
  ? terminalReplicaRowsEqual(left, right)
1954
2460
  : null;
1955
2461
  };
1956
- for (let index = 0; index < baseline.history.length; index++)
1957
- if (equal(baseline.history[index], snapshot.history[index]) !== true)
2462
+ for (let index = trim; index < baseline.history.length; index++)
2463
+ if (equal(baseline.history[index], snapshot.history[index - trim]) !== true)
1958
2464
  return semanticSeed(target);
1959
2465
  const rows = [];
1960
2466
  for (let index = 0; index < snapshot.grid.length; index++) {
@@ -1964,19 +2470,20 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1964
2470
  if (!same)
1965
2471
  rows.push({ index, row: snapshot.grid[index] });
1966
2472
  }
1967
- const appendedRows = snapshot.history.length - baseline.history.length;
2473
+ const retained = baseline.history.length - trim;
2474
+ const appendedRows = snapshot.history.length - retained;
1968
2475
  // Compact patches serialize synchronously. Do not move a large appended
1969
2476
  // suffix or repaint across the seed-only cooperative encoding boundary.
1970
2477
  if ((rows.length + appendedRows) * snapshot.cols >= TERMINAL_COMPACT_COOPERATIVE_SEED_CELLS)
1971
2478
  return semanticSeed(target);
1972
- const append = snapshot.history.slice(baseline.history.length);
2479
+ const append = snapshot.history.slice(retained);
1973
2480
  return {
1974
2481
  frame: "patch",
1975
2482
  baseRevision: baselineRevision,
1976
2483
  revision: update.revision,
1977
2484
  patch: {
1978
2485
  rows,
1979
- ...(append.length ? { historyDelta: { trim: 0, append } } : {}),
2486
+ ...(append.length || trim ? { historyDelta: { trim, append } } : {}),
1980
2487
  cursor: snapshot.cursor,
1981
2488
  modes: snapshot.modes,
1982
2489
  placements: snapshot.placements,
@@ -1986,6 +2493,37 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1986
2493
  }
1987
2494
  return semanticSeed(target);
1988
2495
  }
2496
+ /**
2497
+ * How many of the baseline's oldest history rows the target dropped, proved by
2498
+ * row identity only: the replica keeps each surviving row object when tmux
2499
+ * trims at its history-limit. Zero when nothing was trimmed or no shift is
2500
+ * proved; the caller still checks every retained row exactly.
2501
+ */
2502
+ function historyTrim(baseline, target) {
2503
+ const first = target[0];
2504
+ if (first === undefined || baseline[0] === first)
2505
+ return 0;
2506
+ // A shared row object (a blank row) can recur; prove at most a few shifts.
2507
+ let candidates = 0;
2508
+ for (let trim = 1; trim < baseline.length; trim++) {
2509
+ if (baseline[trim] !== first)
2510
+ continue;
2511
+ if (++candidates > 4)
2512
+ return 0;
2513
+ const retained = baseline.length - trim;
2514
+ if (retained > target.length)
2515
+ continue;
2516
+ let same = true;
2517
+ for (let index = 0; index < retained; index++)
2518
+ if (baseline[trim + index] !== target[index]) {
2519
+ same = false;
2520
+ break;
2521
+ }
2522
+ if (same)
2523
+ return trim;
2524
+ }
2525
+ return 0;
2526
+ }
1989
2527
  /** Account represented cells without traversing/serializing the snapshot. */
1990
2528
  function canonicalUpdateCellCost(update) {
1991
2529
  if (update.type === "terminal.tombstone")