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
@@ -1,4 +1,4 @@
1
- import { browserIcon } from "./browser-icon.js";
1
+ import { browserIcon, processAlive } from "./browser-icon.js";
2
2
  import { readerOption } from "./reader-option.js";
3
3
  /**
4
4
  * `qa` asks tmux to escape each value as a command argument. In particular,
@@ -33,6 +33,8 @@ export const SESSION_PANE_DESCRIPTOR_FORMAT = [
33
33
  "#{qa:@tmux_ide_reader}",
34
34
  // The reader option belongs to the pane only when its own process set it.
35
35
  "#{pane_pid}",
36
+ // Set only by a terminal browser that has tmux-ide's native controls (#718).
37
+ "#{qa:@tmux_ide_browser_control}",
36
38
  ].join("\t");
37
39
  /**
38
40
  * Descriptor fields the program in a pane changes whenever it likes: its
@@ -129,9 +131,9 @@ export function parseSessionPaneDescriptorReply(lines) {
129
131
  continue;
130
132
  }
131
133
  const encoded = utf8Line.split("\t");
132
- if (encoded.length < 21 || encoded.length > 25)
134
+ if (encoded.length < 21 || encoded.length > 26)
133
135
  continue;
134
- const [runtimePaneId = "", semanticPaneId = "", role = "", type = "", currentCommand = "", cwd = "", windowIndexRaw = "", windowName = "", windowId = "", title = "", runtimeSessionId = "", paneIndexRaw = "", name = "", missionStamp = "", paneActiveRaw = "", windowActiveRaw = "", semanticWindowId = "", sessionName = "", windowPaneCountRaw = "", sessionWindowCountRaw = "", nativePaneBirthId = "", nameSource = "", browserIconRaw = "", readerRaw = "", panePidRaw = "",] = encoded.map(decodeTmuxArgument);
136
+ const [runtimePaneId = "", semanticPaneId = "", role = "", type = "", currentCommand = "", cwd = "", windowIndexRaw = "", windowName = "", windowId = "", title = "", runtimeSessionId = "", paneIndexRaw = "", name = "", missionStamp = "", paneActiveRaw = "", windowActiveRaw = "", semanticWindowId = "", sessionName = "", windowPaneCountRaw = "", sessionWindowCountRaw = "", nativePaneBirthId = "", nameSource = "", browserIconRaw = "", readerRaw = "", panePidRaw = "", browserControl = "",] = encoded.map(decodeTmuxArgument);
135
137
  if (!/^%(?:0|[1-9][0-9]*)$/u.test(runtimePaneId) || runtimePaneId.length > 32)
136
138
  continue;
137
139
  if (!/^\$(?:0|[1-9][0-9]*)$/u.test(runtimeSessionId) || runtimeSessionId.length > 32)
@@ -169,6 +171,7 @@ export function parseSessionPaneDescriptorReply(lines) {
169
171
  }
170
172
  descriptors.push({
171
173
  browserIcon: browserIcon(browserIconRaw),
174
+ browserKind: terminalBrowserKind(browserControl, currentCommand),
172
175
  reader: readerOption(readerRaw, panePidRaw),
173
176
  sessionName,
174
177
  runtimePaneId,
@@ -325,3 +328,23 @@ export function decodeControlReplyUtf8(value) {
325
328
  function positiveInteger(value, fallback) {
326
329
  return Number.isSafeInteger(value) && value > 0 ? value : fallback;
327
330
  }
331
+ /**
332
+ * #718: a pane runs a terminal browser with tmux-ide's native controls while
333
+ * the browser that published @tmux_ide_browser_control is alive: the browser
334
+ * never clears the option, so a pane that outlives it (remain-on-exit,
335
+ * respawn-pane) is judged by what runs there now. A plain terminal browser
336
+ * is known by its process name (tmux cuts it to 15 characters on macOS).
337
+ */
338
+ export function terminalBrowserKind(control, currentCommand, alive = processAlive) {
339
+ if (control.length > 0 && control.length <= 4096) {
340
+ try {
341
+ const pid = JSON.parse(control)?.pid;
342
+ if (typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && alive(pid))
343
+ return "native";
344
+ }
345
+ catch {
346
+ // Not an endpoint: judged by the process name below.
347
+ }
348
+ }
349
+ return /^terminal-browser?$/u.test(currentCommand) ? "plain" : null;
350
+ }
@@ -1694,6 +1694,7 @@ class SessionRuntimeConsumerImpl {
1694
1694
  ack: (ack) => upstream.ack(ack),
1695
1695
  ...(upstream.projectionReceipt ? { projectionReceipt: upstream.projectionReceipt } : {}),
1696
1696
  ...(upstream.materialize ? { materialize: upstream.materialize } : {}),
1697
+ ...(upstream.prioritize ? { prioritize: upstream.prioritize } : {}),
1697
1698
  nack: (nack) => upstream.nack(nack),
1698
1699
  setVisibility: (visibility) => upstream.setVisibility(visibility),
1699
1700
  close: async () => {
@@ -19,6 +19,21 @@ const MAX_PANES = 32;
19
19
  const MAX_PENDING_CANONICAL_CELLS = 1_000_000;
20
20
  const MAX_CONNECTIONS = MAX_CLIENTS * MAX_PANES;
21
21
  const BACKGROUND_CADENCE_MS = 100;
22
+ /**
23
+ * One connection's unacknowledged delivery bytes, across its panes, before a
24
+ * pane other than the one it types into waits. A remote link (SSH) queues
25
+ * every sent byte ahead of the next input-ack and echo; this bounds that queue
26
+ * to about this much plus one delivery. Daemon policy only: nothing on the wire.
27
+ */
28
+ export const TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES = 256 * 1024;
29
+ /** No pane is held longer than this: it is then sent behind whatever is in flight. */
30
+ export const TERMINAL_DELIVERY_CONNECTION_HOLD_MS = 250;
31
+ /**
32
+ * A pane is held only once some delivery of its connection has gone this long
33
+ * unacknowledged: a fast link acks bulk within a few round trips, and holding
34
+ * there only bunches panes up behind each other.
35
+ */
36
+ export const TERMINAL_DELIVERY_CONNECTION_CONGESTED_MS = 30;
22
37
  class DeferredProjectionEncoding extends Error {
23
38
  payload;
24
39
  constructor(payload) {
@@ -76,6 +91,8 @@ export class SessionRuntimeTerminalDeliveryHub {
76
91
  #observability;
77
92
  #panes = new Map();
78
93
  #clients = new Map();
94
+ /** Per connection: the pane it last typed into. */
95
+ #priority = new Map();
79
96
  #sourceCloseFailures = 0;
80
97
  #pendingSourceCloses = 0;
81
98
  /** Synchronous reservations held while an async pane source is starting. */
@@ -93,10 +110,14 @@ export class SessionRuntimeTerminalDeliveryHub {
93
110
  #deliveryLifecycleOrdinal = 0;
94
111
  #deliveryStatusOrdinal = 0;
95
112
  #closed = false;
113
+ #holdMs;
114
+ #congestedMs;
96
115
  constructor(generation, workspaceName, ownerForPane, options = {}) {
97
116
  this.generation = generation;
98
117
  this.workspaceName = workspaceName;
99
118
  this.#ownerForPane = ownerForPane;
119
+ this.#holdMs = options.connectionHoldMs ?? TERMINAL_DELIVERY_CONNECTION_HOLD_MS;
120
+ this.#congestedMs = options.connectionCongestedMs ?? TERMINAL_DELIVERY_CONNECTION_CONGESTED_MS;
100
121
  this.#scheduler = options.scheduler ?? SYSTEM_SESSION_RUNTIME_SCHEDULER;
101
122
  this.#observability = options.observability ?? DISABLED_SESSION_RUNTIME_OBSERVABILITY;
102
123
  }
@@ -165,6 +186,9 @@ export class SessionRuntimeTerminalDeliveryHub {
165
186
  lastAck: null,
166
187
  sourceClosedFlight: null,
167
188
  backgroundTimer: null,
189
+ budgetHeld: false,
190
+ budgetHeldSince: null,
191
+ budgetTimer: null,
168
192
  };
169
193
  this.#clients.set(key, client);
170
194
  client.lifecycleOpenRecorded = this.#recordDeliveryLifecycle(client, pane, "open");
@@ -177,6 +201,12 @@ export class SessionRuntimeTerminalDeliveryHub {
177
201
  projectionReceipt: (receipt) => this.#projectionReceipt(client, receipt),
178
202
  materialize: (request) => this.#materialize(client, request),
179
203
  nack: (nack) => this.#nack(client, nack),
204
+ prioritize: () => {
205
+ if (client.closed)
206
+ return;
207
+ this.#priority.set(client.clientId, client.paneId);
208
+ this.#releaseBudget(client.clientId);
209
+ },
180
210
  setVisibility: (visibilityInput) => {
181
211
  if (client.closed)
182
212
  return;
@@ -352,6 +382,7 @@ export class SessionRuntimeTerminalDeliveryHub {
352
382
  this.#cancelEncoding(client);
353
383
  client.outgoing.length = 0;
354
384
  client.inFlight = null;
385
+ client.budgetHeld = false;
355
386
  logDeliveryFault(client, "source-closed", "source-restarted");
356
387
  this.#enqueue(client, {
357
388
  type: "terminal.delivery.fault",
@@ -673,6 +704,32 @@ export class SessionRuntimeTerminalDeliveryHub {
673
704
  pane.rawFloorRevision = Math.max(pane.rawFloorRevision, first[0] + 1);
674
705
  }
675
706
  }
707
+ #overBudget(client) {
708
+ if (this.#priority.get(client.clientId) === client.paneId)
709
+ return false;
710
+ if (client.budgetHeldSince !== null &&
711
+ this.#scheduler.nowMs() - client.budgetHeldSince >= this.#holdMs)
712
+ return false;
713
+ const now = this.#scheduler.nowMs();
714
+ let bytes = 0;
715
+ let oldest = now;
716
+ for (const other of this.#clients.values())
717
+ if (other !== client && other.clientId === client.clientId && other.inFlight) {
718
+ bytes += other.inFlight.envelope.representationBytes;
719
+ oldest = Math.min(oldest, other.inFlight.sentAt);
720
+ }
721
+ return bytes >= TERMINAL_DELIVERY_CONNECTION_UNACKED_BYTES && now - oldest >= this.#congestedMs;
722
+ }
723
+ /** A pane's delivery settled or left: held panes of its connection try again, typed-into pane first. */
724
+ #releaseBudget(clientId) {
725
+ const held = [...this.#clients.values()].filter((other) => other.clientId === clientId && other.budgetHeld);
726
+ const priority = this.#priority.get(clientId);
727
+ held.sort((a, b) => Number(b.paneId === priority) - Number(a.paneId === priority));
728
+ for (const other of held) {
729
+ other.budgetHeld = false;
730
+ this.#schedule(other);
731
+ }
732
+ }
676
733
  #schedule(client) {
677
734
  if (client.closed ||
678
735
  client.captureUnavailable ||
@@ -715,6 +772,21 @@ export class SessionRuntimeTerminalDeliveryHub {
715
772
  client.visibility === "frozen" ||
716
773
  (!completed && target.update.revision !== client.latestRevision))
717
774
  return;
775
+ if (!completed && this.#overBudget(client)) {
776
+ client.budgetHeld = true;
777
+ client.budgetHeldSince ??= this.#scheduler.nowMs();
778
+ client.budgetTimer ??= this.#scheduler.timer(() => {
779
+ client.budgetTimer = null;
780
+ if (client.closed || !client.budgetHeld)
781
+ return;
782
+ client.budgetHeld = false;
783
+ this.#schedule(client);
784
+ }, this.#holdMs);
785
+ return;
786
+ }
787
+ client.budgetHeldSince = null;
788
+ client.budgetTimer?.cancel();
789
+ client.budgetTimer = null;
718
790
  const traceStarted = completed?.traceStarted ??
719
791
  (this.#observability.enabled ? this.#observability.nowMicros() : 0);
720
792
  let deferred = false;
@@ -1302,6 +1374,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1302
1374
  client.baselineHash = ack.canonicalStateHash;
1303
1375
  client.reseedRequired = false;
1304
1376
  client.inFlight = null;
1377
+ this.#releaseBudget(client.clientId);
1305
1378
  client.lastAck = ack;
1306
1379
  if (client.latestRevision === ack.canonicalRevision)
1307
1380
  client.latestRevision = null;
@@ -1376,6 +1449,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1376
1449
  client.lastProjectionReceipt = receipt;
1377
1450
  client.reseedRequired = false;
1378
1451
  client.inFlight = null;
1452
+ this.#releaseBudget(client.clientId);
1379
1453
  if (client.latestRevision === receipt.canonicalRevision)
1380
1454
  client.latestRevision = null;
1381
1455
  if (client.materializeRequested)
@@ -1440,6 +1514,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1440
1514
  this.#nacks += 1;
1441
1515
  client.reseedRequired = true;
1442
1516
  client.inFlight = null;
1517
+ this.#releaseBudget(client.clientId);
1443
1518
  this.#pruneCanonicalRevisions(client.paneId);
1444
1519
  this.#schedule(client);
1445
1520
  this.#recordDeliveryStatus(client, this.#panes.get(client.paneId));
@@ -1482,6 +1557,7 @@ export class SessionRuntimeTerminalDeliveryHub {
1482
1557
  if (reason === "source-closed")
1483
1558
  client.sourceClosedFlight = client.inFlight?.envelope ?? null;
1484
1559
  client.inFlight = null;
1560
+ this.#releaseBudget(client.clientId);
1485
1561
  const fault = {
1486
1562
  type: "terminal.delivery.fault",
1487
1563
  reason,
@@ -1557,8 +1633,14 @@ export class SessionRuntimeTerminalDeliveryHub {
1557
1633
  if (client.lifecycleOpenRecorded)
1558
1634
  this.#recordDeliveryLifecycle(client, this.#panes.get(client.paneId), "close");
1559
1635
  client.backgroundTimer?.cancel();
1636
+ client.budgetTimer?.cancel();
1637
+ client.budgetTimer = null;
1560
1638
  client.outgoing.length = 0;
1561
1639
  this.#clients.delete(client.key);
1640
+ if (![...this.#clients.values()].some((other) => other.clientId === client.clientId))
1641
+ this.#priority.delete(client.clientId);
1642
+ else
1643
+ this.#releaseBudget(client.clientId);
1562
1644
  this.#pruneCanonicalRevisions(client.paneId);
1563
1645
  if ([...this.#clients.values()].some((candidate) => candidate.paneId === client.paneId))
1564
1646
  return;
@@ -1937,11 +2019,12 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1937
2019
  // append-only history is proved here; trim/reflow and changed dimensions
1938
2020
  // retain the full seed boundary. Equality includes wrapped and all cells.
1939
2021
  const snapshot = target.state.snapshot;
2022
+ const trim = baseline ? historyTrim(baseline.history, snapshot.history) : 0;
1940
2023
  if (baseline &&
1941
2024
  baselineIncarnation === update.incarnation &&
1942
2025
  baseline.cols === snapshot.cols &&
1943
2026
  baseline.rows === snapshot.rows &&
1944
- baseline.history.length <= snapshot.history.length) {
2027
+ baseline.history.length - trim <= snapshot.history.length) {
1945
2028
  // Identity reuse is cheap, but detached equal histories must not turn a
1946
2029
  // cooperative seed into an unbounded synchronous cell comparison.
1947
2030
  let comparisonCells = 0;
@@ -1953,8 +2036,8 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1953
2036
  ? terminalReplicaRowsEqual(left, right)
1954
2037
  : null;
1955
2038
  };
1956
- for (let index = 0; index < baseline.history.length; index++)
1957
- if (equal(baseline.history[index], snapshot.history[index]) !== true)
2039
+ for (let index = trim; index < baseline.history.length; index++)
2040
+ if (equal(baseline.history[index], snapshot.history[index - trim]) !== true)
1958
2041
  return semanticSeed(target);
1959
2042
  const rows = [];
1960
2043
  for (let index = 0; index < snapshot.grid.length; index++) {
@@ -1964,19 +2047,20 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1964
2047
  if (!same)
1965
2048
  rows.push({ index, row: snapshot.grid[index] });
1966
2049
  }
1967
- const appendedRows = snapshot.history.length - baseline.history.length;
2050
+ const retained = baseline.history.length - trim;
2051
+ const appendedRows = snapshot.history.length - retained;
1968
2052
  // Compact patches serialize synchronously. Do not move a large appended
1969
2053
  // suffix or repaint across the seed-only cooperative encoding boundary.
1970
2054
  if ((rows.length + appendedRows) * snapshot.cols >= TERMINAL_COMPACT_COOPERATIVE_SEED_CELLS)
1971
2055
  return semanticSeed(target);
1972
- const append = snapshot.history.slice(baseline.history.length);
2056
+ const append = snapshot.history.slice(retained);
1973
2057
  return {
1974
2058
  frame: "patch",
1975
2059
  baseRevision: baselineRevision,
1976
2060
  revision: update.revision,
1977
2061
  patch: {
1978
2062
  rows,
1979
- ...(append.length ? { historyDelta: { trim: 0, append } } : {}),
2063
+ ...(append.length || trim ? { historyDelta: { trim, append } } : {}),
1980
2064
  cursor: snapshot.cursor,
1981
2065
  modes: snapshot.modes,
1982
2066
  placements: snapshot.placements,
@@ -1986,6 +2070,37 @@ function semanticPayload(baselineRevision, baseline, target, baselineIncarnation
1986
2070
  }
1987
2071
  return semanticSeed(target);
1988
2072
  }
2073
+ /**
2074
+ * How many of the baseline's oldest history rows the target dropped, proved by
2075
+ * row identity only: the replica keeps each surviving row object when tmux
2076
+ * trims at its history-limit. Zero when nothing was trimmed or no shift is
2077
+ * proved; the caller still checks every retained row exactly.
2078
+ */
2079
+ function historyTrim(baseline, target) {
2080
+ const first = target[0];
2081
+ if (first === undefined || baseline[0] === first)
2082
+ return 0;
2083
+ // A shared row object (a blank row) can recur; prove at most a few shifts.
2084
+ let candidates = 0;
2085
+ for (let trim = 1; trim < baseline.length; trim++) {
2086
+ if (baseline[trim] !== first)
2087
+ continue;
2088
+ if (++candidates > 4)
2089
+ return 0;
2090
+ const retained = baseline.length - trim;
2091
+ if (retained > target.length)
2092
+ continue;
2093
+ let same = true;
2094
+ for (let index = 0; index < retained; index++)
2095
+ if (baseline[trim + index] !== target[index]) {
2096
+ same = false;
2097
+ break;
2098
+ }
2099
+ if (same)
2100
+ return trim;
2101
+ }
2102
+ return 0;
2103
+ }
1989
2104
  /** Account represented cells without traversing/serializing the snapshot. */
1990
2105
  function canonicalUpdateCellCost(update) {
1991
2106
  if (update.type === "terminal.tombstone")
@@ -123,6 +123,7 @@ export class TerminalReplicaInterpreter {
123
123
  rows: options.rows,
124
124
  scrollback: this.#scrollback,
125
125
  });
126
+ this.#backend.startHistoryCollection?.();
126
127
  this.#kitty = new KittyImageStore(options.kittyImageBudget ? { budget: options.kittyImageBudget } : {});
127
128
  this.#attachKitty(this.#backend);
128
129
  this.#snapshot = blankTerminalReplicaSnapshot(options.cols, options.rows);
@@ -321,6 +322,7 @@ export class TerminalReplicaInterpreter {
321
322
  this.#admitRaw(chunk);
322
323
  this.#observeMarkerBytes(chunk);
323
324
  }
325
+ replacement.startHistoryCollection?.();
324
326
  const previous = this.#backend;
325
327
  this.#backend = replacement;
326
328
  this.#attachKitty(replacement);
@@ -9,6 +9,9 @@ export class XtermTerminalInterpreterBackend {
9
9
  #terminal;
10
10
  #rowCache = new WeakMap();
11
11
  #scrollEpoch = 0;
12
+ #historyLimit;
13
+ #collecting = false;
14
+ #lastYbase = null;
12
15
  #lastScrollEpoch = 0;
13
16
  #lastViewportY = 0;
14
17
  #lastBufferType = "normal";
@@ -21,11 +24,16 @@ export class XtermTerminalInterpreterBackend {
21
24
  #historyProjectionInvalidated = false;
22
25
  #scrollOnClear;
23
26
  constructor(options) {
27
+ const historyLimit = options.historyLimit ?? options.scrollback;
28
+ this.#historyLimit = historyLimit;
24
29
  this.#terminal = new Terminal({
25
30
  cols: options.cols,
26
31
  rows: options.rows,
27
- scrollback: options.scrollback,
28
- tmuxHistoryLimit: options.historyLimit ?? options.scrollback,
32
+ // One row of headroom over what the replica may hold (the limit, or a
33
+ // larger captured history): xterm must not recycle the row a scroll
34
+ // adds before #collectHistory sees it.
35
+ scrollback: historyLimit > 0 ? Math.max(options.scrollback, historyLimit) + 1 : options.scrollback,
36
+ tmuxHistoryLimit: historyLimit,
29
37
  allowProposedApi: true,
30
38
  });
31
39
  this.#terminal.loadAddon(new Unicode11Addon());
@@ -67,8 +75,10 @@ export class XtermTerminalInterpreterBackend {
67
75
  this.#terminal.onScroll(() => {
68
76
  // tmux retains normal history while alternate rows scroll independently.
69
77
  // Neither captured nor live alternate scrolling may trim that history.
70
- if (this.#terminal.buffer.active.type === "normal")
71
- this.#scrollEpoch += 1;
78
+ if (this.#terminal.buffer.active.type !== "normal")
79
+ return;
80
+ this.#scrollEpoch += 1;
81
+ this.#collectHistory();
72
82
  });
73
83
  const core = this.#terminal._core;
74
84
  if (!core?.coreService) {
@@ -76,6 +86,43 @@ export class XtermTerminalInterpreterBackend {
76
86
  throw new Error("Unsupported @tmux-ide/xterm-headless private API shape");
77
87
  }
78
88
  }
89
+ /**
90
+ * tmux at its history-limit collects the oldest tenth of history before a
91
+ * scroll would pass it (grid_collect_history), so its history_size moves
92
+ * between 0.9 and 1.0 of the limit. Recycling one row at a time instead kept
93
+ * the replica at the limit, and the owner's history-size check then reseeded
94
+ * the whole pane each time its output paused. The projection reports the
95
+ * collection as an ordinary history trim.
96
+ */
97
+ startHistoryCollection() {
98
+ this.#collecting = true;
99
+ this.#lastYbase = this.#normalBuffer()?.ybase ?? null;
100
+ }
101
+ #normalBuffer() {
102
+ return this.#terminal._core?.buffers?.normal;
103
+ }
104
+ #collectHistory() {
105
+ const buffer = this.#normalBuffer();
106
+ if (!buffer)
107
+ return;
108
+ const before = this.#lastYbase;
109
+ const limit = this.#historyLimit;
110
+ // Only a plain one-row scroll from at or above the limit is collected
111
+ // here. ED2 collects before its own scrolls (one-column.patch), and any
112
+ // other change (reset, resize, a capped ring) is left alone: a history
113
+ // that still differs from tmux is caught by the owner's size check.
114
+ if (this.#collecting &&
115
+ limit > 0 &&
116
+ before !== null &&
117
+ before >= limit &&
118
+ buffer.ybase === before + 1) {
119
+ const trim = Math.min(buffer.ybase, Math.max(1, Math.floor(limit / 10)));
120
+ buffer.lines.trimStart(trim);
121
+ buffer.ybase -= trim;
122
+ buffer.ydisp = Math.max(0, buffer.ydisp - trim);
123
+ }
124
+ this.#lastYbase = buffer.ybase;
125
+ }
79
126
  get cols() {
80
127
  return this.#terminal.cols;
81
128
  }
@@ -1,13 +1,15 @@
1
1
  import {
2
2
  TERMINAL_RUNTIME_INVENTORY_RESOURCE_VERSION,
3
3
  TerminalRuntimeInventoryProjectionV1SchemaZ,
4
+ TerminalRuntimeInventoryProjectionV2SchemaZ,
4
5
  type TerminalRuntimeInventoryProjectionV1,
6
+ type TerminalRuntimeInventoryProjectionV2,
5
7
  type TerminalRuntimeInventoryResourceV1,
6
8
  type DaemonInstanceIdentity,
7
9
  } from "@tmux-ide/contracts";
8
10
 
9
11
  import type { NativeTerminalRuntimeSessionSnapshot } from "../../terminal/attachments/native-runtime.ts";
10
- import { projectApplicationShellResource } from "./application-shell.ts";
12
+ import { paneIdentities, projectApplicationShellResource } from "./application-shell.ts";
11
13
 
12
14
  /** Pure, wire-safe agent-free topology projection. */
13
15
  export function projectTerminalRuntimeInventory(
@@ -32,6 +34,51 @@ export function projectTerminalRuntimeInventory(
32
34
  });
33
35
  }
34
36
 
37
+ /**
38
+ * #806: version 1 plus each window and its panes, in tmux order. A window is
39
+ * named only when it has a verified window stamp and every pane in it is
40
+ * available, so its pane set is one a window-scoped issue can accept.
41
+ */
42
+ export function projectTerminalRuntimeInventoryV2(
43
+ session: NativeTerminalRuntimeSessionSnapshot,
44
+ resourceRevision: number,
45
+ ): TerminalRuntimeInventoryProjectionV2 {
46
+ const identities = paneIdentities(session);
47
+ const windows = new Map<
48
+ string,
49
+ { semanticWindowId: string | null; active: boolean; panes: string[]; complete: boolean }
50
+ >();
51
+ session.panes.forEach((pane, index) => {
52
+ if (pane.windowId === undefined) return;
53
+ const stamp = pane.windowStamp ?? null;
54
+ const entry = windows.get(pane.windowId) ?? {
55
+ semanticWindowId: stamp,
56
+ active: false,
57
+ panes: [] as string[],
58
+ complete: true,
59
+ };
60
+ windows.set(pane.windowId, entry);
61
+ const attachability = identities[index]!.attachability;
62
+ if (attachability.status === "available") entry.panes.push(attachability.semanticPaneId);
63
+ else entry.complete = false;
64
+ if (pane.active) entry.active = true;
65
+ });
66
+ return TerminalRuntimeInventoryProjectionV2SchemaZ.parse({
67
+ ...projectTerminalRuntimeInventory(session, resourceRevision),
68
+ windows: [...windows.values()].flatMap((window) =>
69
+ window.complete && window.semanticWindowId !== null && window.panes.length > 0
70
+ ? [
71
+ {
72
+ semanticWindowId: window.semanticWindowId,
73
+ active: window.active,
74
+ semanticPaneIds: [...window.panes].sort(),
75
+ },
76
+ ]
77
+ : [],
78
+ ),
79
+ });
80
+ }
81
+
35
82
  export function terminalRuntimeInventoryEnvelope(
36
83
  daemon: DaemonInstanceIdentity,
37
84
  session: NativeTerminalRuntimeSessionSnapshot,
@@ -24,6 +24,7 @@ import {
24
24
  TmuxServersResourceSchemaZ,
25
25
  TmuxServerSessionsResourceSchemaZ,
26
26
  TmuxServerSessionsResourceV2SchemaZ,
27
+ TmuxServerSessionsResourceV3SchemaZ,
27
28
  WorkspaceMultiplexerMutationRequestSchemaZ,
28
29
  WorkspacePaneCreateMutationRequestSchemaZ,
29
30
  WorkspaceSessionCreateArgumentsSchemaZ,
@@ -40,7 +41,10 @@ import { WorkspacePaneCreationError } from "../lib/workspace-pane-creation.ts";
40
41
  import { ownerBearerMatches } from "./owner-authority.ts";
41
42
  import { logger } from "../lib/log.ts";
42
43
  import { mountPaneStreamIssueRoute } from "./pane-stream-issue.ts";
43
- import { projectTerminalRuntimeInventory } from "./resources/terminal-runtime-inventory.ts";
44
+ import {
45
+ projectTerminalRuntimeInventory,
46
+ projectTerminalRuntimeInventoryV2,
47
+ } from "./resources/terminal-runtime-inventory.ts";
44
48
 
45
49
  export interface TmuxServerRoutesOptions {
46
50
  readonly ownerToken: string | null;
@@ -295,7 +299,9 @@ export function mountTmuxServerRoutes(app: Hono, options: TmuxServerRoutesOption
295
299
  `${scoped}/sessions`,
296
300
  route(async (c) => {
297
301
  const server = scope(c);
298
- const v2 = c.req.query("version") === "2";
302
+ // #806: version 3 is version 2 plus the largest window's pane count.
303
+ const v3 = c.req.query("version") === "3";
304
+ const v2 = v3 || c.req.query("version") === "2";
299
305
  const { rows, favicons } = await options.owners.withOwner(server, async (owner) => {
300
306
  const sessions = await owner.catalog();
301
307
  const workspaces = owner.workspaceRegistry.list();
@@ -328,9 +334,10 @@ export function mountTmuxServerRoutes(app: Hono, options: TmuxServerRoutesOption
328
334
  }),
329
335
  );
330
336
  let budget = SESSIONS_RESOURCE_FAVICON_BUDGET_BYTES;
337
+ const schema = v3 ? TmuxServerSessionsResourceV3SchemaZ : TmuxServerSessionsResourceV2SchemaZ;
331
338
  return c.json(
332
- TmuxServerSessionsResourceV2SchemaZ.parse({
333
- version: 2,
339
+ schema.parse({
340
+ version: v3 ? 3 : 2,
334
341
  server,
335
342
  sessions: rows.map(({ session, workspaceName }, index) => {
336
343
  const found = favicons[index] ?? null;
@@ -342,6 +349,7 @@ export function mountTmuxServerRoutes(app: Hono, options: TmuxServerRoutesOption
342
349
  workspaceName,
343
350
  paneCount: session.paneCount,
344
351
  windowCount: session.windowCount,
352
+ ...(v3 ? { largestWindowPaneCount: session.largestWindowPaneCount } : {}),
345
353
  lastActivity: session.lastActivity,
346
354
  favicon: favicon ? { mime: favicon.mime, data: favicon.data } : null,
347
355
  };
@@ -368,6 +376,8 @@ export function mountTmuxServerRoutes(app: Hono, options: TmuxServerRoutesOption
368
376
  route(async (c) => {
369
377
  const server = scope(c);
370
378
  const workspaceName = workspaceSchema.parse(c.req.param("workspaceName"));
379
+ // #806: version 2 also names each window and its panes.
380
+ const v2 = c.req.query("version") === "2";
371
381
  const resource = await options.owners.withOwner(server, async (owner) => {
372
382
  const sessions = await owner.catalog();
373
383
  const workspace = owner.workspaceRegistry.get(workspaceName);
@@ -384,10 +394,13 @@ export function mountTmuxServerRoutes(app: Hono, options: TmuxServerRoutesOption
384
394
  workspace.sessionName,
385
395
  c.req.raw.signal,
386
396
  );
387
- return snapshot ? projectTerminalRuntimeInventory(snapshot, 0) : null;
397
+ if (!snapshot) return null;
398
+ return v2
399
+ ? projectTerminalRuntimeInventoryV2(snapshot, 0)
400
+ : projectTerminalRuntimeInventory(snapshot, 0);
388
401
  });
389
402
  return resource
390
- ? c.json({ version: 1, server, resource })
403
+ ? c.json({ version: v2 ? 2 : 1, server, resource })
391
404
  : c.json({ error: { code: "workspace-not-found" } }, 404);
392
405
  }),
393
406
  );
@@ -108,6 +108,8 @@ function discoveredWorkspaceName(registry: WorkspaceRegistry, sessionName: strin
108
108
  export interface NativeLiveSessionSummary extends LiveSessionSummary {
109
109
  /** Distinct tmux windows of the session (at least one). */
110
110
  readonly windowCount: number;
111
+ /** Panes of the session's largest window (#806: streams open window by window). */
112
+ readonly largestWindowPaneCount: number;
111
113
  /** tmux `#{session_activity}` in epoch seconds, or null when tmux reports none. */
112
114
  readonly lastActivity: number | null;
113
115
  /** tmux `#{session_path}`, the session's working directory. */
@@ -159,7 +161,7 @@ export function createNativeTmuxServerCatalog(
159
161
  {
160
162
  summary: LiveSessionSummary;
161
163
  panes: Set<string>;
162
- windows: Set<string>;
164
+ windows: Map<string, number>;
163
165
  dir: string;
164
166
  activity: number | null;
165
167
  }
@@ -192,12 +194,12 @@ export function createNativeTmuxServerCatalog(
192
194
  const row = rows.get(liveSessionId) ?? {
193
195
  summary: { liveSessionId, sessionName: name, paneCount: 0 },
194
196
  panes: new Set<string>(),
195
- windows: new Set<string>(),
197
+ windows: new Map<string, number>(),
196
198
  dir,
197
199
  activity: activity && /^\d+$/.test(activity) ? Number(activity) : null,
198
200
  };
201
+ if (!row.panes.has(pane)) row.windows.set(window, (row.windows.get(window) ?? 0) + 1);
199
202
  row.panes.add(pane);
200
- row.windows.add(window);
201
203
  rows.set(liveSessionId, row);
202
204
  }
203
205
  const names = new Set([...rows.values()].map(({ summary }) => summary.sessionName));
@@ -218,6 +220,7 @@ export function createNativeTmuxServerCatalog(
218
220
  ...summary,
219
221
  paneCount: panes.size,
220
222
  windowCount: windows.size,
223
+ largestWindowPaneCount: Math.max(...windows.values()),
221
224
  lastActivity: activity,
222
225
  sessionPath: dir,
223
226
  }));
@@ -92,6 +92,8 @@ export type MirrorPaneEvent =
92
92
  /** One visible pane rectangle inside a layout event, in window cells. */
93
93
  export interface MirrorLayoutPane {
94
94
  browserIcon?: string | null;
95
+ /** #718: a terminal browser with native controls, a plain one, or null. */
96
+ browserKind?: "native" | "plain" | null;
95
97
  /** A live Markdown reader pane; the path is daemon-only and never framed. */
96
98
  reader?: { name: string; path: string } | null;
97
99
  /** Null while the pane's semantic identity join is still unverified. */
@@ -755,6 +755,10 @@ export class SessionChannel {
755
755
  await this.captureAttachedSessionIdentity();
756
756
  this.io.send("refresh-client -B 'tmux-ide-browser-icon:%*:#{@tmux_ide_browser_icon}'");
757
757
  this.io.send("refresh-client -B 'tmux-ide-reader:%*:#{@tmux_ide_reader}'");
758
+ // #718: a browser's controls appear, or a plain terminal browser starts or exits.
759
+ this.io.send(
760
+ "refresh-client -B 'tmux-ide-browser-kind:%*:#{@tmux_ide_browser_control}#{m:terminal-browse*,#{pane_current_command}}'",
761
+ );
758
762
  // Changing border placement can resize PTYs without changing the layout
759
763
  // string, so tmux emits no layout-change. Subscribe to this window option.
760
764
  this.io.send("refresh-client -B 'tmux-ide-pane-borders:@*:#{pane-border-status}'");
@@ -2937,7 +2941,9 @@ export class SessionChannel {
2937
2941
  this.opts.onWindowTopologyChanged?.();
2938
2942
  if (
2939
2943
  name === "subscription-changed" &&
2940
- (rest.startsWith("tmux-ide-browser-icon ") || rest.startsWith("tmux-ide-reader "))
2944
+ (rest.startsWith("tmux-ide-browser-icon ") ||
2945
+ rest.startsWith("tmux-ide-reader ") ||
2946
+ rest.startsWith("tmux-ide-browser-kind "))
2941
2947
  ) {
2942
2948
  this.scheduleSync();
2943
2949
  return;
@@ -3355,6 +3361,7 @@ export class SessionChannel {
3355
3361
  displayName: display?.name ?? null,
3356
3362
  displayNameSource: display?.source ?? null,
3357
3363
  browserIcon: pane?.descriptor?.browserIcon ?? null,
3364
+ browserKind: pane?.descriptor?.browserKind ?? null,
3358
3365
  reader: pane?.descriptor?.reader ?? null,
3359
3366
  left: leaf.left,
3360
3367
  top: leaf.top,