tmux-ide 2.9.26 → 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 (47) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +1252 -528
  3. package/package.json +2 -2
  4. package/packages/contracts/src/pane-stream.ts +9 -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/server.js +3 -0
  13. package/packages/daemon/dist/command-center/tmux-server-attach.js +51 -0
  14. package/packages/daemon/dist/command-center/tmux-servers.js +78 -0
  15. package/packages/daemon/dist/doctor.js +4 -4
  16. package/packages/daemon/dist/lib/app-config.js +7 -0
  17. package/packages/daemon/dist/lib/node-requirement.js +20 -0
  18. package/packages/daemon/dist/lib/require-supported-node.js +8 -0
  19. package/packages/daemon/dist/lib/tmux-server-session-open.js +38 -12
  20. package/packages/daemon/dist/lib/workspace-promotion.js +4 -4
  21. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  22. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  23. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  25. package/packages/daemon/dist/server/pane-stream-upgrade.js +39 -1
  26. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +14 -0
  27. package/packages/daemon/dist/terminal/session-runtime/registry.js +1 -0
  28. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +465 -42
  29. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +76 -2
  30. package/packages/daemon/dist/tui/mirror/theme.js +8 -1
  31. package/packages/daemon/src/command-center/attach-window-rule.cases.json +84 -0
  32. package/packages/daemon/src/command-center/owner-keep-alive.ts +38 -0
  33. package/packages/daemon/src/command-center/server.ts +3 -0
  34. package/packages/daemon/src/command-center/tmux-server-attach.ts +75 -0
  35. package/packages/daemon/src/command-center/tmux-servers.ts +84 -0
  36. package/packages/daemon/src/doctor.ts +4 -4
  37. package/packages/daemon/src/lib/app-config.ts +15 -0
  38. package/packages/daemon/src/lib/node-requirement.ts +22 -0
  39. package/packages/daemon/src/lib/require-supported-node.ts +9 -0
  40. package/packages/daemon/src/lib/tmux-server-session-open.ts +53 -15
  41. package/packages/daemon/src/lib/workspace-promotion.ts +4 -4
  42. package/packages/daemon/src/server/pane-stream-upgrade.ts +41 -1
  43. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +25 -0
  44. package/packages/daemon/src/terminal/session-runtime/registry.ts +1 -0
  45. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +575 -39
  46. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +82 -2
  47. package/packages/daemon/src/tui/mirror/theme.ts +13 -1
@@ -0,0 +1,152 @@
1
+ import {
2
+ TERMINAL_HISTORY_EMPTY_DIGEST,
3
+ type TerminalDeliveryHistoryCommitment,
4
+ type TerminalReplicaRow,
5
+ type TerminalReplicaSnapshot,
6
+ } from "@tmux-ide/contracts";
7
+ import {
8
+ concatTerminalReplicaRowsDigest,
9
+ dropTerminalReplicaRowsDigestPrefix,
10
+ popTerminalReplicaRowsDigestSuffix,
11
+ hashTerminalReplicaRows,
12
+ hashTerminalReplicaSnapshotWithHistoryDigest,
13
+ } from "./terminal-replica.ts";
14
+
15
+ /**
16
+ * History on demand (capability 122). A client holds the newest history rows
17
+ * and a commitment `{rows, digest}` to the older rows it has not loaded. The
18
+ * rows digest is a polynomial fold, so the commitment plus the loaded rows give
19
+ * the whole history's digest and the snapshot verifies against the full
20
+ * canonical state hash.
21
+ */
22
+
23
+ /** H(A ++ B) from H(A) and B. */
24
+ export function concatTerminalHistoryDigest(
25
+ prefixDigest: string,
26
+ suffix: readonly TerminalReplicaRow[],
27
+ ): string {
28
+ return concatTerminalReplicaRowsDigest(prefixDigest, suffix);
29
+ }
30
+
31
+ /** Frozen histories are immutable: a prefix digest computed once is reused. */
32
+ const PREFIX_COMMITMENTS = new WeakMap<
33
+ readonly TerminalReplicaRow[],
34
+ Map<number, TerminalDeliveryHistoryCommitment>
35
+ >();
36
+
37
+ /** The commitment to the oldest `unloadedRows` rows of a history (O(unloaded), cached). */
38
+ export function terminalHistoryPrefixCommitment(
39
+ history: readonly TerminalReplicaRow[],
40
+ unloadedRows: number,
41
+ ): TerminalDeliveryHistoryCommitment {
42
+ if (!Number.isSafeInteger(unloadedRows) || unloadedRows < 0 || unloadedRows > history.length)
43
+ throw new RangeError("Unloaded rows outside the history");
44
+ const cache = Object.isFrozen(history) ? PREFIX_COMMITMENTS.get(history) : undefined;
45
+ const cached = cache?.get(unloadedRows);
46
+ if (cached) return cached;
47
+ const commitment = Object.freeze({
48
+ rows: unloadedRows,
49
+ digest: hashTerminalReplicaRows(
50
+ unloadedRows === history.length ? history : history.slice(0, unloadedRows),
51
+ ),
52
+ });
53
+ if (Object.isFrozen(history)) {
54
+ const entries = cache ?? new Map<number, TerminalDeliveryHistoryCommitment>();
55
+ if (entries.size >= 8) entries.delete(entries.keys().next().value!);
56
+ entries.set(unloadedRows, commitment);
57
+ PREFIX_COMMITMENTS.set(history, entries);
58
+ }
59
+ return commitment;
60
+ }
61
+
62
+ /** The commitment once its oldest rows `dropped` are trimmed away: O(|dropped|). */
63
+ export function dropTerminalHistoryCommitmentPrefix(
64
+ commitment: TerminalDeliveryHistoryCommitment,
65
+ dropped: readonly TerminalReplicaRow[],
66
+ ): TerminalDeliveryHistoryCommitment {
67
+ if (dropped.length > commitment.rows) throw new RangeError("Dropped rows exceed the commitment");
68
+ const rows = commitment.rows - dropped.length;
69
+ return Object.freeze({
70
+ rows,
71
+ digest:
72
+ rows === 0
73
+ ? TERMINAL_HISTORY_EMPTY_DIGEST
74
+ : dropTerminalReplicaRowsDigestPrefix(commitment.digest, dropped, rows),
75
+ });
76
+ }
77
+
78
+ /** The commitment once its newest rows `taken` are sent as a chunk: O(|taken|). */
79
+ export function popTerminalHistoryCommitmentSuffix(
80
+ commitment: TerminalDeliveryHistoryCommitment,
81
+ taken: readonly TerminalReplicaRow[],
82
+ ): TerminalDeliveryHistoryCommitment {
83
+ if (taken.length > commitment.rows) throw new RangeError("Taken rows exceed the commitment");
84
+ const rows = commitment.rows - taken.length;
85
+ return Object.freeze({
86
+ rows,
87
+ digest:
88
+ rows === 0
89
+ ? TERMINAL_HISTORY_EMPTY_DIGEST
90
+ : popTerminalReplicaRowsDigestSuffix(commitment.digest, taken),
91
+ });
92
+ }
93
+
94
+ /** The canonical hash of a snapshot holding only its loaded history rows. */
95
+ export function hashPartialTerminalReplicaSnapshot(
96
+ snapshot: TerminalReplicaSnapshot,
97
+ unloaded: TerminalDeliveryHistoryCommitment,
98
+ ): string {
99
+ return hashTerminalReplicaSnapshotWithHistoryDigest(
100
+ snapshot,
101
+ concatTerminalHistoryDigest(unloaded.digest, snapshot.history),
102
+ );
103
+ }
104
+
105
+ /** Keep the newest `tailRows` history rows; commit to the rest. */
106
+ export function splitTerminalHistory(
107
+ snapshot: TerminalReplicaSnapshot,
108
+ tailRows: number,
109
+ ): { snapshot: TerminalReplicaSnapshot; unloaded: TerminalDeliveryHistoryCommitment } {
110
+ const unloadedRows = Math.max(0, snapshot.history.length - Math.max(0, Math.floor(tailRows)));
111
+ return {
112
+ snapshot:
113
+ unloadedRows === 0
114
+ ? snapshot
115
+ : { ...snapshot, history: snapshot.history.slice(unloadedRows) },
116
+ unloaded: terminalHistoryPrefixCommitment(snapshot.history, unloadedRows),
117
+ };
118
+ }
119
+
120
+ /** The newest `maxRows` rows of the unloaded part, oldest first, and what stays unloaded. */
121
+ export function takeTerminalHistoryChunk(
122
+ history: readonly TerminalReplicaRow[],
123
+ unloadedRows: number,
124
+ maxRows: number,
125
+ ): { rows: readonly TerminalReplicaRow[]; unloaded: TerminalDeliveryHistoryCommitment } {
126
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1) throw new RangeError("Invalid chunk size");
127
+ const remaining = Math.max(0, unloadedRows - maxRows);
128
+ return {
129
+ rows: history.slice(remaining, unloadedRows),
130
+ unloaded: terminalHistoryPrefixCommitment(history, remaining),
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Prepend a history chunk after proving it: the old commitment must equal the
136
+ * new commitment extended by exactly these rows.
137
+ */
138
+ export function prependVerifiedTerminalHistory(
139
+ snapshot: TerminalReplicaSnapshot,
140
+ unloaded: TerminalDeliveryHistoryCommitment,
141
+ rows: readonly TerminalReplicaRow[],
142
+ next: TerminalDeliveryHistoryCommitment,
143
+ ): TerminalReplicaSnapshot {
144
+ if (
145
+ rows.length === 0 ||
146
+ (next.rows === 0 && next.digest !== TERMINAL_HISTORY_EMPTY_DIGEST) ||
147
+ next.rows + rows.length !== unloaded.rows ||
148
+ concatTerminalHistoryDigest(next.digest, rows) !== unloaded.digest
149
+ )
150
+ throw new TypeError("The history chunk does not match the unloaded commitment");
151
+ return { ...snapshot, history: [...rows, ...snapshot.history] };
152
+ }
@@ -43,6 +43,13 @@ const ROW_ARRAY_HASH_CACHE = new WeakMap<
43
43
  { readonly hash: bigint; readonly length: number }
44
44
  >();
45
45
  const ROW_SEQUENCE_BASE = 0x100000001b3n;
46
+ /** ROW_SEQUENCE_BASE⁻¹ mod 2^64 (Newton's iteration; the base is odd). */
47
+ const ROW_SEQUENCE_BASE_INVERSE = (() => {
48
+ let inverse = ROW_SEQUENCE_BASE;
49
+ for (let step = 0; step < 6; step++)
50
+ inverse = BigInt.asUintN(64, inverse * (2n - ROW_SEQUENCE_BASE * inverse));
51
+ return inverse;
52
+ })();
46
53
 
47
54
  export interface TerminalReplicaState extends TerminalReplicaAddress {
48
55
  readonly generation: SessionRuntimeGeneration;
@@ -782,10 +789,72 @@ export function hashTerminalReplicaSnapshot(snapshot: TerminalReplicaSnapshot):
782
789
  return hashTerminalReplicaSnapshotProfiled(snapshot);
783
790
  }
784
791
 
792
+ /**
793
+ * Capability 122: the canonical hash of a snapshot whose `history` holds only
794
+ * the newest rows, given the digest of the whole history (see
795
+ * concatTerminalReplicaRowsDigest). Equal to the full snapshot's hash.
796
+ */
797
+ export function hashTerminalReplicaSnapshotWithHistoryDigest(
798
+ snapshot: TerminalReplicaSnapshot,
799
+ historyDigest: string,
800
+ ): string {
801
+ return hashTerminalReplicaSnapshotProfiled(snapshot, undefined, undefined, historyDigest);
802
+ }
803
+
804
+ /**
805
+ * The rows digest is a polynomial fold, H(A ++ B) = H(A)·P^|B| + H(B) mod 2^64,
806
+ * so the digest of older rows extends by newer rows without the older ones.
807
+ */
808
+ export function concatTerminalReplicaRowsDigest(
809
+ prefixDigest: string,
810
+ suffix: readonly TerminalReplicaRow[],
811
+ ): string {
812
+ if (!/^[0-9a-f]{16}$/u.test(prefixDigest)) throw new TypeError("Invalid rows digest");
813
+ const hash = BigInt.asUintN(
814
+ 64,
815
+ BigInt(`0x${prefixDigest}`) * pow64(ROW_SEQUENCE_BASE, suffix.length) +
816
+ BigInt(`0x${hashTerminalReplicaRows(suffix)}`),
817
+ );
818
+ return hash.toString(16).padStart(16, "0");
819
+ }
820
+
821
+ /**
822
+ * H(B) from H(A ++ B) and A: the digest left after dropping the oldest rows
823
+ * A of a rows sequence of `remaining` + |A| rows. H(A ++ B) = H(A)·P^|B| + H(B).
824
+ */
825
+ export function dropTerminalReplicaRowsDigestPrefix(
826
+ digest: string,
827
+ prefix: readonly TerminalReplicaRow[],
828
+ remaining: number,
829
+ ): string {
830
+ if (!/^[0-9a-f]{16}$/u.test(digest)) throw new TypeError("Invalid rows digest");
831
+ const hash = BigInt.asUintN(
832
+ 64,
833
+ BigInt(`0x${digest}`) -
834
+ BigInt(`0x${hashTerminalReplicaRows(prefix)}`) * pow64(ROW_SEQUENCE_BASE, remaining),
835
+ );
836
+ return hash.toString(16).padStart(16, "0");
837
+ }
838
+
839
+ /** H(A) from H(A ++ B) and B: P is odd, so P^|B| is invertible mod 2^64. */
840
+ export function popTerminalReplicaRowsDigestSuffix(
841
+ digest: string,
842
+ suffix: readonly TerminalReplicaRow[],
843
+ ): string {
844
+ if (!/^[0-9a-f]{16}$/u.test(digest)) throw new TypeError("Invalid rows digest");
845
+ const hash = BigInt.asUintN(
846
+ 64,
847
+ (BigInt(`0x${digest}`) - BigInt(`0x${hashTerminalReplicaRows(suffix)}`)) *
848
+ pow64(ROW_SEQUENCE_BASE_INVERSE, suffix.length),
849
+ );
850
+ return hash.toString(16).padStart(16, "0");
851
+ }
852
+
785
853
  function hashTerminalReplicaSnapshotProfiled(
786
854
  snapshot: TerminalReplicaSnapshot,
787
855
  profile?: MutableTerminalReplicaApplyProfile,
788
856
  instrumentation?: TerminalReplicaApplyOptions["instrumentation"],
857
+ historyDigest?: string,
789
858
  ): string {
790
859
  // Cross-language Merkle stream: each immutable row is FNV-1a over the
791
860
  // type-tagged UTF-8 cell stream, then the snapshot hashes fixed-order row
@@ -797,7 +866,7 @@ function hashTerminalReplicaSnapshotProfiled(
797
866
  snapshot.cols,
798
867
  snapshot.rows,
799
868
  hashTerminalReplicaRows(snapshot.grid, profile, instrumentation),
800
- hashTerminalReplicaRows(snapshot.history, profile, instrumentation),
869
+ historyDigest ?? hashTerminalReplicaRows(snapshot.history, profile, instrumentation),
801
870
  snapshot.cursor,
802
871
  snapshot.modes,
803
872
  snapshot.placements,
@@ -0,0 +1,30 @@
1
+ import { ownerBearerMatches } from "./owner-authority.js";
2
+ /**
3
+ * How long an owner-authenticated HTTP connection may sit idle before the
4
+ * daemon closes it. Node's default is 5 s, so a native app that paused for
5
+ * longer found its proven connection gone; over SSH every replacement costs
6
+ * a channel open and an identity proof (attach-rtt). The app keeps an idle
7
+ * connection for at most 60 s, below this.
8
+ */
9
+ export const OWNER_KEEP_ALIVE_MS = 65_000;
10
+ /**
11
+ * After a response to the owner bearer, keep that connection open for
12
+ * `timeoutMs` while idle. Every other connection keeps Node's default.
13
+ * Node arms its own keep-alive timer when the response finishes; this runs
14
+ * after it and replaces the bound for this socket only. The next request on
15
+ * the socket clears the timer as usual.
16
+ */
17
+ export function ownerKeepAlive(ownerToken, timeoutMs = OWNER_KEEP_ALIVE_MS) {
18
+ return async (c, next) => {
19
+ const bindings = c.env;
20
+ const outgoing = bindings?.outgoing;
21
+ const socket = bindings?.incoming?.socket;
22
+ if (outgoing && socket && ownerBearerMatches(c.req.header("Authorization"), ownerToken)) {
23
+ outgoing.once("finish", () => {
24
+ if (!socket.destroyed && outgoing.shouldKeepAlive)
25
+ socket.setTimeout(timeoutMs);
26
+ });
27
+ }
28
+ await next();
29
+ };
30
+ }
@@ -68,6 +68,7 @@ import { mountWorkspaceResourceRoutes } from "./resources/workspace-resource-rou
68
68
  import { mountFleetResourceRoute } from "./resources/fleet-resource-route.js";
69
69
  import { mountWorkspaceMissionsRoute } from "./resources/workspace-missions-route.js";
70
70
  import { ownerAuthorityGate, requireOwnerAuthority } from "./owner-authority.js";
71
+ import { ownerKeepAlive } from "./owner-keep-alive.js";
71
72
  import { mountDiagnosticsRoute } from "./diagnostics.js";
72
73
  import { mountStartupReadinessRoute, } from "./resources/startup-readiness-route.js";
73
74
  import { readWidgetAsset } from "../lib/widget-asset-store.js";
@@ -338,6 +339,8 @@ export function createApp(options = {}) {
338
339
  const app = new Hono();
339
340
  // Allow cross-origin (Next.js dashboard, Tailscale, etc.)
340
341
  app.use("/*", cors());
342
+ // An owner connection stays open while idle for longer than Node's 5 s.
343
+ app.use("/*", ownerKeepAlive(options.remoteAccess?.ownerToken ?? null));
341
344
  if (options.tmuxServerOwners) {
342
345
  mountAutomationRoutes(app, {
343
346
  ownerToken: options.remoteAccess?.ownerToken ?? null,
@@ -0,0 +1,51 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * One request that opens a session, reads its inventory and issues its stream
4
+ * (attach-rtt). Before it the app sent three: open, inventory, issue. The app
5
+ * still checks the answer: it applies its own window rule to the returned
6
+ * inventory and uses the issued stream only when the daemon chose the same.
7
+ *
8
+ * `issue` is the body of an ordinary pane-stream issue request without the
9
+ * workspace name, the panes and the window, which only the daemon knows here.
10
+ */
11
+ export const TmuxServerAttachRequestSchemaZ = z
12
+ .object({
13
+ version: z.literal(1),
14
+ preferredPane: z.string().min(1).max(128).nullable(),
15
+ maxPanes: z.number().int().min(1).max(256),
16
+ issue: z
17
+ .object({
18
+ expectedDaemonInstanceId: z.uuid(),
19
+ stream: z.record(z.string(), z.unknown()),
20
+ })
21
+ .catchall(z.unknown()),
22
+ })
23
+ .strict();
24
+ /**
25
+ * The app's rule (browser_native_local_window.rs `scope`), here so the open
26
+ * and the issue can be one request: a session that fits streams whole;
27
+ * otherwise the window holding the preferred pane (else the active one) when
28
+ * it fits, else the active one, else the first in tmux order that fits. No
29
+ * selection when there is no pane or nothing fits: the app decides then.
30
+ */
31
+ export function chooseAttachSelection(inventory, preferredPane, maxPanes) {
32
+ const panes = inventory.semanticPaneIds;
33
+ if (panes.length === 0)
34
+ return null;
35
+ let semanticWindowId = null;
36
+ let chosen = panes;
37
+ if (panes.length > maxPanes) {
38
+ const fits = (window) => window !== undefined && window.semanticPaneIds.length <= maxPanes;
39
+ const active = inventory.windows.find((window) => window.active);
40
+ const wanted = (preferredPane !== null
41
+ ? inventory.windows.find((window) => window.semanticPaneIds.includes(preferredPane))
42
+ : undefined) ?? active;
43
+ const window = [wanted, active].find(fits) ?? inventory.windows.find(fits);
44
+ if (!window)
45
+ return null;
46
+ semanticWindowId = window.semanticWindowId;
47
+ chosen = window.semanticPaneIds;
48
+ }
49
+ const selectedPane = preferredPane !== null && chosen.includes(preferredPane) ? preferredPane : chosen[0];
50
+ return { semanticWindowId, panes: chosen, selectedPane };
51
+ }
@@ -19,6 +19,7 @@ import { WorkspacePaneCreationError } from "../lib/workspace-pane-creation.js";
19
19
  import { ownerBearerMatches } from "./owner-authority.js";
20
20
  import { logger } from "../lib/log.js";
21
21
  import { mountPaneStreamIssueRoute } from "./pane-stream-issue.js";
22
+ import { chooseAttachSelection, TmuxServerAttachRequestSchemaZ } from "./tmux-server-attach.js";
22
23
  import { projectTerminalRuntimeInventory, projectTerminalRuntimeInventoryV2, } from "./resources/terminal-runtime-inventory.js";
23
24
  /** Total raw favicon bytes one version 2 sessions response may carry. */
24
25
  export const SESSIONS_RESOURCE_FAVICON_BUDGET_BYTES = 512 * 1024;
@@ -204,6 +205,83 @@ export function mountTmuxServerRoutes(app, options) {
204
205
  const result = await options.owners.withOwner(server, (owner) => owner.openSession(workspaceSchema.parse(c.req.param("liveSessionId"))));
205
206
  return c.json({ version: 1, server, ...result });
206
207
  }));
208
+ // attach-rtt: open, inventory and issue in one round trip. The stream is
209
+ // issued through the ordinary issue route with this request's headers, so
210
+ // it is checked exactly as a separate issue request would be.
211
+ app.post(`${scoped}/sessions/:liveSessionId/attach`, route(async (c) => {
212
+ const server = scope(c);
213
+ const liveSessionId = workspaceSchema.parse(c.req.param("liveSessionId"));
214
+ const request = TmuxServerAttachRequestSchemaZ.parse(await boundedJson(c.req.raw));
215
+ // The issue below checks the same, but only after the open: refuse a
216
+ // request for another generation before it can promote anything.
217
+ if (request.issue.expectedDaemonInstanceId !== server.generation ||
218
+ c.req.header("X-Tmux-Ide-Expected-Daemon-Instance-Id") !== server.generation)
219
+ throw new TmuxServerScopeError("stale-generation");
220
+ const result = await options.owners.withOwner(server, async (owner) => {
221
+ const opened = await owner.openSession(liveSessionId);
222
+ const workspace = owner.workspaceRegistry.get(opened.workspaceName);
223
+ if (!workspace || opened.liveSessionId !== liveSessionId)
224
+ throw new TmuxServerScopeError("stale-generation");
225
+ const snapshot = await owner.terminalInventoryRuntime.discoverTerminalRuntimeSession(workspace.sessionName, c.req.raw.signal);
226
+ if (!snapshot)
227
+ return null;
228
+ const inventory = projectTerminalRuntimeInventoryV2(snapshot, 0);
229
+ const selection = chooseAttachSelection(inventory, request.preferredPane, request.maxPanes);
230
+ if (!selection)
231
+ return { kind: "attached", opened, inventory, selection, issue: null };
232
+ // The window is the daemon's to choose, never the client's.
233
+ const stream = { ...request.issue.stream };
234
+ delete stream.semanticWindowId;
235
+ const body = {
236
+ ...request.issue,
237
+ stream: {
238
+ ...stream,
239
+ workspaceName: opened.workspaceName,
240
+ panes: selection.panes,
241
+ ...(selection.semanticWindowId ? { semanticWindowId: selection.semanticWindowId } : {}),
242
+ },
243
+ };
244
+ const issueApp = new Hono();
245
+ mountPaneStreamIssueRoute(issueApp, {
246
+ daemonInstanceId: server.generation,
247
+ ownerToken: options.ownerToken,
248
+ workspaceRegistry: owner.workspaceRegistry,
249
+ backend: owner.paneStreamRuntime.coordinator,
250
+ });
251
+ const url = new URL(c.req.url);
252
+ url.pathname = PANE_STREAM_ISSUE_PATH;
253
+ url.search = "";
254
+ const headers = new Headers(c.req.raw.headers);
255
+ headers.delete("Content-Length");
256
+ headers.set("Content-Type", "application/json");
257
+ const issued = await issueApp.request(new Request(url, { method: "POST", headers, body: JSON.stringify(body) }));
258
+ // The issue route answers a refused issue as 200 with an error
259
+ // envelope, which goes back in `issue` with the open and inventory
260
+ // (the app then issues again). A non-200 is an auth or body refusal.
261
+ if (issued.status !== 200)
262
+ return { kind: "refused", refused: issued };
263
+ return {
264
+ kind: "attached",
265
+ opened,
266
+ inventory,
267
+ selection,
268
+ issue: (await issued.json()),
269
+ };
270
+ });
271
+ if (!result)
272
+ return c.json({ error: { code: "workspace-not-found" } }, 404);
273
+ if (result.kind === "refused")
274
+ return result.refused;
275
+ return c.json({
276
+ version: 1,
277
+ server,
278
+ workspaceName: result.opened.workspaceName,
279
+ liveSessionId,
280
+ inventory: result.inventory,
281
+ selection: result.selection,
282
+ issue: result.issue,
283
+ });
284
+ }));
207
285
  app.get(`${scoped}/sessions`, route(async (c) => {
208
286
  const server = scope(c);
209
287
  // #806: version 3 is version 2 plus the largest window's pane count.
@@ -17,6 +17,7 @@ import { findCompiledTui, hasDevelopmentTuiSource, isBunAvailable } from "./tui/
17
17
  import { claudeSettingsPath } from "./tui/integrations/claude.js";
18
18
  import { readNotificationPrefs, resolveNativeMacosNotifierPath } from "./tui/chrome/notify.js";
19
19
  import { resolveConfig } from "./lib/resolved-config.js";
20
+ import { MINIMUM_NODE_MAJOR, isSupportedNodeVersion } from "./lib/node-requirement.js";
20
21
  import { collectDaemonProvenanceReport, } from "./lib/daemon-provenance.js";
21
22
  /**
22
23
  * PURE — the "agent integrations" doctor rows, one per DISCOVERED agent (absent
@@ -387,12 +388,11 @@ export function tmuxServerSocketRow(environment, uid) {
387
388
  };
388
389
  }
389
390
  export function nodeVersionRow(version) {
390
- const major = Number(version.split(".")[0]);
391
- const pass = Number.isInteger(major) && major >= 20;
391
+ const pass = isSupportedNodeVersion(version);
392
392
  return {
393
- label: "Node.js ≥ 20",
393
+ label: `Node.js ≥ ${MINIMUM_NODE_MAJOR}`,
394
394
  pass,
395
- detail: pass ? `v${version}` : `Node ${version} (need ≥ 20)`,
395
+ detail: pass ? `v${version}` : `Node ${version} (need ≥ ${MINIMUM_NODE_MAJOR})`,
396
396
  optional: false,
397
397
  };
398
398
  }
@@ -131,6 +131,11 @@ function appThemeOverrideProvenance(theme, status, glyphs) {
131
131
  * back to its default, so partial and garbage configs both resolve to a complete,
132
132
  * well-typed {@link AppConfig}. Never throws.
133
133
  */
134
+ /** `theme.light` / `theme.dark`, when the id names a preset of that appearance. */
135
+ function systemSide(value, appearance) {
136
+ const preset = findVisualThemePreset(value);
137
+ return preset?.appearance === appearance ? { [appearance]: preset.id } : {};
138
+ }
134
139
  export function parseAppConfig(input) {
135
140
  const D = DEFAULT_APP_CONFIG;
136
141
  const root = asObject(input);
@@ -164,6 +169,8 @@ export function parseAppConfig(input) {
164
169
  automaticContrast: pickBool(theme.automaticContrast, D.theme.automaticContrast),
165
170
  mode: pickChoice(theme.mode, ["dark", "light", "system"], findVisualThemePreset(theme.preset)?.appearance ?? D.theme.mode),
166
171
  ...(findVisualThemePreset(theme.preset) ? { preset: String(theme.preset) } : {}),
172
+ ...systemSide(theme.light, "light"),
173
+ ...systemSide(theme.dark, "dark"),
167
174
  accent: pickString(theme.accent, D.theme.accent),
168
175
  muted: pickString(theme.muted, D.theme.muted),
169
176
  fg: pickString(theme.fg, D.theme.fg),
@@ -0,0 +1,20 @@
1
+ /** The oldest Node.js major an npm install of tmux-ide supports (package.json `engines`). */
2
+ export const MINIMUM_NODE_MAJOR = 24;
3
+ /** True when `version` (as in `process.versions.node`) is new enough. */
4
+ export function isSupportedNodeVersion(version) {
5
+ const major = Number(version.split(".")[0]);
6
+ return Number.isInteger(major) && major >= MINIMUM_NODE_MAJOR;
7
+ }
8
+ /**
9
+ * The message the CLI prints before exiting on an unsupported Node.js, or null
10
+ * when the runtime is supported. Bun (dev runs, compiled surfaces) is exempt.
11
+ */
12
+ export function unsupportedNodeMessage(versions) {
13
+ if (versions.bun !== undefined || versions.node === undefined)
14
+ return null;
15
+ if (isSupportedNodeVersion(versions.node))
16
+ return null;
17
+ return (`tmux-ide needs Node.js ${MINIMUM_NODE_MAJOR} or newer; this is Node.js ${versions.node}.\n` +
18
+ `Upgrade Node.js, or use the installer, which brings its own runtime:\n` +
19
+ ` curl -fsSL https://tmux-ide.com/install.sh | sh\n`);
20
+ }
@@ -0,0 +1,8 @@
1
+ // Imported first by bin/cli.ts so an unsupported Node.js stops with a clear
2
+ // message before any command code runs.
3
+ import { unsupportedNodeMessage } from "./node-requirement.js";
4
+ const message = unsupportedNodeMessage(process.versions);
5
+ if (message !== null) {
6
+ process.stderr.write(message);
7
+ process.exit(1);
8
+ }
@@ -4,7 +4,7 @@ import { WorkspaceCatalogLiveSessionIdSchemaZ } from "@tmux-ide/contracts";
4
4
  import { liveSessionIdForNativeIdentity } from "../terminal/protocol/live-session-identity.js";
5
5
  import { fleetSessionIdForName } from "../command-center/resources/fleet-catalog.js";
6
6
  import { isVisibleFleetSession } from "../command-center/discovery.js";
7
- import { WorkspacePromotionAuthority } from "./workspace-promotion.js";
7
+ import { ADOPTED_OPTION, hasValidPaneStamp, SEMANTIC_PANE_OPTION, SEMANTIC_WINDOW_OPTION, WorkspacePromotionAuthority, } from "./workspace-promotion.js";
8
8
  import { shellEscape } from "./shell.js";
9
9
  /** Owner-local bounded admission; all native IO must already fence the server generation. */
10
10
  export function createNativeTmuxSessionOpener(options) {
@@ -18,28 +18,54 @@ export function createNativeTmuxSessionOpener(options) {
18
18
  };
19
19
  const open = async (liveSessionId, observed) => {
20
20
  assertOpen();
21
+ // One row per pane: the session's identity, whether it is adopted, and
22
+ // each window's and pane's stamp. tmux rejects tabs in session names, so
23
+ // the name is the last field; a pane stamp with a tab is invalid anyway.
21
24
  const records = await options.run([
22
- "list-sessions",
25
+ "list-panes",
26
+ "-a",
23
27
  "-F",
24
- "#{pid}\t#{session_id}\t#{session_created}\t#{session_name}",
28
+ `#{pid}\t#{session_id}\t#{session_created}\t#{${ADOPTED_OPTION}}\t#{${SEMANTIC_WINDOW_OPTION}}\t#{${SEMANTIC_PANE_OPTION}}\t#{session_name}`,
25
29
  ]);
26
- // The final field is an exact session identity; spaces are valid name bytes.
27
- const matches = records
30
+ const rows = records
28
31
  .replace(/\n+$/u, "")
29
32
  .split("\n")
30
33
  .map((line) => line.split("\t"))
31
- .filter(([pid, id, created, name]) => pid &&
32
- /^\d+$/.test(pid) &&
33
- id &&
34
+ .filter((fields) => fields.length >= 7)
35
+ .map((fields) => ({
36
+ // A tab can only come from a window or pane stamp: such a row never
37
+ // takes the fast path below.
38
+ exact: fields.length === 7,
39
+ pid: fields[0],
40
+ id: fields[1],
41
+ created: fields[2],
42
+ adopted: fields[3],
43
+ window: fields.slice(4, -2).join("\t"),
44
+ pane: fields.at(-2),
45
+ name: fields.at(-1),
46
+ }))
47
+ .filter(({ pid, id, created, name }) => /^\d+$/.test(pid) &&
34
48
  /^\$\d+$/.test(id) &&
35
- created &&
36
49
  /^\d+$/.test(created) &&
37
50
  name &&
38
51
  isVisibleFleetSession(name) &&
39
52
  liveSessionIdForNativeIdentity(pid, id, created) === liveSessionId);
40
- if (matches.length !== 1)
53
+ if (new Set(rows.map((row) => row.id)).size !== 1)
41
54
  throw new Error("Selected live tmux session is no longer available");
42
- const [, nativeSessionId, created, name] = matches[0];
55
+ const { id: nativeSessionId, created, name } = rows[0];
56
+ // Re-opening a session that an earlier open already finished changes
57
+ // nothing: it is adopted, has exactly one durable alias, and every window
58
+ // and pane already carries a stamp. Promotion would only read it again
59
+ // (seven tmux commands), so skip it. Anything else promotes as before,
60
+ // which also stamps panes split since the last open.
61
+ const aliases = options.registry.list().filter((entry) => entry.sessionName === name);
62
+ if (!observed &&
63
+ aliases.length === 1 &&
64
+ !options.registry.isVolatile(aliases[0].name) &&
65
+ rows.every((row) => row.exact && row.adopted === "1" && row.window.length > 0 && hasValidPaneStamp(row.pane))) {
66
+ assertOpen();
67
+ return { workspaceName: aliases[0].name, liveSessionId };
68
+ }
43
69
  // Each command checks the exact native session on the server accepting it.
44
70
  // A name-only validation followed by stamping would cross a session replacement.
45
71
  const run = async (args) => {
@@ -62,7 +88,7 @@ export function createNativeTmuxSessionOpener(options) {
62
88
  return output;
63
89
  };
64
90
  const agent = observed
65
- ? await captureAgentAdmission(run, { id: nativeSessionId, name: name }, observed)
91
+ ? await captureAgentAdmission(run, { id: nativeSessionId, name }, observed)
66
92
  : null;
67
93
  await agent?.verify(false);
68
94
  const promotion = new WorkspacePromotionAuthority({
@@ -18,12 +18,12 @@ const MAX_TMUX_OUTPUT_BYTES = 128 * 1024;
18
18
  // is proven, immediately before registry admission. The promotion marker is
19
19
  // DELIBERATELY distinct from the m32 open marker so a promoted session is a
20
20
  // separate provenance.
21
- const ADOPTED_OPTION = "@tmux_ide_adopted";
21
+ export const ADOPTED_OPTION = "@tmux_ide_adopted";
22
22
  const SESSION_PROMOTED_MARKER_OPTION = "@tmux_ide_workspace_promoted_v1";
23
23
  const SESSION_WORKSPACE_OPTION = "@tmux_ide_workspace_name";
24
24
  const SESSION_OPERATION_OPTION = "@tmux_ide_workspace_promote_operation";
25
- const SEMANTIC_PANE_OPTION = "@tmux_ide_pane_id";
26
- const SEMANTIC_WINDOW_OPTION = "@tmux_ide_window_id";
25
+ export const SEMANTIC_PANE_OPTION = "@tmux_ide_pane_id";
26
+ export const SEMANTIC_WINDOW_OPTION = "@tmux_ide_window_id";
27
27
  // Distinctive multi-char field/line delimiters — collision-resistant against
28
28
  // arbitrary pane paths, window names and user-controlled `@agent_*` values,
29
29
  // matching the fleet-discovery idiom. A value carrying a newline splits into a
@@ -142,7 +142,7 @@ function isInternalSession(name) {
142
142
  }
143
143
  const VALID_SEMANTIC_PANE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
144
144
  const RESERVED_DISCOVERED_PREFIX = "terminal.discovered.";
145
- function hasValidPaneStamp(value) {
145
+ export function hasValidPaneStamp(value) {
146
146
  return (value.length > 0 &&
147
147
  value.length <= 128 &&
148
148
  VALID_SEMANTIC_PANE_ID.test(value) &&
@@ -21,9 +21,9 @@
21
21
  <key>CFBundlePackageType</key>
22
22
  <string>APPL</string>
23
23
  <key>CFBundleShortVersionString</key>
24
- <string>2.9.26</string>
24
+ <string>2.9.27</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.26</string>
26
+ <string>2.9.27</string>
27
27
  <key>LSMinimumSystemVersion</key>
28
28
  <string>11.0</string>
29
29
  <key>LSUIElement</key>
@@ -10,7 +10,7 @@
10
10
  </data>
11
11
  <key>Resources/Assets.car</key>
12
12
  <data>
13
- vCGQEYGoc/hxKRik4536rZeOyzI=
13
+ 7/c5M7HIcG2L8zbGq7f5hfd3b+k=
14
14
  </data>
15
15
  </dict>
16
16
  <key>files2</key>
@@ -26,7 +26,7 @@
26
26
  <dict>
27
27
  <key>hash2</key>
28
28
  <data>
29
- YpwfBnJnj+KlpeQ27JX9G6+7YYKfAwTW97PEFohYyuE=
29
+ lInayHTe0NipJWAju3yVQdmkOMR8qipP8gNMy+AgXt4=
30
30
  </data>
31
31
  </dict>
32
32
  </dict>