tmux-ide 2.9.26 → 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 (47) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +1252 -528
  3. package/package.json +2 -2
  4. package/packages/contracts/src/pane-stream.ts +9 -0
  5. package/packages/contracts/src/terminal-delivery.ts +114 -3
  6. package/packages/core/src/index.ts +1 -0
  7. package/packages/core/src/terminal-delivery-binary.ts +8 -7
  8. package/packages/core/src/terminal-delivery.ts +174 -3
  9. package/packages/core/src/terminal-partial-history.ts +152 -0
  10. package/packages/core/src/terminal-replica.ts +70 -1
  11. package/packages/daemon/dist/command-center/owner-keep-alive.js +30 -0
  12. package/packages/daemon/dist/command-center/server.js +3 -0
  13. package/packages/daemon/dist/command-center/tmux-server-attach.js +51 -0
  14. package/packages/daemon/dist/command-center/tmux-servers.js +78 -0
  15. package/packages/daemon/dist/doctor.js +4 -4
  16. package/packages/daemon/dist/lib/app-config.js +7 -0
  17. package/packages/daemon/dist/lib/node-requirement.js +20 -0
  18. package/packages/daemon/dist/lib/require-supported-node.js +8 -0
  19. package/packages/daemon/dist/lib/tmux-server-session-open.js +38 -12
  20. package/packages/daemon/dist/lib/workspace-promotion.js +4 -4
  21. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  22. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  23. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  25. package/packages/daemon/dist/server/pane-stream-upgrade.js +39 -1
  26. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +14 -0
  27. package/packages/daemon/dist/terminal/session-runtime/registry.js +1 -0
  28. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +465 -42
  29. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +76 -2
  30. package/packages/daemon/dist/tui/mirror/theme.js +8 -1
  31. package/packages/daemon/src/command-center/attach-window-rule.cases.json +84 -0
  32. package/packages/daemon/src/command-center/owner-keep-alive.ts +38 -0
  33. package/packages/daemon/src/command-center/server.ts +3 -0
  34. package/packages/daemon/src/command-center/tmux-server-attach.ts +75 -0
  35. package/packages/daemon/src/command-center/tmux-servers.ts +84 -0
  36. package/packages/daemon/src/doctor.ts +4 -4
  37. package/packages/daemon/src/lib/app-config.ts +15 -0
  38. package/packages/daemon/src/lib/node-requirement.ts +22 -0
  39. package/packages/daemon/src/lib/require-supported-node.ts +9 -0
  40. package/packages/daemon/src/lib/tmux-server-session-open.ts +53 -15
  41. package/packages/daemon/src/lib/workspace-promotion.ts +4 -4
  42. package/packages/daemon/src/server/pane-stream-upgrade.ts +41 -1
  43. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +25 -0
  44. package/packages/daemon/src/terminal/session-runtime/registry.ts +1 -0
  45. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +575 -39
  46. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +82 -2
  47. 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,6 +15,11 @@ 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;
@@ -34,6 +39,14 @@ export const TERMINAL_DELIVERY_CONNECTION_HOLD_MS = 250;
34
39
  * there only bunches panes up behind each other.
35
40
  */
36
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 };
37
50
  class DeferredProjectionEncoding extends Error {
38
51
  payload;
39
52
  constructor(payload) {
@@ -43,9 +56,13 @@ class DeferredProjectionEncoding extends Error {
43
56
  }
44
57
  class DeferredSeedEncoding extends Error {
45
58
  payload;
46
- constructor(payload) {
59
+ variant;
60
+ constructor(payload,
61
+ /** Capability 122: the history tail this seed carries, part of its encoding key. */
62
+ variant = "complete") {
47
63
  super("Deferred compact seed encoding");
48
64
  this.payload = payload;
65
+ this.variant = variant;
49
66
  }
50
67
  }
51
68
  class ExactSemanticRepresentationSelectionError extends TerminalDeliveryStateTooLargeError {
@@ -172,7 +189,16 @@ export class SessionRuntimeTerminalDeliveryHub {
172
189
  lastProjectionReceipt: null,
173
190
  lastMaterialize: null,
174
191
  reseedRequired: false,
192
+ historyUnloadedRows: 0,
193
+ historyUnloadedDigest: TERMINAL_HISTORY_EMPTY_DIGEST,
194
+ historyLoadedRows: 0,
195
+ pendingHistoryRows: null,
196
+ historyBytesPerRow: null,
197
+ revisionSinceHistoryRequest: false,
175
198
  inFlight: null,
199
+ pipelining: offer.protocolVersions.includes(TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION),
200
+ pipelined: [],
201
+ droppedTransactions: new Set(),
176
202
  latestRevision: pane.latest?.update.revision ?? null,
177
203
  encoding: null,
178
204
  scheduled: false,
@@ -201,6 +227,7 @@ export class SessionRuntimeTerminalDeliveryHub {
201
227
  projectionReceipt: (receipt) => this.#projectionReceipt(client, receipt),
202
228
  materialize: (request) => this.#materialize(client, request),
203
229
  nack: (nack) => this.#nack(client, nack),
230
+ historyRequest: (request) => this.#historyRequest(client, request),
204
231
  prioritize: () => {
205
232
  if (client.closed)
206
233
  return;
@@ -350,7 +377,7 @@ export class SessionRuntimeTerminalDeliveryHub {
350
377
  maxSlowClientMs: Math.max(this.#maxSlowClientMs, currentSlow),
351
378
  queueDepth: [...this.#clients.values()].reduce((sum, client) => sum + client.outgoing.length, 0),
352
379
  maxQueueDepth: this.#maxQueueDepth,
353
- 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),
354
381
  });
355
382
  }
356
383
  convergenceSnapshot() {
@@ -382,6 +409,7 @@ export class SessionRuntimeTerminalDeliveryHub {
382
409
  this.#cancelEncoding(client);
383
410
  client.outgoing.length = 0;
384
411
  client.inFlight = null;
412
+ client.pipelined.length = 0;
385
413
  client.budgetHeld = false;
386
414
  logDeliveryFault(client, "source-closed", "source-restarted");
387
415
  this.#enqueue(client, {
@@ -715,7 +743,7 @@ export class SessionRuntimeTerminalDeliveryHub {
715
743
  let oldest = now;
716
744
  for (const other of this.#clients.values())
717
745
  if (other !== client && other.clientId === client.clientId && other.inFlight) {
718
- bytes += other.inFlight.envelope.representationBytes;
746
+ bytes += this.#unackedBytes(other);
719
747
  oldest = Math.min(oldest, other.inFlight.sentAt);
720
748
  }
721
749
  return bytes >= TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES && now - oldest >= this.#congestedMs;
@@ -730,13 +758,108 @@ export class SessionRuntimeTerminalDeliveryHub {
730
758
  this.#schedule(other);
731
759
  }
732
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
+ }
733
856
  #schedule(client) {
734
857
  if (client.closed ||
735
858
  client.captureUnavailable ||
736
- client.inFlight ||
859
+ (client.inFlight && !this.#canPipeline(client)) ||
737
860
  client.encoding ||
738
- client.latestRevision === null ||
739
- client.latestRevision === client.baselineRevision ||
861
+ ((client.latestRevision === null || client.latestRevision === this.#sentRevision(client)) &&
862
+ client.pendingHistoryRows === null) ||
740
863
  client.visibility === "hidden" ||
741
864
  client.visibility === "frozen")
742
865
  return;
@@ -745,7 +868,9 @@ export class SessionRuntimeTerminalDeliveryHub {
745
868
  return;
746
869
  client.backgroundTimer = this.#scheduler.timer(() => {
747
870
  client.backgroundTimer = null;
748
- if (!client.closed && !client.inFlight && client.latestRevision !== null)
871
+ if (!client.closed &&
872
+ !client.inFlight &&
873
+ (client.latestRevision !== null || client.pendingHistoryRows !== null))
749
874
  this.#deliver(client);
750
875
  }, BACKGROUND_CADENCE_MS);
751
876
  return;
@@ -755,38 +880,36 @@ export class SessionRuntimeTerminalDeliveryHub {
755
880
  client.scheduled = true;
756
881
  this.#scheduler.microtask(() => {
757
882
  client.scheduled = false;
758
- if (!client.closed && client.visibility === "visible" && !client.inFlight)
883
+ if (!client.closed &&
884
+ client.visibility === "visible" &&
885
+ (!client.inFlight || this.#canPipeline(client)))
759
886
  this.#deliver(client);
760
887
  });
761
888
  }
762
889
  #deliver(client, completed) {
763
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
+ }
764
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;
765
901
  if (!pane ||
766
902
  !target ||
767
903
  client.closed ||
768
904
  client.captureUnavailable ||
769
- client.inFlight ||
905
+ (client.inFlight && (completed || !this.#canPipeline(client))) ||
770
906
  client.encoding ||
771
907
  client.visibility === "hidden" ||
772
908
  client.visibility === "frozen" ||
773
909
  (!completed && target.update.revision !== client.latestRevision))
774
910
  return;
775
- if (!completed && this.#overBudget(client)) {
776
- client.budgetHeld = true;
777
- client.budgetHeldSince ??= this.#scheduler.nowMs();
778
- client.budgetTimer ??= this.#scheduler.timer(() => {
779
- client.budgetTimer = null;
780
- if (client.closed || !client.budgetHeld)
781
- return;
782
- client.budgetHeld = false;
783
- this.#schedule(client);
784
- }, this.#holdMs);
911
+ if (!completed && this.#holdForBudget(client))
785
912
  return;
786
- }
787
- client.budgetHeldSince = null;
788
- client.budgetTimer?.cancel();
789
- client.budgetTimer = null;
790
913
  const traceStarted = completed?.traceStarted ??
791
914
  (this.#observability.enabled ? this.#observability.nowMicros() : 0);
792
915
  let deferred = false;
@@ -795,7 +918,15 @@ export class SessionRuntimeTerminalDeliveryHub {
795
918
  let deliveryEnvelope = null;
796
919
  let deliveryOrdinal = null;
797
920
  try {
798
- 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
+ }
799
930
  encodedRepresentation = representation;
800
931
  const transactionId = this.#scheduler.createId();
801
932
  const chunkCount = Math.max(1, Math.ceil(representation.bytes.byteLength / (256 * 1024)));
@@ -820,7 +951,7 @@ export class SessionRuntimeTerminalDeliveryHub {
820
951
  ? representation.projectionBaseRevision
821
952
  : representation.frame === "seed"
822
953
  ? null
823
- : Math.max(0, client.baselineRevision),
954
+ : Math.max(0, base.baselineRevision),
824
955
  canonicalRevision: target.update.revision,
825
956
  canonicalStateHash: target.update.stateHash,
826
957
  representationHash: representation.representationHash ??
@@ -829,19 +960,29 @@ export class SessionRuntimeTerminalDeliveryHub {
829
960
  chunkCount,
830
961
  canonicalEquivalent: representation.canonicalEquivalent,
831
962
  history: representation.history,
963
+ ...(representation.historyUnloaded
964
+ ? { historyUnloaded: representation.historyUnloaded }
965
+ : {}),
832
966
  richPlacements: client.negotiated.richPlacements,
833
967
  });
834
968
  deliveryEnvelope = envelope;
835
969
  deliveryOrdinal = ++this.#deliveryOrdinal;
836
970
  registerTerminalDeliveryObservationOrdinal(envelope, deliveryOrdinal);
837
- client.inFlight = {
971
+ if (client.pendingHistoryRows !== null)
972
+ client.revisionSinceHistoryRequest = true;
973
+ const flight = {
838
974
  envelope,
839
975
  projection: representation.projection ?? null,
976
+ historyRows: representation.historyRows ?? null,
840
977
  deliveryOrdinal,
841
978
  bytes: representation.bytes,
842
979
  nextChunk: 0,
843
980
  sentAt: this.#scheduler.nowMs(),
844
981
  };
982
+ if (pipelining)
983
+ client.pipelined.push(flight);
984
+ else
985
+ client.inFlight = flight;
845
986
  this.#enqueue(client, envelope);
846
987
  this.#recordDeliveryStatus(client, pane);
847
988
  if (target.trace?.traceId === pane.pendingDeliveryTrace?.traceId)
@@ -850,7 +991,7 @@ export class SessionRuntimeTerminalDeliveryHub {
850
991
  catch (error) {
851
992
  if (error instanceof DeferredSeedEncoding || error instanceof DeferredProjectionEncoding) {
852
993
  deferred = true;
853
- 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");
854
995
  return;
855
996
  }
856
997
  failedSelectionObservation = semanticSelectionObservationFromError(error);
@@ -908,7 +1049,7 @@ export class SessionRuntimeTerminalDeliveryHub {
908
1049
  }
909
1050
  }
910
1051
  }
911
- #startEncoding(client, pane, target, payload, traceStarted, projection = false) {
1052
+ #startEncoding(client, pane, target, payload, traceStarted, projection = false, variant = "complete") {
912
1053
  const key = cacheKey([
913
1054
  target.update.workspaceName,
914
1055
  client.paneId,
@@ -920,7 +1061,7 @@ export class SessionRuntimeTerminalDeliveryHub {
920
1061
  client.negotiated.richPlacements ? "rich" : "plain",
921
1062
  projection
922
1063
  ? `projection:${client.projectionBaseline?.revision ?? -1}:${client.projectionBaseline?.hash ?? "none"}`
923
- : "complete",
1064
+ : variant,
924
1065
  ]);
925
1066
  let job = this.#pendingEncodings.get(key);
926
1067
  let created = false;
@@ -946,6 +1087,7 @@ export class SessionRuntimeTerminalDeliveryHub {
946
1087
  baselineRevision: client.baselineRevision,
947
1088
  baselineHash: client.baselineHash,
948
1089
  reseedRequired: client.reseedRequired,
1090
+ historyUnloadedRows: client.historyUnloadedRows,
949
1091
  traceStarted,
950
1092
  };
951
1093
  owned.clients.add(client);
@@ -995,6 +1137,7 @@ export class SessionRuntimeTerminalDeliveryHub {
995
1137
  client.baselineRevision !== encoding.baselineRevision ||
996
1138
  client.baselineHash !== encoding.baselineHash ||
997
1139
  client.reseedRequired !== encoding.reseedRequired ||
1140
+ client.historyUnloadedRows !== encoding.historyUnloadedRows ||
998
1141
  client.inFlight ||
999
1142
  client.visibility === "hidden" ||
1000
1143
  client.visibility === "frozen" ||
@@ -1045,6 +1188,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1045
1188
  projectionBaseRevision: payload.frame === "seed" ? null : payload.baseRevision,
1046
1189
  };
1047
1190
  }
1191
+ if (client.negotiated.partialHistory === "tail-v1" && target.state.snapshot)
1192
+ return this.#partialRepresentation(client, pane, target, seedOutcome);
1048
1193
  const key = cacheKey([
1049
1194
  target.update.workspaceName,
1050
1195
  target.update.semanticPaneId,
@@ -1331,6 +1476,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1331
1476
  #ack(client, input) {
1332
1477
  const ack = TerminalDeliveryAckSchemaZ.parse(input);
1333
1478
  const flight = client.inFlight;
1479
+ if (client.droppedTransactions.has(ack.transactionId))
1480
+ return;
1334
1481
  if (!flight) {
1335
1482
  if (client.lastAck && JSON.stringify(client.lastAck) === JSON.stringify(ack))
1336
1483
  return;
@@ -1373,7 +1520,14 @@ export class SessionRuntimeTerminalDeliveryHub {
1373
1520
  client.baselineRevision = ack.canonicalRevision;
1374
1521
  client.baselineHash = ack.canonicalStateHash;
1375
1522
  client.reseedRequired = false;
1376
- 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();
1377
1531
  this.#releaseBudget(client.clientId);
1378
1532
  client.lastAck = ack;
1379
1533
  if (client.latestRevision === ack.canonicalRevision)
@@ -1421,6 +1575,264 @@ export class SessionRuntimeTerminalDeliveryHub {
1421
1575
  this.#schedule(client);
1422
1576
  this.#recordDeliveryStatus(client, this.#panes.get(client.paneId));
1423
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
+ }
1424
1836
  #projectionReceipt(client, input) {
1425
1837
  const receipt = TerminalProjectionReceiptSchemaZ.parse(input);
1426
1838
  if (client.lastProjectionReceipt &&
@@ -1500,6 +1912,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1500
1912
  nack.deliveryNonce === closed.deliveryNonce &&
1501
1913
  nack.transactionId === closed.transactionId)
1502
1914
  return;
1915
+ if (nack.transactionId !== null && client.droppedTransactions.has(nack.transactionId))
1916
+ return;
1503
1917
  const envelope = client.inFlight?.envelope;
1504
1918
  if (!envelope ||
1505
1919
  nack.workspaceName !== envelope.workspaceName ||
@@ -1514,6 +1928,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1514
1928
  this.#nacks += 1;
1515
1929
  client.reseedRequired = true;
1516
1930
  client.inFlight = null;
1931
+ this.#dropPipelined(client);
1517
1932
  this.#releaseBudget(client.clientId);
1518
1933
  this.#pruneCanonicalRevisions(client.paneId);
1519
1934
  this.#schedule(client);
@@ -1557,6 +1972,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1557
1972
  if (reason === "source-closed")
1558
1973
  client.sourceClosedFlight = client.inFlight?.envelope ?? null;
1559
1974
  client.inFlight = null;
1975
+ this.#dropPipelined(client);
1560
1976
  this.#releaseBudget(client.clientId);
1561
1977
  const fault = {
1562
1978
  type: "terminal.delivery.fault",
@@ -1591,10 +2007,15 @@ export class SessionRuntimeTerminalDeliveryHub {
1591
2007
  while (!client.closed) {
1592
2008
  const queued = client.outgoing.shift();
1593
2009
  let next = queued?.();
1594
- 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;
1595
2013
  if (!next && flight && flight.nextChunk < flight.envelope.chunkCount) {
1596
2014
  const index = flight.nextChunk;
1597
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);
1598
2019
  next = {
1599
2020
  type: "terminal.delivery.chunk",
1600
2021
  transactionId: flight.envelope.transactionId,
@@ -1776,14 +2197,15 @@ export class SessionRuntimeTerminalDeliveryHub {
1776
2197
  const encoding = client.encoding?.target.update;
1777
2198
  if (encoding?.incarnation === latest.incarnation)
1778
2199
  reachable.add(encoding.revision);
1779
- const flight = client.inFlight?.envelope;
1780
- if (flight?.incarnation === latest.incarnation)
1781
- reachable.add(flight.canonicalRevision);
1782
- }
1783
- // A hidden or slow reader owns at most one baseline and one transaction.
1784
- // Historical redraws with no reader cannot help a future delivery: new
1785
- // readers and skipped revisions already receive an atomic current seed.
1786
- // 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.
1787
2209
  for (const revision of pane.revisions.keys())
1788
2210
  if (!reachable.has(revision)) {
1789
2211
  this.#releaseNativeBacking(pane.revisions.get(revision)?.nativeBacking);
@@ -1798,7 +2220,8 @@ export class SessionRuntimeTerminalDeliveryHub {
1798
2220
  const reachable = clients.some((candidate) => cached.cacheBaseRevision === candidate.baselineRevision ||
1799
2221
  (Number.isSafeInteger(cached.cacheTargetRevision) &&
1800
2222
  cached.cacheTargetRevision > candidate.baselineRevision) ||
1801
- cached.cacheTargetRevision === candidate.inFlight?.envelope.canonicalRevision);
2223
+ cached.cacheTargetRevision === candidate.inFlight?.envelope.canonicalRevision ||
2224
+ candidate.pipelined.some((flight) => cached.cacheTargetRevision === flight.envelope.canonicalRevision));
1802
2225
  if (reachable)
1803
2226
  continue;
1804
2227
  this.#cache.delete(key);