tmux-ide 2.9.26 → 2.9.28

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 (89) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +2046 -623
  3. package/package.json +2 -2
  4. package/packages/contracts/src/pane-stream.ts +45 -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/resources/terminal-runtime-inventory.js +17 -3
  13. package/packages/daemon/dist/command-center/server.js +3 -0
  14. package/packages/daemon/dist/command-center/tmux-server-attach.js +51 -0
  15. package/packages/daemon/dist/command-center/tmux-servers.js +80 -1
  16. package/packages/daemon/dist/doctor.js +4 -4
  17. package/packages/daemon/dist/lib/app-config.js +7 -0
  18. package/packages/daemon/dist/lib/node-requirement.js +20 -0
  19. package/packages/daemon/dist/lib/require-supported-node.js +8 -0
  20. package/packages/daemon/dist/lib/tmux-server-session-open.js +38 -12
  21. package/packages/daemon/dist/lib/workspace-promotion.js +4 -4
  22. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  23. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  26. package/packages/daemon/dist/server/pane-stream-upgrade.js +39 -1
  27. package/packages/daemon/dist/terminal/attachments/native-runtime.js +12 -8
  28. package/packages/daemon/dist/terminal/mirror/mirror-service.js +13 -0
  29. package/packages/daemon/dist/terminal/mirror/native-atomic-snapshot.js +17 -7
  30. package/packages/daemon/dist/terminal/mirror/native-grid-capture.js +129 -5
  31. package/packages/daemon/dist/terminal/mirror/pane-feed.js +4 -0
  32. package/packages/daemon/dist/terminal/mirror/pane-hold.js +13 -0
  33. package/packages/daemon/dist/terminal/mirror/session-channel.js +198 -27
  34. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  35. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +198 -12
  36. package/packages/daemon/dist/terminal/protocol/layout-parse.js +99 -10
  37. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +5 -2
  38. package/packages/daemon/dist/terminal/session-runtime/registry.js +1 -0
  39. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +465 -42
  40. package/packages/daemon/dist/terminal/session-runtime/terminal-interpreter-backend.js +2 -1
  41. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +46 -1
  42. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +128 -3
  43. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +115 -6
  44. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +94 -2
  45. package/packages/daemon/dist/tui/mirror/runtime/open-tui-generation-host.js +9 -1
  46. package/packages/daemon/dist/tui/mirror/theme.js +8 -1
  47. package/packages/daemon/dist/tui/mirror/workspace/connection-feedback.js +8 -0
  48. package/packages/daemon/src/command-center/attach-window-rule.cases.json +84 -0
  49. package/packages/daemon/src/command-center/owner-keep-alive.ts +38 -0
  50. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +20 -2
  51. package/packages/daemon/src/command-center/server.ts +3 -0
  52. package/packages/daemon/src/command-center/tmux-server-attach.ts +75 -0
  53. package/packages/daemon/src/command-center/tmux-servers.ts +88 -1
  54. package/packages/daemon/src/doctor.ts +4 -4
  55. package/packages/daemon/src/lib/app-config.ts +15 -0
  56. package/packages/daemon/src/lib/node-requirement.ts +22 -0
  57. package/packages/daemon/src/lib/require-supported-node.ts +9 -0
  58. package/packages/daemon/src/lib/tmux-server-session-open.ts +53 -15
  59. package/packages/daemon/src/lib/workspace-promotion.ts +4 -4
  60. package/packages/daemon/src/server/pane-stream-upgrade.ts +41 -1
  61. package/packages/daemon/src/terminal/attachments/native-runtime.ts +15 -1
  62. package/packages/daemon/src/terminal/mirror/events.ts +31 -1
  63. package/packages/daemon/src/terminal/mirror/mirror-service.ts +19 -0
  64. package/packages/daemon/src/terminal/mirror/native-atomic-snapshot.ts +16 -5
  65. package/packages/daemon/src/terminal/mirror/native-grid-capture.ts +164 -5
  66. package/packages/daemon/src/terminal/mirror/pane-feed.ts +5 -0
  67. package/packages/daemon/src/terminal/mirror/pane-hold.ts +16 -0
  68. package/packages/daemon/src/terminal/mirror/session-channel.ts +253 -38
  69. package/packages/daemon/src/terminal/mirror/trusted-inventory.ts +2 -0
  70. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  71. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +240 -12
  72. package/packages/daemon/src/terminal/protocol/layout-parse.ts +109 -10
  73. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +10 -1
  74. package/packages/daemon/src/terminal/session-runtime/registry.ts +1 -0
  75. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -1
  76. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +575 -39
  77. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +24 -1
  78. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +61 -5
  79. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +159 -32
  80. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +134 -11
  81. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +101 -2
  82. package/packages/daemon/src/tui/mirror/runtime/open-tui-generation-host.ts +13 -0
  83. package/packages/daemon/src/tui/mirror/theme.ts +13 -1
  84. package/packages/daemon/src/tui/mirror/workspace/connection-feedback.ts +13 -1
  85. package/packages/daemon-client/src/direct-application-shell-transport.ts +6 -2
  86. package/packages/daemon-client/src/pane-stream-client.ts +24 -6
  87. package/packages/daemon-client/src/workspace-client-types.ts +6 -0
  88. package/packages/daemon-client/src/workspace-client.ts +15 -9
  89. package/packages/daemon-client/src/workspace-event-supervisor.ts +3 -1
@@ -1,4 +1,9 @@
1
- import { isNativeBootstrapCapture, type NativeGridCapture } from "../mirror/native-grid-capture.ts";
1
+ import {
2
+ isNativeBootstrapCapture,
3
+ type NativeGridCapture,
4
+ type NativeGridCaptureRow,
5
+ type NativeHistoryPiece,
6
+ } from "../mirror/native-grid-capture.ts";
2
7
  import { projectNativeGridRow } from "../mirror/native-grid-projection.ts";
3
8
  import type { MirrorObservedTerminalModes } from "../mirror/events.ts";
4
9
  import { Terminal } from "@tmux-ide/xterm-headless";
@@ -11,10 +16,11 @@ import type {
11
16
  TerminalReplicaSnapshot,
12
17
  } from "@tmux-ide/contracts";
13
18
  import { createProjectedTerminalReplicaRowBuilder } from "@tmux-ide/core";
14
- import type {
15
- TerminalInterpreterBackend,
16
- TerminalInterpreterBackendFactoryOptions,
17
- TerminalInterpreterBackendProjection,
19
+ import {
20
+ DAEMON_HISTORY_ROW_CAP,
21
+ type TerminalInterpreterBackend,
22
+ type TerminalInterpreterBackendFactoryOptions,
23
+ type TerminalInterpreterBackendProjection,
18
24
  } from "./terminal-interpreter-backend.ts";
19
25
 
20
26
  /** Pinned xterm 6 adapter and the rollback oracle for native backends. */
@@ -37,10 +43,15 @@ export class XtermTerminalInterpreterBackend implements TerminalInterpreterBacke
37
43
  #nativeModesObserved = false;
38
44
  #historyProjectionInvalidated = false;
39
45
  #scrollOnClear: boolean | undefined;
46
+ /** #873: tmux history rows older than the oldest row held (see omittedHistory). */
47
+ #omittedHistory = 0;
48
+ /** #873: the most history rows held; rows pushed past it count as left out. */
49
+ readonly #historyRowCap: number;
40
50
 
41
51
  constructor(options: TerminalInterpreterBackendFactoryOptions) {
42
52
  const historyLimit = options.historyLimit ?? options.scrollback;
43
53
  this.#historyLimit = historyLimit;
54
+ this.#historyRowCap = options.historyRowCap ?? DAEMON_HISTORY_ROW_CAP;
44
55
  this.#terminal = new Terminal({
45
56
  cols: options.cols,
46
57
  rows: options.rows,
@@ -115,9 +126,32 @@ export class XtermTerminalInterpreterBackend implements TerminalInterpreterBacke
115
126
  */
116
127
  startHistoryCollection(): void {
117
128
  this.#collecting = true;
129
+ this.#enforceRowCap();
118
130
  this.#lastYbase = this.#normalBuffer()?.ybase ?? null;
119
131
  }
120
132
 
133
+ historyRowCap(): number {
134
+ return this.#historyRowCap;
135
+ }
136
+
137
+ /**
138
+ * #873: hold at most #historyRowCap history rows. The oldest rows past it
139
+ * are dropped here and counted as left out, so tmux's history size is still
140
+ * the rows held plus the rows left out. tmux itself keeps them.
141
+ */
142
+ #enforceRowCap(): void {
143
+ const buffer = this.#normalBuffer();
144
+ if (!buffer || buffer.ybase <= this.#historyRowCap) return;
145
+ const extra = buffer.ybase - this.#historyRowCap;
146
+ buffer.lines.trimStart(extra);
147
+ buffer.ybase -= extra;
148
+ buffer.ydisp = Math.max(0, buffer.ydisp - extra);
149
+ this.#setOmittedHistory(this.#omittedHistory + extra);
150
+ // No projection invalidation: the incremental projection reads a trim at
151
+ // the old end like tmux's own collection, so a scroll at the cap stays a
152
+ // one-row delta. Seeds and prepends invalidate on their own.
153
+ }
154
+
121
155
  #normalBuffer() {
122
156
  return (
123
157
  this.#terminal as unknown as {
@@ -126,7 +160,13 @@ export class XtermTerminalInterpreterBackend implements TerminalInterpreterBacke
126
160
  normal?: {
127
161
  ybase: number;
128
162
  ydisp: number;
129
- lines: { trimStart(count: number): void };
163
+ lines: {
164
+ length: number;
165
+ maxLength: number;
166
+ trimStart(count: number): void;
167
+ get(index: number): { isWrapped: boolean } | undefined;
168
+ splice(start: number, deleteCount: number, ...items: NativeImportLine[]): void;
169
+ };
130
170
  };
131
171
  };
132
172
  };
@@ -134,27 +174,52 @@ export class XtermTerminalInterpreterBackend implements TerminalInterpreterBacke
134
174
  )._core?.buffers?.normal;
135
175
  }
136
176
 
177
+ omittedHistory(): number {
178
+ return this.#omittedHistory;
179
+ }
180
+
181
+ /**
182
+ * The parser's own erase-in-display collection counts only the rows held.
183
+ * While tmux holds older rows than these, turn it off: #collectHistory then
184
+ * collects after each of the erase's scrolls instead, which leaves the same
185
+ * rows as tmux's collection before it.
186
+ */
187
+ #setOmittedHistory(count: number): void {
188
+ this.#omittedHistory = count;
189
+ this.#terminal.options.tmuxHistoryLimit =
190
+ count > 0 ? Number.MAX_SAFE_INTEGER : this.#historyLimit;
191
+ }
192
+
137
193
  #collectHistory(): void {
138
194
  const buffer = this.#normalBuffer();
139
195
  if (!buffer) return;
140
196
  const before = this.#lastYbase;
141
197
  const limit = this.#historyLimit;
198
+ const omitted = this.#omittedHistory;
142
199
  // Only a plain one-row scroll from at or above the limit is collected
143
200
  // here. ED2 collects before its own scrolls (one-column.patch), and any
144
201
  // other change (reset, resize, a capped ring) is left alone: a history
145
202
  // that still differs from tmux is caught by the owner's size check.
203
+ // tmux's history size counts the rows a native seed left out, and its
204
+ // collection drops the oldest rows: those first, then rows held.
146
205
  if (
147
206
  this.#collecting &&
148
207
  limit > 0 &&
149
208
  before !== null &&
150
- before >= limit &&
209
+ omitted + before >= limit &&
151
210
  buffer.ybase === before + 1
152
211
  ) {
153
- const trim = Math.min(buffer.ybase, Math.max(1, Math.floor(limit / 10)));
154
- buffer.lines.trimStart(trim);
155
- buffer.ybase -= trim;
156
- buffer.ydisp = Math.max(0, buffer.ydisp - trim);
212
+ const collected = Math.min(omitted + buffer.ybase, Math.max(1, Math.floor(limit / 10)));
213
+ const fromOmitted = Math.min(omitted, collected);
214
+ if (fromOmitted > 0) this.#setOmittedHistory(omitted - fromOmitted);
215
+ const trim = collected - fromOmitted;
216
+ if (trim > 0) {
217
+ buffer.lines.trimStart(trim);
218
+ buffer.ybase -= trim;
219
+ buffer.ydisp = Math.max(0, buffer.ydisp - trim);
220
+ }
157
221
  }
222
+ if (this.#collecting) this.#enforceRowCap();
158
223
  this.#lastYbase = buffer.ybase;
159
224
  }
160
225
 
@@ -233,6 +298,8 @@ export class XtermTerminalInterpreterBackend implements TerminalInterpreterBacke
233
298
  const cell = this.#terminal.buffer.active.getNullCell() as unknown as NativeImportCell;
234
299
  if (typeof cell.setFromCharData !== "function")
235
300
  throw new Error("Unsupported @tmux-ide/xterm-headless 6 native cell shape");
301
+ const omitted = snapshot.omittedHistory ?? 0;
302
+ if (!Number.isSafeInteger(omitted) || omitted < 0) return false;
236
303
  if (buffer.lines.maxLength < snapshot.grid.length) return false;
237
304
  buffer.lines.length = 0;
238
305
  for (let index = 0; index < snapshot.grid.length; index++) {
@@ -280,10 +347,66 @@ export class XtermTerminalInterpreterBackend implements TerminalInterpreterBacke
280
347
  1,
281
348
  )!.cells[0]!;
282
349
  [handler._curAttrData.fg, handler._curAttrData.bg] = nativeImportAttributes(current);
350
+ this.#setOmittedHistory(omitted);
283
351
  this.#historyProjectionInvalidated = true;
284
352
  return true;
285
353
  }
286
354
 
355
+ prependNativeHistory(piece: NativeHistoryPiece): boolean {
356
+ const omitted = this.#omittedHistory;
357
+ const buffer = this.#normalBuffer();
358
+ if (
359
+ !buffer ||
360
+ omitted <= 0 ||
361
+ this.#terminal.buffer.active.type !== "normal" ||
362
+ piece.cols !== this.cols ||
363
+ piece.historySize !== omitted + buffer.ybase ||
364
+ !Number.isSafeInteger(piece.firstRow) ||
365
+ piece.firstRow < 0 ||
366
+ piece.firstRow >= omitted ||
367
+ piece.firstRow + piece.rows.length < omitted ||
368
+ !this.canImportNativeGrid()
369
+ )
370
+ return false;
371
+ // Rows numbered below the oldest row held; a piece can overlap rows held.
372
+ const count = omitted - piece.firstRow;
373
+ if (buffer.lines.length + count > buffer.lines.maxLength) return false;
374
+ const lines = piece.rows
375
+ .slice(0, count)
376
+ .map((row, index) =>
377
+ this.#nativeLine(row, index > 0 && (piece.rows[index - 1]!.flags & 1) !== 0),
378
+ );
379
+ // In slices: one call with every row as an argument can exceed the stack.
380
+ for (let offset = 0; offset < lines.length; offset += 4096)
381
+ buffer.lines.splice(offset, 0, ...lines.slice(offset, offset + 4096));
382
+ // The import marked the row that was oldest as unwrapped: it had no row before it.
383
+ const boundary = buffer.lines.get(count);
384
+ if (boundary) boundary.isWrapped = (piece.rows[count - 1]!.flags & 1) !== 0;
385
+ buffer.ybase += count;
386
+ buffer.ydisp += count;
387
+ if (this.#lastYbase !== null) this.#lastYbase += count;
388
+ this.#setOmittedHistory(piece.firstRow);
389
+ this.#enforceRowCap();
390
+ this.#historyProjectionInvalidated = true;
391
+ return true;
392
+ }
393
+
394
+ /** One native row as a parser line, as importNativeGrid writes it. */
395
+ #nativeLine(source: NativeGridCaptureRow, wrapped: boolean): NativeImportLine {
396
+ const buffer = (this.#terminal.buffer.active as unknown as { _buffer: NativeImportBuffer })
397
+ ._buffer;
398
+ const cell = this.#terminal.buffer.active.getNullCell() as unknown as NativeImportCell;
399
+ const row = projectNativeGridRow(source, this.cols, 0, wrapped)!;
400
+ const line = buffer.getBlankLine(undefined, row.wrapped);
401
+ for (let column = 0; column < row.cells.length; column++) {
402
+ const projected = row.cells[column]!;
403
+ cell.setFromCharData([0, projected.grapheme, projected.width, 0]);
404
+ [cell.fg, cell.bg] = nativeImportAttributes(projected);
405
+ line.setCell(column, cell);
406
+ }
407
+ return line;
408
+ }
409
+
287
410
  prioritizeNextWrite(): void {
288
411
  this.#terminal.prioritizeNextWrite();
289
412
  }
@@ -1,4 +1,9 @@
1
- import { STOCK_CAPTURE_TAB_UNAVAILABLE } from "@tmux-ide/contracts";
1
+ import {
2
+ PANE_STREAM_MAX_PANES,
3
+ STOCK_CAPTURE_TAB_UNAVAILABLE,
4
+ TERMINAL_DELIVERY_MAX_PIPELINED,
5
+ TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION,
6
+ } from "@tmux-ide/contracts";
2
7
  import { randomUUID } from "node:crypto";
3
8
  import type {
4
9
  WindowLinkTopology,
@@ -329,6 +334,22 @@ function layoutExactlyCoversPanes(
329
334
  );
330
335
  }
331
336
 
337
+ /**
338
+ * A session with more panes than one pane stream carries (#585). The daemon
339
+ * refuses such a stream on every try, so the runtime supervisor does not try
340
+ * again until the session's panes change (`code` is what it checks).
341
+ */
342
+ export class OpenTuiPaneLimitError extends Error {
343
+ readonly code = "pane-limit-exceeded";
344
+ constructor(
345
+ readonly panes: number,
346
+ readonly limit: number,
347
+ ) {
348
+ super(`Session has ${panes} panes; one pane stream carries at most ${limit}`);
349
+ this.name = "OpenTuiPaneLimitError";
350
+ }
351
+ }
352
+
332
353
  function canonicalPaneIds(inventory: WorkspaceClientRuntimeInventory): readonly string[] {
333
354
  const panes = [...new Set(inventory.semanticPaneIds)].sort((left, right) =>
334
355
  left.localeCompare(right),
@@ -413,6 +434,13 @@ class WireTerminalEndpoint {
413
434
  #pending: PendingDelivery | null = null;
414
435
  #rejectedTransactionId: string | null = null;
415
436
  #decodeToken: object | null = null;
437
+ /**
438
+ * Capability 124: patches the daemon pipelined behind the delivery that is
439
+ * still decoding or unsettled, each with its chunks, in arrival order. Each
440
+ * names the one before as its base; they are admitted once that one is ACKed.
441
+ */
442
+ #queued: TerminalDeliveryServerMessage[] = [];
443
+ #draining = false;
416
444
  #closed = false;
417
445
  readonly #ready: Promise<boolean>;
418
446
  #resolveReady!: (ready: boolean) => void;
@@ -505,6 +533,7 @@ class WireTerminalEndpoint {
505
533
  return;
506
534
  }
507
535
  if (message.type === "terminal.delivery.fault") {
536
+ this.#queued.length = 0;
508
537
  if (message.deliveryNonce !== this.#negotiated.deliveryNonce) {
509
538
  this.#failConnection(new Error("Terminal fault nonce does not match negotiation"));
510
539
  return;
@@ -532,6 +561,15 @@ class WireTerminalEndpoint {
532
561
  return;
533
562
  }
534
563
  if (this.#unavailable) return;
564
+ if ((this.#queued.length > 0 || this.#busy()) && this.#mayQueue(message)) {
565
+ this.#queued.push(message);
566
+ return;
567
+ }
568
+ return this.#acceptNow(message);
569
+ }
570
+
571
+ #acceptNow(message: TerminalDeliveryServerMessage): void | { readonly consumedOwnedChunk: true } {
572
+ if (message.type === "terminal.delivery.fault") return;
535
573
  if (message.type === "terminal.projection") {
536
574
  this.#failConnection(new Error("Unsolicited alternate-screen projection"));
537
575
  return;
@@ -543,9 +581,62 @@ class WireTerminalEndpoint {
543
581
  return this.#acceptChunk(message);
544
582
  }
545
583
 
584
+ /** A flight is decoding or waiting for its subscriber: it has not been ACKed. */
585
+ #busy(): boolean {
586
+ return this.#decodeToken !== null || this.#pending !== null;
587
+ }
588
+
589
+ /**
590
+ * Capability 124: only a patch based on the newest flight (decoding,
591
+ * unsettled or queued), within TERMINAL_DELIVERY_MAX_PIPELINED, and the
592
+ * chunks of the newest queued patch. Anything else overlapping a flight is
593
+ * still a protocol violation and takes the ordinary path.
594
+ */
595
+ #mayQueue(message: TerminalDeliveryServerMessage): boolean {
596
+ let newest: TerminalDeliveryEnvelope | null = this.#pending?.envelope ?? this.#envelope;
597
+ let envelopes = 1;
598
+ let chunks = 0;
599
+ for (const queued of this.#queued)
600
+ if (queued.type === "terminal.delivery") {
601
+ newest = queued;
602
+ envelopes += 1;
603
+ chunks = 0;
604
+ } else if (queued.type === "terminal.delivery.chunk") chunks += 1;
605
+ if (!newest) return false;
606
+ if (message.type === "terminal.delivery.chunk")
607
+ return (
608
+ envelopes > 1 &&
609
+ message.transactionId === newest.transactionId &&
610
+ chunks < newest.chunkCount
611
+ );
612
+ return (
613
+ message.type === "terminal.delivery" &&
614
+ message.frame === "patch" &&
615
+ message.baseRevision === newest.canonicalRevision &&
616
+ message.incarnation === newest.incarnation &&
617
+ envelopes < TERMINAL_DELIVERY_MAX_PIPELINED &&
618
+ (envelopes === 1 || chunks === newest.chunkCount)
619
+ );
620
+ }
621
+
622
+ /** Admit queued deliveries in order until one is decoding or unsettled again. */
623
+ #drain(): void {
624
+ if (this.#draining) return;
625
+ this.#draining = true;
626
+ try {
627
+ while (this.#queued.length > 0 && !this.#busy() && !this.#closed) {
628
+ const message = this.#queued.shift()!;
629
+ this.#acceptNow(message);
630
+ }
631
+ } finally {
632
+ this.#draining = false;
633
+ }
634
+ }
635
+
546
636
  close(): void {
547
637
  if (this.#closed) return;
548
638
  this.#closed = true;
639
+ this.#queued.length = 0;
549
640
  this.#assembler = null;
550
641
  this.#assemblyStorage = null;
551
642
  this.#envelope = null;
@@ -847,7 +938,9 @@ class WireTerminalEndpoint {
847
938
  });
848
939
  } catch (error) {
849
940
  this.#failConnection(error instanceof Error ? error : new Error(String(error)));
941
+ return;
850
942
  }
943
+ this.#drain();
851
944
  }
852
945
 
853
946
  #reject(
@@ -882,6 +975,9 @@ class WireTerminalEndpoint {
882
975
  this.#decodeToken = null;
883
976
  this.#rejectedTransactionId = attempted?.transactionId ?? transactionId;
884
977
  this.#reseedRequired = true;
978
+ // Patches queued behind the rejected flight are NACKed in turn ("gap");
979
+ // the daemon dropped them with the first NACK.
980
+ this.#drain();
885
981
  }
886
982
  }
887
983
 
@@ -980,6 +1076,8 @@ export async function connectOpenTuiWorkspaceRuntimePort(
980
1076
  ): Promise<OpenTuiWorkspaceRuntimePort> {
981
1077
  const { inventory, routing } = options;
982
1078
  const panes = canonicalPaneIds(inventory);
1079
+ if (panes.length > PANE_STREAM_MAX_PANES)
1080
+ throw new OpenTuiPaneLimitError(panes.length, PANE_STREAM_MAX_PANES);
983
1081
  const expected: OpenTuiVerifiedRoutingIdentity = {
984
1082
  daemonInstanceId: inventory.daemonGeneration,
985
1083
  workspaceName: inventory.workspaceName,
@@ -1227,7 +1325,8 @@ export async function connectOpenTuiWorkspaceRuntimePort(
1227
1325
  panes: [...panes],
1228
1326
  viewerMode: "interactive",
1229
1327
  terminalDelivery: {
1230
- protocolVersions: [1],
1328
+ // 124: this endpoint holds patches pipelined behind a decoding one.
1329
+ protocolVersions: [1, TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION],
1231
1330
  encodings: ["semantic-compact-v1", "semantic-v1"],
1232
1331
  richPlacements: true,
1233
1332
  },
@@ -29,6 +29,7 @@ import { canonicalDaemonUrl } from "../../../lib/canonical-daemon.ts";
29
29
  import { ensureOpenTuiSessionWorkspaceResult } from "../configless-session-bootstrap.ts";
30
30
  import {
31
31
  OPEN_TUI_HOST_CLIENT_ID,
32
+ OpenTuiPaneLimitError,
32
33
  connectOpenTuiWorkspaceRuntimePort,
33
34
  type ConnectOpenTuiWorkspaceRuntimePortOptions,
34
35
  type OpenTuiWorkspaceRuntimePort,
@@ -131,6 +132,8 @@ interface BundleCallbacks {
131
132
  readonly didSuspendRuntime: (runtime: OpenTuiWorkspaceRuntimePort) => void;
132
133
  readonly didRetireRuntime: () => void;
133
134
  readonly didFaultRuntime: (runtime: OpenTuiWorkspaceRuntimePort | null, error: Error) => void;
135
+ /** Refused for good until the session's panes change (#585). */
136
+ readonly didRefuseRuntime: (error: unknown) => void;
134
137
  readonly didRuntimeDiagnostic: (
135
138
  phase: Parameters<NonNullable<ConnectOpenTuiWorkspaceRuntimePortOptions["onDiagnostic"]>>[0],
136
139
  details: Readonly<Record<string, unknown>>,
@@ -157,6 +160,7 @@ export interface OpenTuiGenerationHostDependencies {
157
160
  | "shell-lifecycle"
158
161
  | "runtime-progress"
159
162
  | "runtime-fault"
163
+ | "runtime-refused"
160
164
  | "workspace-client-state"
161
165
  | "host-internal-snapshot-publication",
162
166
  details: Readonly<Record<string, unknown>>,
@@ -313,6 +317,7 @@ function buildProductionBundle(
313
317
  callbacks.didSuspendRuntime(runtime as OpenTuiWorkspaceRuntimePort);
314
318
  },
315
319
  didRetireRuntime: callbacks.didRetireRuntime,
320
+ didFailRuntime: callbacks.didRefuseRuntime,
316
321
  requestTerminalRuntimeInventoryRefresh: () => {
317
322
  connection.transport.refreshTerminalRuntimeInventory();
318
323
  },
@@ -740,6 +745,14 @@ export function createOpenTuiGenerationHost(
740
745
  currentOwner.runtime = null;
741
746
  publish({ ...snapshot, status: "rebinding" });
742
747
  },
748
+ didRefuseRuntime(error) {
749
+ const details =
750
+ error instanceof OpenTuiPaneLimitError
751
+ ? { code: error.code, panes: error.panes, limit: error.limit }
752
+ : { message: error instanceof Error ? error.message : String(error) };
753
+ overrides.onConnectionProgress?.("runtime-refused", details);
754
+ diagnose?.("runtime-refused", details);
755
+ },
743
756
  didRuntimeDiagnostic(phase, details) {
744
757
  if (phase === "seed" || phase === "coherent")
745
758
  overrides.onConnectionProgress?.("runtime-progress", {
@@ -139,6 +139,9 @@ export interface SemanticThemeSnapshot extends SemanticThemeTokens {
139
139
  export interface ThemeConfigInput {
140
140
  mode?: ThemeModeSetting;
141
141
  preset?: string;
142
+ /** System mode's preset when the host is light, and when it is dark. */
143
+ light?: string;
144
+ dark?: string;
142
145
  userTheme?: unknown;
143
146
  projectTheme?: unknown;
144
147
  accessibility?: Partial<ThemeAccessibilityPreferences>;
@@ -900,10 +903,19 @@ export function createSemanticThemeSnapshot(
900
903
  config?.accessibility?.increasedContrast ?? DEFAULT_ACCESSIBILITY.increasedContrast,
901
904
  };
902
905
  const mode = resolvedMode(setting, rendererMode, hostDefaults);
906
+ // System mode with a chosen preset for each side (the Mac app's Match
907
+ // macOS writes theme.light / theme.dark): the side the host is on.
908
+ const side =
909
+ setting === "system"
910
+ ? findVisualThemePreset(mode === "light" ? config?.light : config?.dark)
911
+ : undefined;
903
912
  const resolved = resolveVisualTheme({
904
913
  appearance: mode,
905
914
  hostDefaults: setting === "system" ? (hostDefaults ?? undefined) : undefined,
906
- userTheme: config?.userTheme ?? findVisualThemePreset(config?.preset),
915
+ userTheme:
916
+ config?.userTheme ??
917
+ findVisualThemePreset(config?.preset) ??
918
+ (side?.appearance === mode ? side : undefined),
907
919
  projectTheme: config?.projectTheme,
908
920
  accessibility,
909
921
  });
@@ -186,7 +186,19 @@ export function createApplicationConnectionFeedback(
186
186
  } else if (phase === "connection-start") update("Connecting to daemon");
187
187
  else if (phase === "connection-resolved") update("Reading terminal layout");
188
188
  else if (phase === "runtime-fault") update("Connection interrupted — retrying");
189
- else if (phase === "runtime-progress") {
189
+ else if (
190
+ phase === "runtime-refused" &&
191
+ Number.isSafeInteger(details.panes) &&
192
+ Number.isSafeInteger(details.limit)
193
+ ) {
194
+ // #585: refused on every try, so the app stops here instead of retrying.
195
+ // Words approved by the owner on 25 Nov 2026.
196
+ stop();
197
+ update(
198
+ `Session too large to stream here: ${String(details.panes)} panes, the limit is ${String(details.limit)}. Move some windows to another session, or open it in the Mac app.`,
199
+ true,
200
+ );
201
+ } else if (phase === "runtime-progress") {
190
202
  if (
191
203
  details.runtimePhase === "seed" &&
192
204
  Number.isSafeInteger(details.seededPanes) &&
@@ -849,7 +849,9 @@ export function createDirectLoopbackDaemonTransport(
849
849
  socket.removeEventListener?.("open", onOpen);
850
850
  socket.removeEventListener?.("message", onMessage);
851
851
  socket.removeEventListener?.("close", onClose);
852
- socket.removeEventListener?.("error", onError);
852
+ // Keep onError (inert once closed): a `ws` socket emits 'error'
853
+ // when the peer sends a bad frame after this close, and an
854
+ // 'error' with no listener is an uncaught exception (#868).
853
855
  handlers.onPeerMismatch(reason);
854
856
  socket.close(clientInitiatedWebSocketCloseCode(1008), "Daemon identity mismatch");
855
857
  return;
@@ -990,7 +992,9 @@ export function createDirectLoopbackDaemonTransport(
990
992
  socket.removeEventListener?.("open", onOpen);
991
993
  socket.removeEventListener?.("message", onMessage);
992
994
  socket.removeEventListener?.("close", onClose);
993
- socket.removeEventListener?.("error", onError);
995
+ // Keep onError (inert once closed): closing a `ws` socket that is
996
+ // still connecting emits 'error', and an 'error' with no listener
997
+ // is an uncaught exception in the host process (#868).
994
998
  socket.close(1000, "Desktop resource store disposed");
995
999
  },
996
1000
  };
@@ -477,7 +477,9 @@ export async function connectIssuedPaneStreamRuntimeClient(
477
477
  socket.binaryType = "arraybuffer";
478
478
  options.onConnectionDiagnostic?.("socket-created", { requestId: descriptor.requestId });
479
479
  const releaseSocketResource = acquireRuntimeResource("pane-stream-socket");
480
- const releaseSocketListenerResources = acquireRuntimeResource("socket-listener", 4);
480
+ const releaseSocketListenerResources = acquireRuntimeResource("socket-listener", 3);
481
+ const releaseErrorListenerResource = acquireRuntimeResource("socket-listener");
482
+ let releaseCloseWatchResource: (() => void) | null = null;
481
483
  let pendingDiagnosticTurns: Set<() => void> | null = null;
482
484
  const cancelDiagnosticTurns = (): void => {
483
485
  if (!pendingDiagnosticTurns) return;
@@ -530,14 +532,28 @@ export async function connectIssuedPaneStreamRuntimeClient(
530
532
  abortListenerAttached = false;
531
533
  options.signal?.removeEventListener("abort", onAbort);
532
534
  };
533
- const detachSocketListeners = (): void => {
535
+ const dropErrorListener = (): void => {
536
+ socket.removeEventListener?.("error", onError);
537
+ socket.removeEventListener?.("close", dropErrorListener);
538
+ releaseErrorListenerResource();
539
+ releaseCloseWatchResource?.();
540
+ };
541
+ // The 'error' listener (inert once `closed`) stays until the socket reports
542
+ // 'close'. A `ws` socket closed while still connecting emits 'error' after
543
+ // close(), and an 'error' with no listener is an uncaught exception (#868).
544
+ const detachSocketListeners = (socketClosed = false): void => {
534
545
  if (!listenersAttached) return;
535
546
  listenersAttached = false;
536
547
  socket.removeEventListener?.("open", onOpen);
537
548
  socket.removeEventListener?.("message", onMessage);
538
549
  socket.removeEventListener?.("close", onClose);
539
- socket.removeEventListener?.("error", onClose);
540
550
  releaseSocketListenerResources();
551
+ if (socketClosed) {
552
+ dropErrorListener();
553
+ return;
554
+ }
555
+ releaseCloseWatchResource = acquireRuntimeResource("socket-listener");
556
+ socket.addEventListener("close", dropErrorListener);
541
557
  };
542
558
  const closeSocketOnce = (code: number, reason: string): void => {
543
559
  if (socketCloseRequested) return;
@@ -1624,13 +1640,13 @@ export async function connectIssuedPaneStreamRuntimeClient(
1624
1640
  }
1625
1641
  routeFrame(options, frame, fail);
1626
1642
  };
1627
- const onClose: SocketListener = (event) => {
1643
+ const settleClosed = (event: Parameters<SocketListener>[0], socketClosed: boolean): void => {
1628
1644
  if (closed) return;
1629
1645
  closed = true;
1630
1646
  clearReadyTimer();
1631
1647
  cancelDiagnosticTurns();
1632
1648
  detachAbortListener();
1633
- detachSocketListeners();
1649
+ detachSocketListeners(socketClosed);
1634
1650
  releaseSocketResource();
1635
1651
  const reason =
1636
1652
  typeof event.reason === "string"
@@ -1646,6 +1662,8 @@ export async function connectIssuedPaneStreamRuntimeClient(
1646
1662
  rejectReady(error);
1647
1663
  options.onFault?.(error);
1648
1664
  };
1665
+ const onClose: SocketListener = (event) => settleClosed(event, true);
1666
+ const onError: SocketListener = (event) => settleClosed(event, false);
1649
1667
  const onAbort = (): void => {
1650
1668
  const reason = options.signal?.reason;
1651
1669
  fail(reason instanceof Error ? reason : new Error("Pane-stream runtime connection aborted"));
@@ -1653,7 +1671,7 @@ export async function connectIssuedPaneStreamRuntimeClient(
1653
1671
  socket.addEventListener("open", onOpen);
1654
1672
  socket.addEventListener("message", onMessage);
1655
1673
  socket.addEventListener("close", onClose);
1656
- socket.addEventListener("error", onClose);
1674
+ socket.addEventListener("error", onError);
1657
1675
  listenersAttached = true;
1658
1676
  if (options.signal) {
1659
1677
  abortListenerAttached = true;
@@ -216,6 +216,12 @@ export interface WorkspaceClientPorts<
216
216
  ) => void;
217
217
  /** Called only when no active runtime remains (empty inventory/target retirement). */
218
218
  readonly didRetireRuntime?: () => void;
219
+ /**
220
+ * The desired runtime was refused in a way another try cannot change (a
221
+ * session over the stream's pane limit, code `pane-limit-exceeded`). No
222
+ * further try is made until the inventory changes.
223
+ */
224
+ readonly didFailRuntime?: (error: unknown) => void;
219
225
  /** Presentation inventory disagreed with the newer terminal authority. */
220
226
  readonly requestTerminalRuntimeInventoryRefresh?: () => void;
221
227
  readonly actions: WorkspaceClientOwnerActionPort;
@@ -123,6 +123,15 @@ interface RuntimeOwner<Snapshot, Patch, Tombstone> {
123
123
  preparationError: Error | null;
124
124
  }
125
125
 
126
+ function runtimeErrorCode(error: unknown): string | null {
127
+ return typeof error === "object" &&
128
+ error !== null &&
129
+ "code" in error &&
130
+ typeof error.code === "string"
131
+ ? error.code
132
+ : null;
133
+ }
134
+
126
135
  function phaseOf<Shell extends ApplicationShellProjectionInputV1>(
127
136
  state: ApplicationShellSessionState<Shell>,
128
137
  ): WorkspaceClientPhase {
@@ -909,7 +918,10 @@ export function createWorkspaceClient<
909
918
  WorkspaceClientRuntimePort<TerminalSnapshot, TerminalPatch, TerminalTombstone>
910
919
  >({
911
920
  wait: (delayMs, signal) => waitWithClock(clock, delayMs, signal),
912
- retryable: () =>
921
+ // A session over the stream's pane limit is refused the same way on
922
+ // every try; trying again only kept the terminal on "connecting" (#585).
923
+ retryable: (error) =>
924
+ runtimeErrorCode(error) !== "pane-limit-exceeded" &&
913
925
  !disposed &&
914
926
  generation === expectedGeneration &&
915
927
  target === expectedTarget &&
@@ -936,15 +948,8 @@ export function createWorkspaceClient<
936
948
  prepare,
937
949
  );
938
950
  } catch (error) {
939
- const code =
940
- typeof error === "object" &&
941
- error !== null &&
942
- "code" in error &&
943
- typeof error.code === "string"
944
- ? error.code
945
- : null;
946
951
  if (
947
- code === "topology-changed" &&
952
+ runtimeErrorCode(error) === "topology-changed" &&
948
953
  !disposed &&
949
954
  generation === expectedGeneration &&
950
955
  target === expectedTarget &&
@@ -993,6 +998,7 @@ export function createWorkspaceClient<
993
998
  ) {
994
999
  return;
995
1000
  }
1001
+ if (state.phase === "failed") options.ports.didFailRuntime?.(state.error);
996
1002
  if (state.phase !== "live" || state.value === null) {
997
1003
  if (activeRuntimeOwner === owner && runtime !== null) {
998
1004
  const suspendedRuntime = runtime;
@@ -769,7 +769,9 @@ export function createWorkspaceEventSupervisor(
769
769
  socket.removeEventListener?.("open", onOpen);
770
770
  socket.removeEventListener?.("message", onMessage);
771
771
  socket.removeEventListener?.("close", onClose);
772
- socket.removeEventListener?.("error", onError);
772
+ // Keep onError (inert once disposed): closing a socket that is still
773
+ // connecting emits 'error', and an EventEmitter socket with no 'error'
774
+ // listener turns that into an uncaught exception in its host process.
773
775
  for (const waiter of ackWaiters.values()) {
774
776
  waiter.reject(new Error("workspace event supervisor disposed"));
775
777
  }