tmux-ide 2.9.24 → 2.9.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/bin/cli.js +1689 -393
  2. package/package.json +5 -2
  3. package/packages/contracts/src/pane-stream.ts +72 -0
  4. package/packages/contracts/src/terminal-delivery.ts +8 -2
  5. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  6. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  7. package/packages/daemon/dist/command-center/discovery.js +24 -5
  8. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  9. package/packages/daemon/dist/command-center/server.js +81 -75
  10. package/packages/daemon/dist/command-center/tmux-servers.js +17 -7
  11. package/packages/daemon/dist/doctor.js +46 -10
  12. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  13. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  14. package/packages/daemon/dist/lib/daemon-embed.js +6 -0
  15. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  16. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  17. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  18. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  19. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  20. package/packages/daemon/dist/lib/update-check.js +18 -0
  21. package/packages/daemon/dist/lib/update-daemon-outcome.js +31 -0
  22. package/packages/daemon/dist/lib/update.js +39 -14
  23. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  27. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  28. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  29. package/packages/daemon/dist/terminal/mirror/session-channel.js +31 -2
  30. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  31. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +831 -222
  32. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  33. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  34. package/packages/daemon/dist/terminal/session-runtime/registry.js +25 -2
  35. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +121 -6
  36. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +79 -2
  37. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  38. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  39. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  40. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  41. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  42. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  43. package/packages/daemon/src/command-center/discovery.ts +24 -4
  44. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  45. package/packages/daemon/src/command-center/server.ts +67 -67
  46. package/packages/daemon/src/command-center/tmux-servers.ts +19 -6
  47. package/packages/daemon/src/doctor.ts +50 -9
  48. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  49. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  50. package/packages/daemon/src/lib/daemon-embed.ts +22 -0
  51. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  52. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  53. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  54. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  55. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  56. package/packages/daemon/src/lib/update-check.ts +34 -0
  57. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  58. package/packages/daemon/src/lib/update.ts +58 -16
  59. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  60. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  61. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  62. package/packages/daemon/src/terminal/mirror/session-channel.ts +38 -2
  63. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  64. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +915 -236
  65. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  66. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  67. package/packages/daemon/src/terminal/session-runtime/registry.ts +36 -2
  68. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +136 -6
  69. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  70. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +76 -2
  71. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  72. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  73. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
  74. package/packages/daemon/src/tui/chrome/snapshot.ts +47 -1
  75. package/packages/daemon/src/tui/chrome/statusline.ts +7 -4
  76. package/packages/daemon/src/tui/chrome/updater.ts +3 -0
  77. package/packages/daemon-client/src/pane-stream-client.ts +47 -5
@@ -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
+ }
@@ -220,6 +220,18 @@ export class SessionRuntimeControllerLeaseError extends Error {
220
220
  }
221
221
  }
222
222
 
223
+ /**
224
+ * An input fenced to a pane lifetime (capability 105) whose lifetime has
225
+ * ended: its owner is gone or was replaced. The input must not reach another
226
+ * lifetime; the pane's delivery tells the client that its lifetime ended.
227
+ */
228
+ export class SessionRuntimeInputLifetimeEndedError extends Error {
229
+ constructor(message: string) {
230
+ super(message);
231
+ this.name = "SessionRuntimeInputLifetimeEndedError";
232
+ }
233
+ }
234
+
223
235
  export interface SessionRuntimeConsumer {
224
236
  readonly generation: SessionRuntimeGeneration;
225
237
  readonly session: string;
@@ -696,6 +708,11 @@ export class SessionRuntimeRegistry implements PaneStreamMirror {
696
708
  await this.#mirror.verifyRegisteredWindows();
697
709
  }
698
710
 
711
+ /** Ownership is being read again: input and geometry wait, they are not refused for good. */
712
+ windowOwnershipPending(): boolean {
713
+ return !this.#disposed && this.#mirror.windowOwnershipPending();
714
+ }
715
+
699
716
  /** Install the bounded registered-session membership reader. */
700
717
  setRegisteredWindowReader(
701
718
  reader: import("../mirror/registered-window-guard.ts").RegisteredWindowReader,
@@ -1264,6 +1281,12 @@ class SessionRuntime {
1264
1281
  readonly #consumersByClientId = new Map<string, SessionRuntimeConsumerImpl>();
1265
1282
  readonly #terminalReplicas = new Map<string, SessionRuntimeTerminalReplicaOwner>();
1266
1283
  readonly #terminalReplicaClocks = new Map<string, { epoch: number; revision: number }>();
1284
+ /** The renderer's last reported cell size; every pane's image placements use it. */
1285
+ #cellPixels: {
1286
+ width: number;
1287
+ height: number;
1288
+ precise?: { width: number; height: number };
1289
+ } | null = null;
1267
1290
  #outputTraces: RuntimeTraceCorrelator | null;
1268
1291
  readonly #outputObservations = new Map<
1269
1292
  string,
@@ -1658,7 +1681,8 @@ class SessionRuntime {
1658
1681
  const replicaOwner = expectedLifetime
1659
1682
  ? this.#terminalReplicas.get(semanticPaneId)
1660
1683
  : this.#terminalReplicaOwner(semanticPaneId);
1661
- if (!replicaOwner) throw new Error("Input target lifetime unavailable");
1684
+ if (!replicaOwner)
1685
+ throw new SessionRuntimeInputLifetimeEndedError("Input target lifetime unavailable");
1662
1686
  if (causalProbe) {
1663
1687
  this.#activeCausalCellProbes += 1;
1664
1688
  let settled = false;
@@ -1689,7 +1713,7 @@ class SessionRuntime {
1689
1713
  this.#terminalReplicas.get(semanticPaneId) !== replicaOwner ||
1690
1714
  replicaOwner.inputAdmissionIncarnation() !== expectedLifetime.incarnation)
1691
1715
  )
1692
- throw new Error("Input target lifetime changed");
1716
+ throw new SessionRuntimeInputLifetimeEndedError("Input target lifetime changed");
1693
1717
  if (input.kind === "text")
1694
1718
  this.#mirror.sendText(
1695
1719
  this.session,
@@ -1818,6 +1842,9 @@ class SessionRuntime {
1818
1842
  ): void {
1819
1843
  this.#assertConnected(clientId);
1820
1844
  this.#mirror.setCellPixels?.(this.session, width, height, precise);
1845
+ this.#cellPixels = { width, height, ...(precise ? { precise } : {}) };
1846
+ for (const owner of this.#terminalReplicas.values())
1847
+ owner.setCellPixels(width, height, precise);
1821
1848
  }
1822
1849
 
1823
1850
  fitViewportWithAuthority(
@@ -2042,6 +2069,12 @@ class SessionRuntime {
2042
2069
  },
2043
2070
  );
2044
2071
  owner = candidate;
2072
+ if (this.#cellPixels)
2073
+ owner.setCellPixels(
2074
+ this.#cellPixels.width,
2075
+ this.#cellPixels.height,
2076
+ this.#cellPixels.precise,
2077
+ );
2045
2078
  this.#terminalReplicas.set(semanticPaneId, owner);
2046
2079
  }
2047
2080
  return owner;
@@ -2497,6 +2530,7 @@ class SessionRuntimeConsumerImpl implements SessionRuntimeConsumer {
2497
2530
  ack: (ack: TerminalDeliveryAck) => upstream.ack(ack),
2498
2531
  ...(upstream.projectionReceipt ? { projectionReceipt: upstream.projectionReceipt } : {}),
2499
2532
  ...(upstream.materialize ? { materialize: upstream.materialize } : {}),
2533
+ ...(upstream.prioritize ? { prioritize: upstream.prioritize } : {}),
2500
2534
  nack: (nack: TerminalDeliveryNack) => upstream.nack(nack),
2501
2535
  setVisibility: (visibility: TerminalDeliveryVisibility) => upstream.setVisibility(visibility),
2502
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(
@@ -1,4 +1,5 @@
1
1
  import { assertStockCaptureRepresentable } from "./stock-capture-fidelity.ts";
2
+ import { logger } from "../../lib/log.ts";
2
3
  import { rememberNativeSeedBacking } from "./native-seed-backing.ts";
3
4
  import type { NativeGridCapture } from "../mirror/native-grid-capture.ts";
4
5
  import type { MirrorObservedTerminalModes } from "../mirror/events.ts";
@@ -184,6 +185,9 @@ export class TerminalReplicaInterpreter {
184
185
  #nativeSeedBackingCandidate: NativeGridCapture | undefined;
185
186
  readonly #generation: SessionRuntimeGeneration;
186
187
  readonly #workspaceName: string;
188
+ #stockTabsNoted = false;
189
+ #seedOrdinal = 0;
190
+ #reconstructedSeed: number | null = null;
187
191
  readonly #semanticPaneId: string;
188
192
  readonly #incarnation: string;
189
193
  #scrollback: number;
@@ -266,6 +270,7 @@ export class TerminalReplicaInterpreter {
266
270
  rows: options.rows,
267
271
  scrollback: this.#scrollback,
268
272
  });
273
+ this.#backend.startHistoryCollection?.();
269
274
  this.#kitty = new KittyImageStore(
270
275
  options.kittyImageBudget ? { budget: options.kittyImageBudget } : {},
271
276
  );
@@ -344,6 +349,15 @@ export class TerminalReplicaInterpreter {
344
349
  return this.#needsSeed ? null : this.#seed();
345
350
  }
346
351
 
352
+ /**
353
+ * Names the current seed when its tab cells were reconstructed from a stock
354
+ * capture; null otherwise. Such a seed can wrap a reflowed line at other
355
+ * places than tmux does, so its history can differ from tmux's in length.
356
+ */
357
+ reconstructedSeed(): number | null {
358
+ return this.#reconstructedSeed;
359
+ }
360
+
347
361
  /** Prioritize one future parser admission, independent of diagnostic tracing. */
348
362
  prioritizeNextWrite(): void {
349
363
  if (!this.#closed) this.#prioritizeNextWrite = true;
@@ -428,7 +442,12 @@ export class TerminalReplicaInterpreter {
428
442
  ): Promise<void> {
429
443
  if (this.#closed) return;
430
444
  if (operation.type === "reseed") {
431
- if (operation.bootstrap === "painted-capture" && !operation.native)
445
+ // A stock capture prints a saved tab cell as one HT and drops its width.
446
+ // Paint it to the next tab stop; refuse only when the parser cannot say
447
+ // where its cursor is.
448
+ const paintCapturedTabs = operation.bootstrap === "painted-capture" && !operation.native;
449
+ let seedReconstructed: boolean;
450
+ if (paintCapturedTabs && !this.#backend.graphicsCursor)
432
451
  assertStockCaptureRepresentable(operation.captureChunks ?? operation.chunks);
433
452
  this.#causalCell?.fail("reseeded");
434
453
  const nativeCols = operation.nativeCols ?? operation.cols;
@@ -447,9 +466,23 @@ export class TerminalReplicaInterpreter {
447
466
  try {
448
467
  if (operation.native && !replacement.importNativeGrid?.(operation.native))
449
468
  throw new Error("Native bootstrap requires a compatible interpreter");
469
+ // Capture chunks come first and in order; anything else is live output,
470
+ // where HT stays cursor motion.
471
+ const captured = operation.captureChunks ?? operation.chunks;
472
+ let nextCaptured = 0;
473
+ let reconstructed = false;
450
474
  for (const chunk of operation.chunks) {
451
- await this.#writeToBackend(replacement, chunk);
475
+ const fromCapture =
476
+ paintCapturedTabs &&
477
+ nextCaptured < captured.length &&
478
+ Buffer.compare(chunk, captured[nextCaptured]!) === 0;
479
+ if (fromCapture) nextCaptured += 1;
480
+ if (fromCapture && chunk.includes(9)) {
481
+ reconstructed = true;
482
+ await this.#writeStockCapture(replacement, chunk);
483
+ } else await this.#writeToBackend(replacement, chunk);
452
484
  }
485
+ seedReconstructed = reconstructed;
453
486
  if (operation.wraparound !== undefined)
454
487
  replacement.setAuthoritativeWraparound(operation.wraparound);
455
488
  if (operation.observedModes) replacement.setAuthoritativeModes(operation.observedModes);
@@ -469,6 +502,7 @@ export class TerminalReplicaInterpreter {
469
502
  this.#admitRaw(chunk);
470
503
  this.#observeMarkerBytes(chunk);
471
504
  }
505
+ replacement.startHistoryCollection?.();
472
506
  const previous = this.#backend;
473
507
  this.#backend = replacement;
474
508
  this.#attachKitty(replacement);
@@ -484,6 +518,8 @@ export class TerminalReplicaInterpreter {
484
518
  previous.modes().alternateScreen === replacement.modes().alternateScreen;
485
519
  if (!sameGraphicsBasis) this.#kitty.dropCursorPlacements();
486
520
  this.#nativeReseedRequested = false;
521
+ this.#seedOrdinal += 1;
522
+ this.#reconstructedSeed = seedReconstructed ? this.#seedOrdinal : null;
487
523
  this.#scrollback = scrollback;
488
524
  this.#bootstrap = {
489
525
  kind: operation.bootstrap,
@@ -673,6 +709,44 @@ export class TerminalReplicaInterpreter {
673
709
  }, 250);
674
710
  }
675
711
 
712
+ /**
713
+ * Replay one stock `capture-pane -e` chunk. tmux stores a tab as one wide
714
+ * cell and prints it as a single HT, without its width. Blank the cells up
715
+ * to the next default tab stop instead (ECH, then CUF): that is the cell tmux
716
+ * made when the tab was written at this column, and erased cells take the
717
+ * rendition the capture set for it, as tmux's blank tab cell does. tmux never
718
+ * tabs into the last column (`input_c0_dispatch`).
719
+ * Where this differs from tmux: a row edited after its tab was written
720
+ * (insert or delete character) or written under custom tab stops is columns
721
+ * off in that row. A line reflowed by a resize is worse: tmux keeps the tab
722
+ * cell's width, this measures it again from the new column, so the line can
723
+ * wrap at other places and the pane can hold other rows than tmux shows,
724
+ * until that output scrolls away or is redrawn. The owner accepts the
725
+ * resulting difference in history length (`reconstructedSeed`).
726
+ */
727
+ async #writeStockCapture(backend: TerminalInterpreterBackend, chunk: Uint8Array): Promise<void> {
728
+ let start = 0;
729
+ for (;;) {
730
+ const tab = chunk.indexOf(9, start);
731
+ if (tab < 0) break;
732
+ if (tab > start) await this.#writeToBackend(backend, chunk.subarray(start, tab));
733
+ const column = backend.graphicsCursor!().x;
734
+ const stop = Math.min(backend.cols - 1, (Math.floor(column / 8) + 1) * 8);
735
+ if (stop > column)
736
+ await this.#writeToBackend(backend, `\x1b[${stop - column}X\x1b[${stop - column}C`);
737
+ start = tab + 1;
738
+ }
739
+ if (!this.#stockTabsNoted) {
740
+ this.#stockTabsNoted = true;
741
+ // Once per pane: its saved rows are not tmux's exact cells on this server.
742
+ logger.info("terminal-replica", "stock capture: tab positions reconstructed", {
743
+ pane: this.#semanticPaneId,
744
+ workspace: this.#workspaceName,
745
+ });
746
+ }
747
+ if (start < chunk.length) await this.#writeToBackend(backend, chunk.subarray(start));
748
+ }
749
+
676
750
  #writeToBackend(backend: TerminalInterpreterBackend, data: Uint8Array | string): Promise<void> {
677
751
  if (this.#prioritizeNextWrite) {
678
752
  this.#prioritizeNextWrite = false;
@@ -128,6 +128,7 @@ export class SessionRuntimeTerminalReplicaOwner {
128
128
  #historyTimer: SessionRuntimeTimer | null = null;
129
129
  #historyChecking = false;
130
130
  #historyDirty = false;
131
+ #reconstructedHistoryGap: { readonly seed: number; readonly gap: number } | null = null;
131
132
 
132
133
  constructor(
133
134
  readonly generation: SessionRuntimeGeneration,
@@ -437,6 +438,11 @@ export class SessionRuntimeTerminalReplicaOwner {
437
438
  return this.#interpreter.onGraphics(listener);
438
439
  }
439
440
 
441
+ /** The renderer's cell size, for image placements that give no `c`/`r` (group H). */
442
+ setCellPixels(width: number, height: number, precise?: { width: number; height: number }): void {
443
+ this.#interpreter.kittyImages().setCellPixels(width, height, precise);
444
+ }
445
+
440
446
  /** Image bytes by content digest, while the pane's store still holds them. */
441
447
  graphicsImage(digest: string): KittyImage | null {
442
448
  return this.#interpreter.kittyImages().imageByDigest(digest) ?? null;
@@ -515,7 +521,21 @@ export class SessionRuntimeTerminalReplicaOwner {
515
521
  )
516
522
  return;
517
523
  const seed = this.#interpreter.currentSeed();
518
- if (seed && seed.snapshot.history.length !== size) upstream.reseed();
524
+ if (!seed) return;
525
+ const gap = size - seed.snapshot.history.length;
526
+ // A seed with reconstructed tabs can differ from tmux in row count, and
527
+ // a new capture would paint the same rows again. Accept the difference
528
+ // that seed has at its first check, zero included, and reseed only when
529
+ // the difference changes.
530
+ const reconstructed = this.#interpreter.reconstructedSeed();
531
+ if (reconstructed !== null) {
532
+ if (this.#reconstructedHistoryGap?.seed !== reconstructed) {
533
+ this.#reconstructedHistoryGap = { seed: reconstructed, gap };
534
+ return;
535
+ }
536
+ if (this.#reconstructedHistoryGap.gap === gap) return;
537
+ } else if (gap === 0) return;
538
+ upstream.reseed();
519
539
  } catch {
520
540
  // Unavailable metadata is not evidence that history disappeared.
521
541
  } finally {