tmux-ide 2.9.25 → 2.9.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/bin/cli.js +344 -50
  2. package/package.json +2 -1
  3. package/packages/contracts/src/pane-stream.ts +19 -0
  4. package/packages/contracts/src/terminal-delivery.ts +8 -2
  5. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  6. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  7. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  8. package/packages/daemon/dist/command-center/tmux-servers.js +17 -7
  9. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  10. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  11. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  12. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  13. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  14. package/packages/daemon/dist/terminal/mirror/session-channel.js +6 -1
  15. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  16. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +98 -22
  17. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  18. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  19. package/packages/daemon/dist/terminal/session-runtime/registry.js +1 -0
  20. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +121 -6
  21. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +2 -0
  22. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  23. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  24. package/packages/daemon/src/command-center/tmux-servers.ts +19 -6
  25. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  26. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  27. package/packages/daemon/src/terminal/mirror/session-channel.ts +8 -1
  28. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  29. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +111 -20
  30. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  31. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  32. package/packages/daemon/src/terminal/session-runtime/registry.ts +1 -0
  33. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +136 -6
  34. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  35. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +2 -0
  36. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
@@ -65,6 +65,8 @@ export interface PaneStreamLeaseDescriptor {
65
65
  readonly sessionName: string;
66
66
  readonly runtimeSessionId: string | null;
67
67
  readonly panes: readonly string[];
68
+ /** #806: the one window this stream was issued for, or null for a pane set of the session. */
69
+ readonly semanticWindowId: string | null;
68
70
  readonly viewerMode: PaneStreamViewerMode;
69
71
  readonly terminalDelivery: TerminalDeliveryOffer | null;
70
72
  readonly status: PaneStreamLeaseStatus;
@@ -365,6 +367,7 @@ export class PaneStreamLeaseManager {
365
367
  sessionName: state.sessionName,
366
368
  runtimeSessionId: state.runtimeSessionId,
367
369
  panes: [...state.request.panes],
370
+ semanticWindowId: state.request.semanticWindowId ?? null,
368
371
  viewerMode: state.request.viewerMode,
369
372
  terminalDelivery: state.request.terminalDelivery ?? null,
370
373
  status: state.status,
@@ -24,6 +24,7 @@ import {
24
24
  PANE_STREAM_INPUT_BYTES_CAPABILITY_VERSION,
25
25
  PANE_STREAM_BROWSER_ICON_CAPABILITY_VERSION,
26
26
  PANE_STREAM_READER_CAPABILITY_VERSION,
27
+ PANE_STREAM_BROWSER_KIND_CAPABILITY_VERSION,
27
28
  PANE_STREAM_READER_TOPOLOGY_BUNDLE_CAPABILITY_VERSION,
28
29
  PANE_STREAM_TOPOLOGY_IN_PLACE_CAPABILITY_VERSION,
29
30
  type PaneStreamInputLifetime,
@@ -423,6 +424,8 @@ export interface SessionRuntimeTerminalDeliveryConnection {
423
424
  materialize?(request: TerminalProjectionMaterialize): void;
424
425
  nack(nack: TerminalDeliveryNack): void;
425
426
  setVisibility(visibility: TerminalDeliveryVisibility): void;
427
+ /** The client typed into this pane: send its deliveries first. */
428
+ prioritize?(): void;
426
429
  close(): Promise<void>;
427
430
  readonly graphics?: TerminalDeliveryGraphics;
428
431
  }
@@ -636,6 +639,23 @@ export class PaneStreamAdmissionCoordinator {
636
639
  );
637
640
  }
638
641
  }
642
+ // #806: a stream for one window is issued for exactly that window's
643
+ // panes, as the trusted inventory places them now.
644
+ if (request.semanticWindowId !== undefined) {
645
+ const windowPanes = new Set(
646
+ described.panes
647
+ .filter((pane) => pane.semanticWindowId === request.semanticWindowId)
648
+ .map((pane) => pane.semanticPaneId),
649
+ );
650
+ if (
651
+ windowPanes.size !== request.panes.length ||
652
+ request.panes.some((pane) => !windowPanes.has(pane))
653
+ )
654
+ throw new PaneStreamAdmissionError(
655
+ "pane-not-found",
656
+ "The panes are not exactly the panes of that window of the workspace session.",
657
+ );
658
+ }
639
659
 
640
660
  const issued = await this.#leaseManager.issue(request, {
641
661
  requestId,
@@ -1680,7 +1700,11 @@ export class PaneStreamLiveConnection {
1680
1700
  * stream with 1011, and nothing was tried twice. A refusal of authority is a
1681
1701
  * decision, not a failure, and is never repeated. Each repeat is logged.
1682
1702
  */
1683
- async #retryOpenStep<T>(step: string, run: () => Promise<T>): Promise<T> {
1703
+ async #retryOpenStep<T>(
1704
+ step: string,
1705
+ run: () => Promise<T>,
1706
+ final: (error: unknown) => boolean = () => false,
1707
+ ): Promise<T> {
1684
1708
  for (let attempt = 0; ; attempt += 1) {
1685
1709
  try {
1686
1710
  return await run();
@@ -1689,7 +1713,8 @@ export class PaneStreamLiveConnection {
1689
1713
  if (
1690
1714
  delayMs === undefined ||
1691
1715
  this.#closed ||
1692
- error instanceof SessionRuntimeControllerLeaseError
1716
+ error instanceof SessionRuntimeControllerLeaseError ||
1717
+ final(error)
1693
1718
  )
1694
1719
  throw error;
1695
1720
  logger.info("pane-stream", "stream open step failed; trying again", {
@@ -1725,24 +1750,38 @@ export class PaneStreamLiveConnection {
1725
1750
  let stagedAuthority: MirrorLayoutAuthoritySnapshot | null = null;
1726
1751
  let authorityMalformed = false;
1727
1752
  let layoutActivated = false;
1753
+ let layoutAttempt = 0;
1728
1754
  // Establish the single session layout observer first. MirrorService owns
1729
1755
  // this lifecycle and may share native control state with delivery setup;
1730
1756
  // only the independent pane delivery opens below are parallelized.
1731
1757
  try {
1732
- if (!this.#mirror.subscribeLayout) throw new Error("authoritative layout is unavailable");
1733
- const subscription = await this.#mirror.subscribeLayout(
1734
- this.#descriptor.sessionName,
1735
- () => undefined,
1736
- {
1737
- expectedSemanticPaneIds: expectedPaneIds,
1738
- expectedRuntimeSessionId: this.#descriptor.runtimeSessionId!,
1739
- onAuthority: (snapshot) => {
1740
- this.#recordDiagnosticLifecycle("pane-stream-layout-staged");
1741
- if (snapshot.layouts.length > PANE_STREAM_MAX_PANES) authorityMalformed = true;
1742
- else if (!layoutActivated) stagedAuthority = snapshot;
1743
- else this.#onLayoutAuthority(snapshot);
1744
- },
1758
+ const subscribeLayout = this.#mirror.subscribeLayout?.bind(this.#mirror);
1759
+ if (!subscribeLayout) throw new Error("authoritative layout is unavailable");
1760
+ // The session's trusted inventory can be unsettled for a moment after a
1761
+ // pane change ("lacks verified identity"): a stream re-issued at once
1762
+ // closed 1011 while the next, 100 ms later, opened. Try again, as the
1763
+ // other opening steps do (#585). A changed pane set is a decision, not
1764
+ // a failure, and still closes 1012 at once. A try that failed is
1765
+ // disowned: its authority callback is ignored.
1766
+ const subscription = await this.#retryOpenStep(
1767
+ "semantic-layout-subscribe",
1768
+ () => {
1769
+ const attempt = ++layoutAttempt;
1770
+ stagedAuthority = null;
1771
+ authorityMalformed = false;
1772
+ return subscribeLayout(this.#descriptor.sessionName, () => undefined, {
1773
+ expectedSemanticPaneIds: expectedPaneIds,
1774
+ expectedRuntimeSessionId: this.#descriptor.runtimeSessionId!,
1775
+ onAuthority: (snapshot) => {
1776
+ if (attempt !== layoutAttempt) return;
1777
+ this.#recordDiagnosticLifecycle("pane-stream-layout-staged");
1778
+ if (snapshot.layouts.length > PANE_STREAM_MAX_PANES) authorityMalformed = true;
1779
+ else if (!layoutActivated) stagedAuthority = snapshot;
1780
+ else this.#onLayoutAuthority(snapshot);
1781
+ },
1782
+ });
1745
1783
  },
1784
+ (error) => error instanceof Error && error.name === "MirrorTopologyChangedError",
1746
1785
  );
1747
1786
  if (this.#closed) {
1748
1787
  await subscription.close().catch(() => undefined);
@@ -2603,7 +2642,10 @@ export class PaneStreamLiveConnection {
2603
2642
  return;
2604
2643
  }
2605
2644
  const frames = this.#validateInitialLayout(snapshot.layouts, this.#semanticExpectedPaneIds);
2606
- if (!frames && this.#topologyInPlace) {
2645
+ // #806: a pane can also move between windows while the session keeps its
2646
+ // panes; for a stream of one window that changes its pane set.
2647
+ const windowChanged = frames !== null && this.#windowPaneSetChanged(snapshot);
2648
+ if ((!frames || windowChanged) && this.#topologyInPlace) {
2607
2649
  // The layout does not fit the pane set this stream knows. With
2608
2650
  // capability 119 that is a change to follow, not a reason to close.
2609
2651
  void this.#reconcileTopology(snapshot);
@@ -2611,6 +2653,7 @@ export class PaneStreamLiveConnection {
2611
2653
  }
2612
2654
  if (
2613
2655
  !frames ||
2656
+ windowChanged ||
2614
2657
  !PaneStreamLayoutSnapshotFrameSchemaZ.safeParse({
2615
2658
  type: "layout-snapshot",
2616
2659
  topologyEpoch: snapshot.topologyEpoch,
@@ -2638,6 +2681,20 @@ export class PaneStreamLiveConnection {
2638
2681
  });
2639
2682
  }
2640
2683
 
2684
+ /** #806: the layout no longer shows this stream's window with exactly its panes. */
2685
+ #windowPaneSetChanged(snapshot: MirrorLayoutAuthoritySnapshot): boolean {
2686
+ const window = this.#descriptor.semanticWindowId;
2687
+ if (window === null) return false;
2688
+ const live = [...this.#panes.values()]
2689
+ .filter((channel) => !channel.closed)
2690
+ .map((channel) => channel.semanticPaneId);
2691
+ const shown = snapshot.layouts.find((event) => event.semanticWindowId === window);
2692
+ if (!shown) return true;
2693
+ const panes = shown.panes.map((pane) => pane.semanticPaneId ?? "");
2694
+ if (shown.zoomed) return panes.length !== 1 || !live.includes(panes[0]!);
2695
+ return panes.length !== live.length || panes.some((pane) => !live.includes(pane));
2696
+ }
2697
+
2641
2698
  /** The same session and runtime, a newer epoch, a layout a stream can carry. */
2642
2699
  #layoutAuthorityAdmissible(snapshot: MirrorLayoutAuthoritySnapshot): boolean {
2643
2700
  return (
@@ -2763,12 +2820,41 @@ export class PaneStreamLiveConnection {
2763
2820
  }).success
2764
2821
  )
2765
2822
  return this.#topologyFailed("layout snapshot invalid");
2823
+ // #806: a stream issued for one window follows that window's panes, as the
2824
+ // trusted inventory places them, and the same layout must show that window
2825
+ // with exactly those panes (a zoomed window shows one of them).
2826
+ const window = this.#descriptor.semanticWindowId;
2827
+ let windowPanes: string[] | null = null;
2828
+ if (window !== null) {
2829
+ windowPanes = [
2830
+ ...new Set(
2831
+ described.panes
2832
+ .filter((pane) => pane.semanticWindowId === window)
2833
+ .map((pane) => pane.semanticPaneId),
2834
+ ),
2835
+ ].sort();
2836
+ if (windowPanes.length === 0) return this.#topologyFailed("the stream's window is gone");
2837
+ const shown = snapshot.layouts.find((event) => event.semanticWindowId === window);
2838
+ const shownPanes = (shown?.panes ?? []).map((pane) => pane.semanticPaneId ?? "");
2839
+ if (
2840
+ !shown ||
2841
+ (shown.zoomed
2842
+ ? shownPanes.length !== 1 || !windowPanes.includes(shownPanes[0]!)
2843
+ : shownPanes.length !== windowPanes.length ||
2844
+ shownPanes.some((pane) => !windowPanes!.includes(pane)))
2845
+ )
2846
+ return "stale";
2847
+ }
2848
+ const followed = windowPanes ?? next;
2766
2849
  const live = [...this.#panes.values()].filter((channel) => !channel.closed);
2767
- const removed = live.filter((channel) => !next.includes(channel.semanticPaneId));
2768
- // A stream issued for the whole session follows it; one issued for some
2769
- // panes keeps exactly those.
2850
+ const removed = live.filter((channel) => !followed.includes(channel.semanticPaneId));
2851
+ // A stream issued for the whole session follows it, and one issued for a
2852
+ // window follows that window; one issued for some panes keeps exactly those.
2770
2853
  const liveIds = new Set(live.map((channel) => channel.semanticPaneId));
2771
- const added = this.#leasesWholeSession ? next.filter((pane) => !liveIds.has(pane)) : [];
2854
+ const added =
2855
+ windowPanes !== null || this.#leasesWholeSession
2856
+ ? followed.filter((pane) => !liveIds.has(pane))
2857
+ : [];
2772
2858
  if (added.length > 0 && !inventoryIsThisSession)
2773
2859
  return this.#topologyFailed("inventory cannot prove the runtime session");
2774
2860
  const remaining = live.length - removed.length + added.length;
@@ -2943,6 +3029,9 @@ export class PaneStreamLiveConnection {
2943
3029
  ...(this.#offers(PANE_STREAM_READER_CAPABILITY_VERSION)
2944
3030
  ? { reader: pane.reader ? { name: pane.reader.name } : null }
2945
3031
  : {}),
3032
+ ...(this.#offers(PANE_STREAM_BROWSER_KIND_CAPABILITY_VERSION)
3033
+ ? { browserKind: pane.browserKind ?? null }
3034
+ : {}),
2946
3035
  left: pane.left,
2947
3036
  top: pane.top,
2948
3037
  width: pane.width,
@@ -3878,6 +3967,8 @@ export class PaneStreamLiveConnection {
3878
3967
  else if (kind === "text") channel.sub!.sendText(data);
3879
3968
  else if (kind === "key") channel.sub!.sendKey(data);
3880
3969
  else throw new Error("Byte input requires semantic runtime");
3970
+ // Its echo goes ahead of the connection's other panes (remote links).
3971
+ channel.delivery?.prioritize?.();
3881
3972
  let ackStartedAtMicros: number | null = null;
3882
3973
  let ackStartedAtSharedMicros: number | null = null;
3883
3974
  if (trace) {
@@ -4,7 +4,7 @@ export function browserIcon(value: string, alive = processAlive): string | null
4
4
  if (!match || !alive(Number(match[1]))) return null;
5
5
  return match[2]!;
6
6
  }
7
- function processAlive(pid: number): boolean {
7
+ export function processAlive(pid: number): boolean {
8
8
  try {
9
9
  process.kill(pid, 0);
10
10
  return true;
@@ -1,8 +1,10 @@
1
- import { browserIcon } from "./browser-icon.ts";
1
+ import { browserIcon, processAlive } from "./browser-icon.ts";
2
2
  import { readerOption, type ReaderOption } from "./reader-option.ts";
3
3
 
4
4
  export interface SessionPaneDescriptor {
5
5
  browserIcon?: string | null;
6
+ /** #718: a terminal browser with native controls, a plain one, or null. */
7
+ browserKind?: "native" | "plain" | null;
6
8
  /** A live `tmux-ide open file.md` reader; the path stays daemon-side. */
7
9
  reader?: ReaderOption | null;
8
10
  nativePaneBirthId?: string | null;
@@ -62,6 +64,8 @@ export const SESSION_PANE_DESCRIPTOR_FORMAT = [
62
64
  "#{qa:@tmux_ide_reader}",
63
65
  // The reader option belongs to the pane only when its own process set it.
64
66
  "#{pane_pid}",
67
+ // Set only by a terminal browser that has tmux-ide's native controls (#718).
68
+ "#{qa:@tmux_ide_browser_control}",
65
69
  ].join("\t");
66
70
 
67
71
  /**
@@ -172,7 +176,7 @@ export function parseSessionPaneDescriptorReply(
172
176
  continue;
173
177
  }
174
178
  const encoded = utf8Line.split("\t");
175
- if (encoded.length < 21 || encoded.length > 25) continue;
179
+ if (encoded.length < 21 || encoded.length > 26) continue;
176
180
  const [
177
181
  runtimePaneId = "",
178
182
  semanticPaneId = "",
@@ -199,6 +203,7 @@ export function parseSessionPaneDescriptorReply(
199
203
  browserIconRaw = "",
200
204
  readerRaw = "",
201
205
  panePidRaw = "",
206
+ browserControl = "",
202
207
  ] = encoded.map(decodeTmuxArgument);
203
208
  if (!/^%(?:0|[1-9][0-9]*)$/u.test(runtimePaneId) || runtimePaneId.length > 32) continue;
204
209
  if (!/^\$(?:0|[1-9][0-9]*)$/u.test(runtimeSessionId) || runtimeSessionId.length > 32) continue;
@@ -239,6 +244,7 @@ export function parseSessionPaneDescriptorReply(
239
244
  }
240
245
  descriptors.push({
241
246
  browserIcon: browserIcon(browserIconRaw),
247
+ browserKind: terminalBrowserKind(browserControl, currentCommand),
242
248
  reader: readerOption(readerRaw, panePidRaw),
243
249
  sessionName,
244
250
  runtimePaneId,
@@ -431,3 +437,27 @@ export function decodeControlReplyUtf8(value: string): string | null {
431
437
  function positiveInteger(value: number | undefined, fallback: number): number {
432
438
  return Number.isSafeInteger(value) && value! > 0 ? value! : fallback;
433
439
  }
440
+
441
+ /**
442
+ * #718: a pane runs a terminal browser with tmux-ide's native controls while
443
+ * the browser that published @tmux_ide_browser_control is alive: the browser
444
+ * never clears the option, so a pane that outlives it (remain-on-exit,
445
+ * respawn-pane) is judged by what runs there now. A plain terminal browser
446
+ * is known by its process name (tmux cuts it to 15 characters on macOS).
447
+ */
448
+ export function terminalBrowserKind(
449
+ control: string,
450
+ currentCommand: string,
451
+ alive: (pid: number) => boolean = processAlive,
452
+ ): "native" | "plain" | null {
453
+ if (control.length > 0 && control.length <= 4096) {
454
+ try {
455
+ const pid = (JSON.parse(control) as { pid?: unknown } | null)?.pid;
456
+ if (typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && alive(pid))
457
+ return "native";
458
+ } catch {
459
+ // Not an endpoint: judged by the process name below.
460
+ }
461
+ }
462
+ return /^terminal-browser?$/u.test(currentCommand) ? "plain" : null;
463
+ }
@@ -2530,6 +2530,7 @@ class SessionRuntimeConsumerImpl implements SessionRuntimeConsumer {
2530
2530
  ack: (ack: TerminalDeliveryAck) => upstream.ack(ack),
2531
2531
  ...(upstream.projectionReceipt ? { projectionReceipt: upstream.projectionReceipt } : {}),
2532
2532
  ...(upstream.materialize ? { materialize: upstream.materialize } : {}),
2533
+ ...(upstream.prioritize ? { prioritize: upstream.prioritize } : {}),
2533
2534
  nack: (nack: TerminalDeliveryNack) => upstream.nack(nack),
2534
2535
  setVisibility: (visibility: TerminalDeliveryVisibility) => upstream.setVisibility(visibility),
2535
2536
  close: async () => {
@@ -88,6 +88,21 @@ const MAX_PANES = 32;
88
88
  const MAX_PENDING_CANONICAL_CELLS = 1_000_000;
89
89
  const MAX_CONNECTIONS = MAX_CLIENTS * MAX_PANES;
90
90
  const BACKGROUND_CADENCE_MS = 100;
91
+ /**
92
+ * One connection's unacknowledged delivery bytes, across its panes, before a
93
+ * pane other than the one it types into waits. A remote link (SSH) queues
94
+ * every sent byte ahead of the next input-ack and echo; this bounds that queue
95
+ * to about this much plus one delivery. Daemon policy only: nothing on the wire.
96
+ */
97
+ export const TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES = 256 * 1024;
98
+ /** No pane is held longer than this: it is then sent behind whatever is in flight. */
99
+ export const TERMINAL_DELIVERY_CONNECTION_HOLD_MS = 250;
100
+ /**
101
+ * A pane is held only once some delivery of its connection has gone this long
102
+ * unacknowledged: a fast link acks bulk within a few round trips, and holding
103
+ * there only bunches panes up behind each other.
104
+ */
105
+ export const TERMINAL_DELIVERY_CONNECTION_CONGESTED_MS = 30;
91
106
 
92
107
  export interface TerminalDeliveryMetrics {
93
108
  /** Unique delivery subscribers, independent of their pane count. */
@@ -143,6 +158,11 @@ export interface TerminalDeliveryConnection {
143
158
  materialize?(request: TerminalProjectionMaterialize): void;
144
159
  nack(nack: TerminalDeliveryNack): void;
145
160
  setVisibility(visibility: TerminalDeliveryVisibility): void;
161
+ /**
162
+ * The client typed into this pane: its deliveries go ahead of the
163
+ * connection's other panes and never wait for their acknowledgements.
164
+ */
165
+ prioritize?(): void;
146
166
  close(): Promise<void>;
147
167
  /**
148
168
  * Kitty graphics side channel, present only when the client offered
@@ -250,6 +270,11 @@ interface ClientState {
250
270
  /** Delivery displaced by authoritative source close; its racing ACK is benign. */
251
271
  sourceClosedFlight: DeliveryEnvelope | null;
252
272
  backgroundTimer: SessionRuntimeTimer | null;
273
+ /** Waiting for its connection's other panes to be acknowledged. */
274
+ budgetHeld: boolean;
275
+ /** When the current hold began (it ends by TERMINAL_DELIVERY_CONNECTION_HOLD_MS). */
276
+ budgetHeldSince: number | null;
277
+ budgetTimer: SessionRuntimeTimer | null;
253
278
  }
254
279
 
255
280
  type SeedEncodingOutcome = { readonly bytes: Uint8Array } | { readonly error: unknown };
@@ -373,6 +398,8 @@ export class SessionRuntimeTerminalDeliveryHub {
373
398
  readonly #observability: SessionRuntimeObservability;
374
399
  readonly #panes = new Map<string, PaneState>();
375
400
  readonly #clients = new Map<string, ClientState>();
401
+ /** Per connection: the pane it last typed into. */
402
+ readonly #priority = new Map<string, string>();
376
403
  #sourceCloseFailures = 0;
377
404
  #pendingSourceCloses = 0;
378
405
  /** Synchronous reservations held while an async pane source is starting. */
@@ -390,6 +417,8 @@ export class SessionRuntimeTerminalDeliveryHub {
390
417
  #deliveryLifecycleOrdinal = 0;
391
418
  #deliveryStatusOrdinal = 0;
392
419
  #closed = false;
420
+ readonly #holdMs: number;
421
+ readonly #congestedMs: number;
393
422
 
394
423
  constructor(
395
424
  readonly generation: SessionRuntimeGeneration,
@@ -398,9 +427,15 @@ export class SessionRuntimeTerminalDeliveryHub {
398
427
  options: {
399
428
  readonly scheduler?: SessionRuntimeScheduler;
400
429
  readonly observability?: SessionRuntimeObservability;
430
+ /** Tests only: the longest a pane waits for its connection's bulk. */
431
+ readonly connectionHoldMs?: number;
432
+ /** Tests only: how long unacked bulk takes to count as congestion. */
433
+ readonly connectionCongestedMs?: number;
401
434
  } = {},
402
435
  ) {
403
436
  this.#ownerForPane = ownerForPane;
437
+ this.#holdMs = options.connectionHoldMs ?? TERMINAL_DELIVERY_CONNECTION_HOLD_MS;
438
+ this.#congestedMs = options.connectionCongestedMs ?? TERMINAL_DELIVERY_CONNECTION_CONGESTED_MS;
404
439
  this.#scheduler = options.scheduler ?? SYSTEM_SESSION_RUNTIME_SCHEDULER;
405
440
  this.#observability = options.observability ?? DISABLED_SESSION_RUNTIME_OBSERVABILITY;
406
441
  }
@@ -484,6 +519,9 @@ export class SessionRuntimeTerminalDeliveryHub {
484
519
  lastAck: null,
485
520
  sourceClosedFlight: null,
486
521
  backgroundTimer: null,
522
+ budgetHeld: false,
523
+ budgetHeldSince: null,
524
+ budgetTimer: null,
487
525
  };
488
526
  this.#clients.set(key, client);
489
527
  client.lifecycleOpenRecorded = this.#recordDeliveryLifecycle(client, pane, "open");
@@ -496,6 +534,11 @@ export class SessionRuntimeTerminalDeliveryHub {
496
534
  projectionReceipt: (receipt) => this.#projectionReceipt(client, receipt),
497
535
  materialize: (request) => this.#materialize(client, request),
498
536
  nack: (nack) => this.#nack(client, nack),
537
+ prioritize: () => {
538
+ if (client.closed) return;
539
+ this.#priority.set(client.clientId, client.paneId);
540
+ this.#releaseBudget(client.clientId);
541
+ },
499
542
  setVisibility: (visibilityInput) => {
500
543
  if (client.closed) return;
501
544
  client.visibility = TerminalDeliveryVisibilitySchemaZ.parse(visibilityInput);
@@ -703,6 +746,7 @@ export class SessionRuntimeTerminalDeliveryHub {
703
746
  this.#cancelEncoding(client);
704
747
  client.outgoing.length = 0;
705
748
  client.inFlight = null;
749
+ client.budgetHeld = false;
706
750
  logDeliveryFault(client, "source-closed", "source-restarted");
707
751
  this.#enqueue(client, {
708
752
  type: "terminal.delivery.fault",
@@ -1069,6 +1113,37 @@ export class SessionRuntimeTerminalDeliveryHub {
1069
1113
  }
1070
1114
  }
1071
1115
 
1116
+ #overBudget(client: ClientState): boolean {
1117
+ if (this.#priority.get(client.clientId) === client.paneId) return false;
1118
+ if (
1119
+ client.budgetHeldSince !== null &&
1120
+ this.#scheduler.nowMs() - client.budgetHeldSince >= this.#holdMs
1121
+ )
1122
+ return false;
1123
+ const now = this.#scheduler.nowMs();
1124
+ let bytes = 0;
1125
+ let oldest = now;
1126
+ for (const other of this.#clients.values())
1127
+ if (other !== client && other.clientId === client.clientId && other.inFlight) {
1128
+ bytes += other.inFlight.envelope.representationBytes;
1129
+ oldest = Math.min(oldest, other.inFlight.sentAt);
1130
+ }
1131
+ return bytes >= TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES && now - oldest >= this.#congestedMs;
1132
+ }
1133
+
1134
+ /** A pane's delivery settled or left: held panes of its connection try again, typed-into pane first. */
1135
+ #releaseBudget(clientId: string): void {
1136
+ const held = [...this.#clients.values()].filter(
1137
+ (other) => other.clientId === clientId && other.budgetHeld,
1138
+ );
1139
+ const priority = this.#priority.get(clientId);
1140
+ held.sort((a, b) => Number(b.paneId === priority) - Number(a.paneId === priority));
1141
+ for (const other of held) {
1142
+ other.budgetHeld = false;
1143
+ this.#schedule(other);
1144
+ }
1145
+ }
1146
+
1072
1147
  #schedule(client: ClientState): void {
1073
1148
  if (
1074
1149
  client.closed ||
@@ -1121,6 +1196,20 @@ export class SessionRuntimeTerminalDeliveryHub {
1121
1196
  (!completed && target.update.revision !== client.latestRevision)
1122
1197
  )
1123
1198
  return;
1199
+ if (!completed && this.#overBudget(client)) {
1200
+ client.budgetHeld = true;
1201
+ client.budgetHeldSince ??= this.#scheduler.nowMs();
1202
+ client.budgetTimer ??= this.#scheduler.timer(() => {
1203
+ client.budgetTimer = null;
1204
+ if (client.closed || !client.budgetHeld) return;
1205
+ client.budgetHeld = false;
1206
+ this.#schedule(client);
1207
+ }, this.#holdMs);
1208
+ return;
1209
+ }
1210
+ client.budgetHeldSince = null;
1211
+ client.budgetTimer?.cancel();
1212
+ client.budgetTimer = null;
1124
1213
  const traceStarted =
1125
1214
  completed?.traceStarted ??
1126
1215
  (this.#observability.enabled ? this.#observability.nowMicros() : 0);
@@ -1838,6 +1927,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1838
1927
  client.baselineHash = ack.canonicalStateHash;
1839
1928
  client.reseedRequired = false;
1840
1929
  client.inFlight = null;
1930
+ this.#releaseBudget(client.clientId);
1841
1931
  client.lastAck = ack;
1842
1932
  if (client.latestRevision === ack.canonicalRevision) client.latestRevision = null;
1843
1933
  this.#pruneAckSupersededCache(client.paneId);
@@ -1927,6 +2017,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1927
2017
  client.lastProjectionReceipt = receipt;
1928
2018
  client.reseedRequired = false;
1929
2019
  client.inFlight = null;
2020
+ this.#releaseBudget(client.clientId);
1930
2021
  if (client.latestRevision === receipt.canonicalRevision) client.latestRevision = null;
1931
2022
  if (client.materializeRequested)
1932
2023
  client.latestRevision = this.#panes.get(client.paneId)?.latest?.update.revision ?? null;
@@ -2004,6 +2095,7 @@ export class SessionRuntimeTerminalDeliveryHub {
2004
2095
  this.#nacks += 1;
2005
2096
  client.reseedRequired = true;
2006
2097
  client.inFlight = null;
2098
+ this.#releaseBudget(client.clientId);
2007
2099
  this.#pruneCanonicalRevisions(client.paneId);
2008
2100
  this.#schedule(client);
2009
2101
  this.#recordDeliveryStatus(client, this.#panes.get(client.paneId));
@@ -2058,6 +2150,7 @@ export class SessionRuntimeTerminalDeliveryHub {
2058
2150
  client.outgoing.length = 0;
2059
2151
  if (reason === "source-closed") client.sourceClosedFlight = client.inFlight?.envelope ?? null;
2060
2152
  client.inFlight = null;
2153
+ this.#releaseBudget(client.clientId);
2061
2154
  const fault: TerminalDeliveryServerMessage = {
2062
2155
  type: "terminal.delivery.fault",
2063
2156
  reason,
@@ -2137,8 +2230,13 @@ export class SessionRuntimeTerminalDeliveryHub {
2137
2230
  if (client.lifecycleOpenRecorded)
2138
2231
  this.#recordDeliveryLifecycle(client, this.#panes.get(client.paneId), "close");
2139
2232
  client.backgroundTimer?.cancel();
2233
+ client.budgetTimer?.cancel();
2234
+ client.budgetTimer = null;
2140
2235
  client.outgoing.length = 0;
2141
2236
  this.#clients.delete(client.key);
2237
+ if (![...this.#clients.values()].some((other) => other.clientId === client.clientId))
2238
+ this.#priority.delete(client.clientId);
2239
+ else this.#releaseBudget(client.clientId);
2142
2240
  this.#pruneCanonicalRevisions(client.paneId);
2143
2241
  if ([...this.#clients.values()].some((candidate) => candidate.paneId === client.paneId)) return;
2144
2242
  const pane = this.#panes.get(client.paneId);
@@ -2584,12 +2682,13 @@ function semanticPayload(
2584
2682
  // append-only history is proved here; trim/reflow and changed dimensions
2585
2683
  // retain the full seed boundary. Equality includes wrapped and all cells.
2586
2684
  const snapshot = target.state.snapshot;
2685
+ const trim = baseline ? historyTrim(baseline.history, snapshot.history) : 0;
2587
2686
  if (
2588
2687
  baseline &&
2589
2688
  baselineIncarnation === update.incarnation &&
2590
2689
  baseline.cols === snapshot.cols &&
2591
2690
  baseline.rows === snapshot.rows &&
2592
- baseline.history.length <= snapshot.history.length
2691
+ baseline.history.length - trim <= snapshot.history.length
2593
2692
  ) {
2594
2693
  // Identity reuse is cheap, but detached equal histories must not turn a
2595
2694
  // cooperative seed into an unbounded synchronous cell comparison.
@@ -2604,8 +2703,8 @@ function semanticPayload(
2604
2703
  ? terminalReplicaRowsEqual(left, right)
2605
2704
  : null;
2606
2705
  };
2607
- for (let index = 0; index < baseline.history.length; index++)
2608
- if (equal(baseline.history[index]!, snapshot.history[index]!) !== true)
2706
+ for (let index = trim; index < baseline.history.length; index++)
2707
+ if (equal(baseline.history[index]!, snapshot.history[index - trim]!) !== true)
2609
2708
  return semanticSeed(target);
2610
2709
  const rows: { index: number; row: TerminalReplicaSnapshot["grid"][number] }[] = [];
2611
2710
  for (let index = 0; index < snapshot.grid.length; index++) {
@@ -2613,19 +2712,20 @@ function semanticPayload(
2613
2712
  if (same === null) return semanticSeed(target);
2614
2713
  if (!same) rows.push({ index, row: snapshot.grid[index]! });
2615
2714
  }
2616
- const appendedRows = snapshot.history.length - baseline.history.length;
2715
+ const retained = baseline.history.length - trim;
2716
+ const appendedRows = snapshot.history.length - retained;
2617
2717
  // Compact patches serialize synchronously. Do not move a large appended
2618
2718
  // suffix or repaint across the seed-only cooperative encoding boundary.
2619
2719
  if ((rows.length + appendedRows) * snapshot.cols >= TERMINAL_COMPACT_COOPERATIVE_SEED_CELLS)
2620
2720
  return semanticSeed(target);
2621
- const append = snapshot.history.slice(baseline.history.length);
2721
+ const append = snapshot.history.slice(retained);
2622
2722
  return {
2623
2723
  frame: "patch",
2624
2724
  baseRevision: baselineRevision,
2625
2725
  revision: update.revision,
2626
2726
  patch: {
2627
2727
  rows,
2628
- ...(append.length ? { historyDelta: { trim: 0, append } } : {}),
2728
+ ...(append.length || trim ? { historyDelta: { trim, append } } : {}),
2629
2729
  cursor: snapshot.cursor,
2630
2730
  modes: snapshot.modes,
2631
2731
  placements: snapshot.placements,
@@ -2636,6 +2736,36 @@ function semanticPayload(
2636
2736
  return semanticSeed(target);
2637
2737
  }
2638
2738
 
2739
+ /**
2740
+ * How many of the baseline's oldest history rows the target dropped, proved by
2741
+ * row identity only: the replica keeps each surviving row object when tmux
2742
+ * trims at its history-limit. Zero when nothing was trimmed or no shift is
2743
+ * proved; the caller still checks every retained row exactly.
2744
+ */
2745
+ function historyTrim(
2746
+ baseline: TerminalReplicaSnapshot["history"],
2747
+ target: TerminalReplicaSnapshot["history"],
2748
+ ): number {
2749
+ const first = target[0];
2750
+ if (first === undefined || baseline[0] === first) return 0;
2751
+ // A shared row object (a blank row) can recur; prove at most a few shifts.
2752
+ let candidates = 0;
2753
+ for (let trim = 1; trim < baseline.length; trim++) {
2754
+ if (baseline[trim] !== first) continue;
2755
+ if (++candidates > 4) return 0;
2756
+ const retained = baseline.length - trim;
2757
+ if (retained > target.length) continue;
2758
+ let same = true;
2759
+ for (let index = 0; index < retained; index++)
2760
+ if (baseline[trim + index] !== target[index]) {
2761
+ same = false;
2762
+ break;
2763
+ }
2764
+ if (same) return trim;
2765
+ }
2766
+ return 0;
2767
+ }
2768
+
2639
2769
  /** Account represented cells without traversing/serializing the snapshot. */
2640
2770
  function canonicalUpdateCellCost(update: CanonicalTerminalReplicaUpdate): number {
2641
2771
  if (update.type === "terminal.tombstone") return 0;
@@ -41,6 +41,12 @@ export interface TerminalInterpreterBackend {
41
41
  setAuthoritativeModes(modes: MirrorObservedTerminalModes): void;
42
42
  /** A pre-existing saved buffer became active without authoritative backing. */
43
43
  requiresNativeReseed(): boolean;
44
+ /**
45
+ * From now on, collect history at the limit the way tmux does. Off while a
46
+ * capture is replayed: tmux's captured history (which can exceed a lowered
47
+ * limit) is replayed as it is.
48
+ */
49
+ startHistoryCollection?(): void;
44
50
  modes(): TerminalReplicaModes;
45
51
  dirtyRange(): { readonly start: number; readonly end: number } | undefined;
46
52
  project(
@@ -270,6 +270,7 @@ export class TerminalReplicaInterpreter {
270
270
  rows: options.rows,
271
271
  scrollback: this.#scrollback,
272
272
  });
273
+ this.#backend.startHistoryCollection?.();
273
274
  this.#kitty = new KittyImageStore(
274
275
  options.kittyImageBudget ? { budget: options.kittyImageBudget } : {},
275
276
  );
@@ -501,6 +502,7 @@ export class TerminalReplicaInterpreter {
501
502
  this.#admitRaw(chunk);
502
503
  this.#observeMarkerBytes(chunk);
503
504
  }
505
+ replacement.startHistoryCollection?.();
504
506
  const previous = this.#backend;
505
507
  this.#backend = replacement;
506
508
  this.#attachKitty(replacement);