tmux-ide 2.9.25 → 2.9.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +1577 -559
  3. package/package.json +3 -2
  4. package/packages/contracts/src/pane-stream.ts +28 -0
  5. package/packages/contracts/src/terminal-delivery.ts +122 -5
  6. package/packages/contracts/src/terminal-runtime-inventory.ts +61 -1
  7. package/packages/contracts/src/tmux-server-scope.ts +18 -0
  8. package/packages/core/src/index.ts +1 -0
  9. package/packages/core/src/terminal-delivery-binary.ts +8 -7
  10. package/packages/core/src/terminal-delivery.ts +174 -3
  11. package/packages/core/src/terminal-partial-history.ts +152 -0
  12. package/packages/core/src/terminal-replica.ts +70 -1
  13. package/packages/daemon/dist/command-center/owner-keep-alive.js +30 -0
  14. package/packages/daemon/dist/command-center/resources/terminal-runtime-inventory.js +42 -2
  15. package/packages/daemon/dist/command-center/server.js +3 -0
  16. package/packages/daemon/dist/command-center/tmux-server-attach.js +51 -0
  17. package/packages/daemon/dist/command-center/tmux-servers.js +95 -7
  18. package/packages/daemon/dist/doctor.js +4 -4
  19. package/packages/daemon/dist/lib/app-config.js +7 -0
  20. package/packages/daemon/dist/lib/node-requirement.js +20 -0
  21. package/packages/daemon/dist/lib/require-supported-node.js +8 -0
  22. package/packages/daemon/dist/lib/tmux-server-owner.js +4 -2
  23. package/packages/daemon/dist/lib/tmux-server-session-open.js +38 -12
  24. package/packages/daemon/dist/lib/workspace-promotion.js +4 -4
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  27. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  29. package/packages/daemon/dist/server/pane-stream-upgrade.js +39 -1
  30. package/packages/daemon/dist/terminal/mirror/session-channel.js +6 -1
  31. package/packages/daemon/dist/terminal/pane-stream/lease-manager.js +1 -0
  32. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +112 -22
  33. package/packages/daemon/dist/terminal/protocol/browser-icon.js +1 -1
  34. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +26 -3
  35. package/packages/daemon/dist/terminal/session-runtime/registry.js +2 -0
  36. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +571 -33
  37. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +2 -0
  38. package/packages/daemon/dist/terminal/session-runtime/xterm-terminal-interpreter-backend.js +51 -4
  39. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +76 -2
  40. package/packages/daemon/dist/tui/mirror/theme.js +8 -1
  41. package/packages/daemon/src/command-center/attach-window-rule.cases.json +84 -0
  42. package/packages/daemon/src/command-center/owner-keep-alive.ts +38 -0
  43. package/packages/daemon/src/command-center/resources/terminal-runtime-inventory.ts +48 -1
  44. package/packages/daemon/src/command-center/server.ts +3 -0
  45. package/packages/daemon/src/command-center/tmux-server-attach.ts +75 -0
  46. package/packages/daemon/src/command-center/tmux-servers.ts +103 -6
  47. package/packages/daemon/src/doctor.ts +4 -4
  48. package/packages/daemon/src/lib/app-config.ts +15 -0
  49. package/packages/daemon/src/lib/node-requirement.ts +22 -0
  50. package/packages/daemon/src/lib/require-supported-node.ts +9 -0
  51. package/packages/daemon/src/lib/tmux-server-owner.ts +6 -3
  52. package/packages/daemon/src/lib/tmux-server-session-open.ts +53 -15
  53. package/packages/daemon/src/lib/workspace-promotion.ts +4 -4
  54. package/packages/daemon/src/server/pane-stream-upgrade.ts +41 -1
  55. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  56. package/packages/daemon/src/terminal/mirror/session-channel.ts +8 -1
  57. package/packages/daemon/src/terminal/pane-stream/lease-manager.ts +3 -0
  58. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +136 -20
  59. package/packages/daemon/src/terminal/protocol/browser-icon.ts +1 -1
  60. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +32 -2
  61. package/packages/daemon/src/terminal/session-runtime/registry.ts +2 -0
  62. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +696 -30
  63. package/packages/daemon/src/terminal/session-runtime/terminal-interpreter-backend.ts +6 -0
  64. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +2 -0
  65. package/packages/daemon/src/terminal/session-runtime/xterm-terminal-interpreter-backend.ts +67 -3
  66. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +82 -2
  67. package/packages/daemon/src/tui/mirror/theme.ts +13 -1
@@ -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,4 +1,4 @@
1
- import { STOCK_CAPTURE_TAB_UNAVAILABLE } from "@tmux-ide/contracts";
1
+ import { STOCK_CAPTURE_TAB_UNAVAILABLE, TERMINAL_DELIVERY_MAX_PIPELINED, TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION, } from "@tmux-ide/contracts";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { TerminalDeliveryAssembler, decodeVerifiedCompactSemanticTerminalUpdate, decodeVerifiedCompactSemanticTerminalUpdateCooperatively, decodeVerifiedLegacySemanticTerminalUpdate, terminalDeliveryEncodingAccepted, } from "@tmux-ide/core";
4
4
  import { PaneStreamOperationError, } from "@tmux-ide/daemon-client/pane-stream-client";
@@ -244,6 +244,13 @@ class WireTerminalEndpoint {
244
244
  #pending = null;
245
245
  #rejectedTransactionId = null;
246
246
  #decodeToken = null;
247
+ /**
248
+ * Capability 124: patches the daemon pipelined behind the delivery that is
249
+ * still decoding or unsettled, each with its chunks, in arrival order. Each
250
+ * names the one before as its base; they are admitted once that one is ACKed.
251
+ */
252
+ #queued = [];
253
+ #draining = false;
247
254
  #closed = false;
248
255
  #ready;
249
256
  #resolveReady;
@@ -311,6 +318,7 @@ class WireTerminalEndpoint {
311
318
  return;
312
319
  }
313
320
  if (message.type === "terminal.delivery.fault") {
321
+ this.#queued.length = 0;
314
322
  if (message.deliveryNonce !== this.#negotiated.deliveryNonce) {
315
323
  this.#failConnection(new Error("Terminal fault nonce does not match negotiation"));
316
324
  return;
@@ -335,6 +343,15 @@ class WireTerminalEndpoint {
335
343
  }
336
344
  if (this.#unavailable)
337
345
  return;
346
+ if ((this.#queued.length > 0 || this.#busy()) && this.#mayQueue(message)) {
347
+ this.#queued.push(message);
348
+ return;
349
+ }
350
+ return this.#acceptNow(message);
351
+ }
352
+ #acceptNow(message) {
353
+ if (message.type === "terminal.delivery.fault")
354
+ return;
338
355
  if (message.type === "terminal.projection") {
339
356
  this.#failConnection(new Error("Unsolicited alternate-screen projection"));
340
357
  return;
@@ -345,10 +362,61 @@ class WireTerminalEndpoint {
345
362
  }
346
363
  return this.#acceptChunk(message);
347
364
  }
365
+ /** A flight is decoding or waiting for its subscriber: it has not been ACKed. */
366
+ #busy() {
367
+ return this.#decodeToken !== null || this.#pending !== null;
368
+ }
369
+ /**
370
+ * Capability 124: only a patch based on the newest flight (decoding,
371
+ * unsettled or queued), within TERMINAL_DELIVERY_MAX_PIPELINED, and the
372
+ * chunks of the newest queued patch. Anything else overlapping a flight is
373
+ * still a protocol violation and takes the ordinary path.
374
+ */
375
+ #mayQueue(message) {
376
+ let newest = this.#pending?.envelope ?? this.#envelope;
377
+ let envelopes = 1;
378
+ let chunks = 0;
379
+ for (const queued of this.#queued)
380
+ if (queued.type === "terminal.delivery") {
381
+ newest = queued;
382
+ envelopes += 1;
383
+ chunks = 0;
384
+ }
385
+ else if (queued.type === "terminal.delivery.chunk")
386
+ chunks += 1;
387
+ if (!newest)
388
+ return false;
389
+ if (message.type === "terminal.delivery.chunk")
390
+ return (envelopes > 1 &&
391
+ message.transactionId === newest.transactionId &&
392
+ chunks < newest.chunkCount);
393
+ return (message.type === "terminal.delivery" &&
394
+ message.frame === "patch" &&
395
+ message.baseRevision === newest.canonicalRevision &&
396
+ message.incarnation === newest.incarnation &&
397
+ envelopes < TERMINAL_DELIVERY_MAX_PIPELINED &&
398
+ (envelopes === 1 || chunks === newest.chunkCount));
399
+ }
400
+ /** Admit queued deliveries in order until one is decoding or unsettled again. */
401
+ #drain() {
402
+ if (this.#draining)
403
+ return;
404
+ this.#draining = true;
405
+ try {
406
+ while (this.#queued.length > 0 && !this.#busy() && !this.#closed) {
407
+ const message = this.#queued.shift();
408
+ this.#acceptNow(message);
409
+ }
410
+ }
411
+ finally {
412
+ this.#draining = false;
413
+ }
414
+ }
348
415
  close() {
349
416
  if (this.#closed)
350
417
  return;
351
418
  this.#closed = true;
419
+ this.#queued.length = 0;
352
420
  this.#assembler = null;
353
421
  this.#assemblyStorage = null;
354
422
  this.#envelope = null;
@@ -595,7 +663,9 @@ class WireTerminalEndpoint {
595
663
  }
596
664
  catch (error) {
597
665
  this.#failConnection(error instanceof Error ? error : new Error(String(error)));
666
+ return;
598
667
  }
668
+ this.#drain();
599
669
  }
600
670
  #reject(reason, envelope, transactionId = null) {
601
671
  const negotiated = this.#negotiated;
@@ -626,6 +696,9 @@ class WireTerminalEndpoint {
626
696
  this.#decodeToken = null;
627
697
  this.#rejectedTransactionId = attempted?.transactionId ?? transactionId;
628
698
  this.#reseedRequired = true;
699
+ // Patches queued behind the rejected flight are NACKed in turn ("gap");
700
+ // the daemon dropped them with the first NACK.
701
+ this.#drain();
629
702
  }
630
703
  }
631
704
  class WireTerminalSubscription {
@@ -942,7 +1015,8 @@ export async function connectOpenTuiWorkspaceRuntimePort(options) {
942
1015
  panes: [...panes],
943
1016
  viewerMode: "interactive",
944
1017
  terminalDelivery: {
945
- protocolVersions: [1],
1018
+ // 124: this endpoint holds patches pipelined behind a decoding one.
1019
+ protocolVersions: [1, TERMINAL_DELIVERY_PIPELINING_CAPABILITY_VERSION],
946
1020
  encodings: ["semantic-compact-v1", "semantic-v1"],
947
1021
  richPlacements: true,
948
1022
  },
@@ -597,10 +597,17 @@ export function createSemanticThemeSnapshot(config = undefined, rendererMode = n
597
597
  increasedContrast: config?.accessibility?.increasedContrast ?? DEFAULT_ACCESSIBILITY.increasedContrast,
598
598
  };
599
599
  const mode = resolvedMode(setting, rendererMode, hostDefaults);
600
+ // System mode with a chosen preset for each side (the Mac app's Match
601
+ // macOS writes theme.light / theme.dark): the side the host is on.
602
+ const side = setting === "system"
603
+ ? findVisualThemePreset(mode === "light" ? config?.light : config?.dark)
604
+ : undefined;
600
605
  const resolved = resolveVisualTheme({
601
606
  appearance: mode,
602
607
  hostDefaults: setting === "system" ? (hostDefaults ?? undefined) : undefined,
603
- userTheme: config?.userTheme ?? findVisualThemePreset(config?.preset),
608
+ userTheme: config?.userTheme ??
609
+ findVisualThemePreset(config?.preset) ??
610
+ (side?.appearance === mode ? side : undefined),
604
611
  projectTheme: config?.projectTheme,
605
612
  accessibility,
606
613
  });
@@ -0,0 +1,84 @@
1
+ [
2
+ {
3
+ "name": "a session that fits streams whole, preferred pane selected",
4
+ "windows": [
5
+ { "id": "window.a", "active": false, "panes": ["pane.1", "pane.2"] },
6
+ { "id": "window.b", "active": true, "panes": ["pane.3"] }
7
+ ],
8
+ "preferred": "pane.3",
9
+ "maxPanes": 3,
10
+ "expect": { "window": null, "panes": ["pane.1", "pane.2", "pane.3"], "selected": "pane.3" }
11
+ },
12
+ {
13
+ "name": "a whole session without a preferred pane selects the first",
14
+ "windows": [{ "id": "window.a", "active": true, "panes": ["pane.1", "pane.2"] }],
15
+ "preferred": null,
16
+ "maxPanes": 2,
17
+ "expect": { "window": null, "panes": ["pane.1", "pane.2"], "selected": "pane.1" }
18
+ },
19
+ {
20
+ "name": "a preferred pane that is gone selects the first",
21
+ "windows": [{ "id": "window.a", "active": true, "panes": ["pane.1"] }],
22
+ "preferred": "pane.9",
23
+ "maxPanes": 24,
24
+ "expect": { "window": null, "panes": ["pane.1"], "selected": "pane.1" }
25
+ },
26
+ {
27
+ "name": "too many panes: the window holding the preferred pane",
28
+ "windows": [
29
+ { "id": "window.a", "active": true, "panes": ["pane.1", "pane.2"] },
30
+ { "id": "window.b", "active": false, "panes": ["pane.3", "pane.4"] }
31
+ ],
32
+ "preferred": "pane.4",
33
+ "maxPanes": 3,
34
+ "expect": { "window": "window.b", "panes": ["pane.3", "pane.4"], "selected": "pane.4" }
35
+ },
36
+ {
37
+ "name": "too many panes and no preferred pane: the active window",
38
+ "windows": [
39
+ { "id": "window.a", "active": false, "panes": ["pane.1", "pane.2"] },
40
+ { "id": "window.b", "active": true, "panes": ["pane.3", "pane.4"] }
41
+ ],
42
+ "preferred": null,
43
+ "maxPanes": 3,
44
+ "expect": { "window": "window.b", "panes": ["pane.3", "pane.4"], "selected": "pane.3" }
45
+ },
46
+ {
47
+ "name": "the wanted window does not fit: the active one",
48
+ "windows": [
49
+ { "id": "window.a", "active": false, "panes": ["pane.1", "pane.2", "pane.5"] },
50
+ { "id": "window.b", "active": true, "panes": ["pane.3"] }
51
+ ],
52
+ "preferred": "pane.2",
53
+ "maxPanes": 2,
54
+ "expect": { "window": "window.b", "panes": ["pane.3"], "selected": "pane.3" }
55
+ },
56
+ {
57
+ "name": "neither wanted nor active fits: the first that fits",
58
+ "windows": [
59
+ { "id": "window.a", "active": true, "panes": ["pane.1", "pane.2", "pane.5"] },
60
+ { "id": "window.b", "active": false, "panes": ["pane.3", "pane.6", "pane.7"] },
61
+ { "id": "window.c", "active": false, "panes": ["pane.4"] }
62
+ ],
63
+ "preferred": null,
64
+ "maxPanes": 2,
65
+ "expect": { "window": "window.c", "panes": ["pane.4"], "selected": "pane.4" }
66
+ },
67
+ {
68
+ "name": "nothing fits: no selection",
69
+ "windows": [
70
+ { "id": "window.a", "active": true, "panes": ["pane.1", "pane.2"] },
71
+ { "id": "window.b", "active": false, "panes": ["pane.3", "pane.4"] }
72
+ ],
73
+ "preferred": null,
74
+ "maxPanes": 1,
75
+ "expect": null
76
+ },
77
+ {
78
+ "name": "no panes: no selection",
79
+ "windows": [],
80
+ "preferred": null,
81
+ "maxPanes": 24,
82
+ "expect": null
83
+ }
84
+ ]
@@ -0,0 +1,38 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { MiddlewareHandler } from "hono";
3
+ import { ownerBearerMatches } from "./owner-authority.ts";
4
+
5
+ /**
6
+ * How long an owner-authenticated HTTP connection may sit idle before the
7
+ * daemon closes it. Node's default is 5 s, so a native app that paused for
8
+ * longer found its proven connection gone; over SSH every replacement costs
9
+ * a channel open and an identity proof (attach-rtt). The app keeps an idle
10
+ * connection for at most 60 s, below this.
11
+ */
12
+ export const OWNER_KEEP_ALIVE_MS = 65_000;
13
+
14
+ type NodeBindings = { incoming?: IncomingMessage; outgoing?: ServerResponse } | undefined;
15
+
16
+ /**
17
+ * After a response to the owner bearer, keep that connection open for
18
+ * `timeoutMs` while idle. Every other connection keeps Node's default.
19
+ * Node arms its own keep-alive timer when the response finishes; this runs
20
+ * after it and replaces the bound for this socket only. The next request on
21
+ * the socket clears the timer as usual.
22
+ */
23
+ export function ownerKeepAlive(
24
+ ownerToken: string | null,
25
+ timeoutMs: number = OWNER_KEEP_ALIVE_MS,
26
+ ): MiddlewareHandler {
27
+ return async (c, next) => {
28
+ const bindings = c.env as NodeBindings;
29
+ const outgoing = bindings?.outgoing;
30
+ const socket = bindings?.incoming?.socket;
31
+ if (outgoing && socket && ownerBearerMatches(c.req.header("Authorization"), ownerToken)) {
32
+ outgoing.once("finish", () => {
33
+ if (!socket.destroyed && outgoing.shouldKeepAlive) socket.setTimeout(timeoutMs);
34
+ });
35
+ }
36
+ await next();
37
+ };
38
+ }
@@ -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,
@@ -161,6 +161,7 @@ import { mountWorkspaceResourceRoutes } from "./resources/workspace-resource-rou
161
161
  import { mountFleetResourceRoute } from "./resources/fleet-resource-route.ts";
162
162
  import { mountWorkspaceMissionsRoute } from "./resources/workspace-missions-route.ts";
163
163
  import { ownerAuthorityGate, requireOwnerAuthority } from "./owner-authority.ts";
164
+ import { ownerKeepAlive } from "./owner-keep-alive.ts";
164
165
  import { mountDiagnosticsRoute } from "./diagnostics.ts";
165
166
  import {
166
167
  mountStartupReadinessRoute,
@@ -569,6 +570,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
569
570
 
570
571
  // Allow cross-origin (Next.js dashboard, Tailscale, etc.)
571
572
  app.use("/*", cors());
573
+ // An owner connection stays open while idle for longer than Node's 5 s.
574
+ app.use("/*", ownerKeepAlive(options.remoteAccess?.ownerToken ?? null));
572
575
 
573
576
  if (options.tmuxServerOwners) {
574
577
  mountAutomationRoutes(app, {
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * One request that opens a session, reads its inventory and issues its stream
5
+ * (attach-rtt). Before it the app sent three: open, inventory, issue. The app
6
+ * still checks the answer: it applies its own window rule to the returned
7
+ * inventory and uses the issued stream only when the daemon chose the same.
8
+ *
9
+ * `issue` is the body of an ordinary pane-stream issue request without the
10
+ * workspace name, the panes and the window, which only the daemon knows here.
11
+ */
12
+ export const TmuxServerAttachRequestSchemaZ = z
13
+ .object({
14
+ version: z.literal(1),
15
+ preferredPane: z.string().min(1).max(128).nullable(),
16
+ maxPanes: z.number().int().min(1).max(256),
17
+ issue: z
18
+ .object({
19
+ expectedDaemonInstanceId: z.uuid(),
20
+ stream: z.record(z.string(), z.unknown()),
21
+ })
22
+ .catchall(z.unknown()),
23
+ })
24
+ .strict();
25
+ export type TmuxServerAttachRequest = z.infer<typeof TmuxServerAttachRequestSchemaZ>;
26
+
27
+ export interface AttachInventory {
28
+ readonly semanticPaneIds: readonly string[];
29
+ readonly windows: readonly {
30
+ readonly semanticWindowId: string;
31
+ readonly active: boolean;
32
+ readonly semanticPaneIds: readonly string[];
33
+ }[];
34
+ }
35
+
36
+ export interface AttachSelection {
37
+ /** The one window the stream carries, or null for the whole session. */
38
+ readonly semanticWindowId: string | null;
39
+ readonly panes: readonly string[];
40
+ readonly selectedPane: string;
41
+ }
42
+
43
+ /**
44
+ * The app's rule (browser_native_local_window.rs `scope`), here so the open
45
+ * and the issue can be one request: a session that fits streams whole;
46
+ * otherwise the window holding the preferred pane (else the active one) when
47
+ * it fits, else the active one, else the first in tmux order that fits. No
48
+ * selection when there is no pane or nothing fits: the app decides then.
49
+ */
50
+ export function chooseAttachSelection(
51
+ inventory: AttachInventory,
52
+ preferredPane: string | null,
53
+ maxPanes: number,
54
+ ): AttachSelection | null {
55
+ const panes = inventory.semanticPaneIds;
56
+ if (panes.length === 0) return null;
57
+ let semanticWindowId: string | null = null;
58
+ let chosen = panes;
59
+ if (panes.length > maxPanes) {
60
+ const fits = (window: AttachInventory["windows"][number] | undefined) =>
61
+ window !== undefined && window.semanticPaneIds.length <= maxPanes;
62
+ const active = inventory.windows.find((window) => window.active);
63
+ const wanted =
64
+ (preferredPane !== null
65
+ ? inventory.windows.find((window) => window.semanticPaneIds.includes(preferredPane))
66
+ : undefined) ?? active;
67
+ const window = [wanted, active].find(fits) ?? inventory.windows.find(fits);
68
+ if (!window) return null;
69
+ semanticWindowId = window.semanticWindowId;
70
+ chosen = window.semanticPaneIds;
71
+ }
72
+ const selectedPane =
73
+ preferredPane !== null && chosen.includes(preferredPane) ? preferredPane : chosen[0]!;
74
+ return { semanticWindowId, panes: chosen, selectedPane };
75
+ }