tmux-ide 2.9.16 → 2.9.18

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 (40) hide show
  1. package/bin/cli.js +913 -367
  2. package/package.json +1 -1
  3. package/packages/core/src/terminal-fnv64-wasm.ts +8 -1
  4. package/packages/core/src/terminal-replica-hash-cache.ts +108 -1
  5. package/packages/core/src/terminal-replica.ts +14 -0
  6. package/packages/daemon/dist/command-center/discovery.js +39 -6
  7. package/packages/daemon/dist/doctor.js +101 -2
  8. package/packages/daemon/dist/lib/catalog-fleet-read.js +10 -0
  9. package/packages/daemon/dist/lib/daemon-embed.js +18 -4
  10. package/packages/daemon/dist/lib/daemon-service.js +13 -5
  11. package/packages/daemon/dist/lib/native-split-capability.js +20 -0
  12. package/packages/daemon/dist/lib/tmux-server-owner.js +2 -1
  13. package/packages/daemon/dist/lib/tmux-server-owners.js +20 -1
  14. package/packages/daemon/dist/lib/tui-binary.js +83 -17
  15. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  16. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/AppIcon.icns +0 -0
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +4 -4
  20. package/packages/daemon/dist/terminal/mirror/control-channel.js +3 -2
  21. package/packages/daemon/dist/terminal/mirror/mirror-service.js +47 -11
  22. package/packages/daemon/dist/terminal/mirror/session-channel.js +19 -4
  23. package/packages/daemon/dist/terminal/mirror/window-split-authority.js +9 -2
  24. package/packages/daemon/dist/terminal/protocol/native-split-resize.js +16 -16
  25. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +194 -0
  26. package/packages/daemon/src/command-center/discovery.ts +72 -7
  27. package/packages/daemon/src/doctor.ts +104 -2
  28. package/packages/daemon/src/lib/catalog-fleet-read.ts +40 -0
  29. package/packages/daemon/src/lib/daemon-embed.ts +31 -12
  30. package/packages/daemon/src/lib/daemon-service.ts +17 -4
  31. package/packages/daemon/src/lib/native-split-capability.ts +21 -0
  32. package/packages/daemon/src/lib/tmux-server-owner.ts +2 -0
  33. package/packages/daemon/src/lib/tmux-server-owners.ts +17 -1
  34. package/packages/daemon/src/lib/tui-binary.ts +114 -22
  35. package/packages/daemon/src/terminal/mirror/control-channel.ts +3 -2
  36. package/packages/daemon/src/terminal/mirror/mirror-service.ts +51 -12
  37. package/packages/daemon/src/terminal/mirror/session-channel.ts +23 -4
  38. package/packages/daemon/src/terminal/mirror/window-split-authority.ts +15 -4
  39. package/packages/daemon/src/terminal/protocol/native-split-resize.ts +16 -16
  40. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +268 -0
@@ -26,8 +26,18 @@ export const MIN_TUI_BINARY_BYTES = 10 * 1024 * 1024;
26
26
  /** Hard download/decompression ceilings: release binaries are currently ~70MB. */
27
27
  export const MAX_TUI_COMPRESSED_BYTES = 128 * 1024 * 1024;
28
28
  export const MAX_TUI_BINARY_BYTES = 256 * 1024 * 1024;
29
- export const TUI_DOWNLOAD_TIMEOUT_MS = 30_000;
29
+ /** Abort a request when no bytes arrive for this long; a slow transfer never trips it. */
30
+ export const TUI_DOWNLOAD_STALL_TIMEOUT_MS = 30_000;
31
+ /** One budget for the manifest, the binary, and every retry: ~145 KB/s at the size ceiling. */
32
+ export const TUI_DOWNLOAD_TOTAL_TIMEOUT_MS = 15 * 60_000;
33
+ /** Attempts per file; only transient failures are retried. */
34
+ export const TUI_DOWNLOAD_MAX_ATTEMPTS = 3;
35
+ export const TUI_DOWNLOAD_RETRY_DELAY_MS = 1_000;
30
36
  const MAX_CHECKSUM_MANIFEST_BYTES = 4 * 1024;
37
+ /** A second installer says why it is quiet once the wait is longer than a lock handover. */
38
+ const TUI_DOWNLOAD_LOCK_NOTICE_MS = 2_000;
39
+ /** Lets a lock waiter outlast the holder's verify and install after its download budget. */
40
+ const TUI_DOWNLOAD_LOCK_MARGIN_MS = 5_000;
31
41
  const SUPPORTED = {
32
42
  "darwin-arm64": "darwin-arm64",
33
43
  "linux-x64": "linux-x64",
@@ -109,6 +119,9 @@ export function findDownloadedTui(version = getCurrentVersion(), options = {}) {
109
119
  purgeCachedBinary(path);
110
120
  return null;
111
121
  }
122
+ /** A failure a retry cannot fix: the release asset is missing or breaks a hard limit. */
123
+ class PermanentDownloadError extends Error {
124
+ }
112
125
  function checksumPath(path) {
113
126
  return `${path}.sha256`;
114
127
  }
@@ -198,32 +211,53 @@ function purgeCachedBinary(path) {
198
211
  }
199
212
  }
200
213
  }
201
- async function readBoundedResponse(fetchImpl, url, maxBytes, timeoutMs) {
214
+ function isTransientHttpStatus(status) {
215
+ return status === 408 || status === 429 || status >= 500;
216
+ }
217
+ async function readBoundedResponse(fetchImpl, url, maxBytes, policy) {
202
218
  const controller = new AbortController();
203
- const timer = setTimeout(() => controller.abort(), timeoutMs);
219
+ let total = 0;
220
+ let timeoutMessage = null;
221
+ const abortWith = (message) => () => {
222
+ timeoutMessage = message();
223
+ controller.abort();
224
+ };
225
+ const overallTimer = setTimeout(abortWith(() => `download did not finish within ${policy.totalTimeoutMs}ms`), Math.max(0, policy.deadline - Date.now()));
226
+ const onStall = abortWith(() => `download stalled: no data for ${policy.stallTimeoutMs}ms after ${total} bytes`);
227
+ let stallTimer = setTimeout(onStall, policy.stallTimeoutMs);
228
+ const markProgress = () => {
229
+ clearTimeout(stallTimer);
230
+ stallTimer = setTimeout(onStall, policy.stallTimeoutMs);
231
+ };
204
232
  try {
205
233
  const response = await fetchImpl(url, { signal: controller.signal });
206
234
  if (!response.ok) {
207
- throw new Error(`HTTP ${response.status} ${response.statusText}`);
235
+ const message = `HTTP ${response.status} ${response.statusText}`;
236
+ if (isTransientHttpStatus(response.status))
237
+ throw new Error(message);
238
+ throw new PermanentDownloadError(message);
208
239
  }
240
+ markProgress();
209
241
  const declaredLength = Number(response.headers.get("content-length"));
210
242
  if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
211
- throw new Error(`declared size ${declaredLength} exceeds ${maxBytes} bytes`);
243
+ throw new PermanentDownloadError(`declared size ${declaredLength} exceeds ${maxBytes} bytes`);
212
244
  }
213
245
  if (!response.body)
214
246
  throw new Error("response has no body");
215
247
  const chunks = [];
216
- let total = 0;
217
248
  const reader = response.body.getReader();
218
249
  try {
219
250
  while (true) {
220
251
  const { done, value } = await reader.read();
221
252
  if (done)
222
253
  break;
254
+ if (value.byteLength === 0)
255
+ continue;
256
+ markProgress();
223
257
  total += value.byteLength;
224
258
  if (total > maxBytes) {
225
259
  await reader.cancel();
226
- throw new Error(`download exceeds ${maxBytes} bytes`);
260
+ throw new PermanentDownloadError(`download exceeds ${maxBytes} bytes`);
227
261
  }
228
262
  chunks.push(Buffer.from(value));
229
263
  }
@@ -234,13 +268,33 @@ async function readBoundedResponse(fetchImpl, url, maxBytes, timeoutMs) {
234
268
  return Buffer.concat(chunks, total);
235
269
  }
236
270
  catch (error) {
237
- if (controller.signal.aborted) {
238
- throw new Error(`download timed out after ${timeoutMs}ms`, { cause: error });
239
- }
271
+ if (timeoutMessage)
272
+ throw new Error(timeoutMessage, { cause: error });
240
273
  throw error;
241
274
  }
242
275
  finally {
243
- clearTimeout(timer);
276
+ clearTimeout(overallTimer);
277
+ clearTimeout(stallTimer);
278
+ // Releases the connection of any response whose body was not fully read.
279
+ controller.abort();
280
+ }
281
+ }
282
+ async function readWithRetries(fetchImpl, url, maxBytes, policy, log) {
283
+ for (let attempt = 1;; attempt++) {
284
+ try {
285
+ return await readBoundedResponse(fetchImpl, url, maxBytes, policy);
286
+ }
287
+ catch (error) {
288
+ const delayMs = policy.retryDelayMs * attempt;
289
+ if (error instanceof PermanentDownloadError ||
290
+ attempt >= policy.maxAttempts ||
291
+ Date.now() + delayMs >= policy.deadline) {
292
+ throw error;
293
+ }
294
+ const message = error instanceof Error ? error.message : String(error);
295
+ log(`download attempt ${attempt}/${policy.maxAttempts} failed (${message}); retrying`);
296
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
297
+ }
244
298
  }
245
299
  }
246
300
  /**
@@ -270,10 +324,11 @@ export async function downloadTuiBinary(opts = {}) {
270
324
  minBinaryBytes: opts.limits?.minBinaryBytes ?? MIN_TUI_BINARY_BYTES,
271
325
  maxCompressedBytes: opts.limits?.maxCompressedBytes ?? MAX_TUI_COMPRESSED_BYTES,
272
326
  maxBinaryBytes: opts.limits?.maxBinaryBytes ?? MAX_TUI_BINARY_BYTES,
273
- timeoutMs: opts.timeoutMs ?? TUI_DOWNLOAD_TIMEOUT_MS,
274
327
  };
328
+ const totalTimeoutMs = opts.totalTimeoutMs ?? TUI_DOWNLOAD_TOTAL_TIMEOUT_MS;
275
329
  mkdirSync(dirname(dest), { recursive: true });
276
- const releaseLock = await acquirePrivateOperationLock(downloadLockPath(dest), limits.timeoutMs * 2 + 5_000);
330
+ const lockNotice = setTimeout(() => log("waiting for another tmux-ide download of this version to finish"), TUI_DOWNLOAD_LOCK_NOTICE_MS);
331
+ const releaseLock = await acquirePrivateOperationLock(downloadLockPath(dest), totalTimeoutMs + TUI_DOWNLOAD_LOCK_MARGIN_MS).finally(() => clearTimeout(lockNotice));
277
332
  const suffix = `${process.pid}.${randomUUID()}.tmp`;
278
333
  const binaryTmp = `${dest}.${suffix}`;
279
334
  const checksumTmp = `${checksumPath(dest)}.${suffix}`;
@@ -283,17 +338,28 @@ export async function downloadTuiBinary(opts = {}) {
283
338
  return { path: dest, bytes: cached.bytes };
284
339
  purgeCachedBinary(dest);
285
340
  const fetchImpl = opts.fetch ?? globalThis.fetch;
341
+ // Starts after the lock so the budget matches what a lock waiter allows for.
342
+ const policy = {
343
+ stallTimeoutMs: opts.stallTimeoutMs ?? TUI_DOWNLOAD_STALL_TIMEOUT_MS,
344
+ deadline: Date.now() + totalTimeoutMs,
345
+ totalTimeoutMs,
346
+ maxAttempts: opts.maxAttempts ?? TUI_DOWNLOAD_MAX_ATTEMPTS,
347
+ retryDelayMs: opts.retryDelayMs ?? TUI_DOWNLOAD_RETRY_DELAY_MS,
348
+ };
286
349
  log(`downloading checksum manifest ${checksumUrl}`);
287
350
  let manifestBytes;
288
351
  let gz;
289
352
  try {
290
- manifestBytes = await readBoundedResponse(fetchImpl, checksumUrl, MAX_CHECKSUM_MANIFEST_BYTES, limits.timeoutMs);
291
- gz = await readBoundedResponse(fetchImpl, url, limits.maxCompressedBytes, limits.timeoutMs);
353
+ manifestBytes = await readWithRetries(fetchImpl, checksumUrl, MAX_CHECKSUM_MANIFEST_BYTES, policy, log);
354
+ log(`downloading ${url}`);
355
+ gz = await readWithRetries(fetchImpl, url, limits.maxCompressedBytes, policy, log);
292
356
  }
293
357
  catch (error) {
294
358
  const message = error instanceof Error ? error.message : String(error);
295
- throw new Error(`could not download the TUI binary and checksum for v${version} (${message}). ` +
296
- `Check that the release published both exact-version assets.`, { cause: error });
359
+ const hint = error instanceof PermanentDownloadError
360
+ ? "Check that the release published both exact-version assets."
361
+ : "Check your network connection, then retry with `tmux-ide update --tui-binary`, or run the installer again if tmux-ide is not installed yet.";
362
+ throw new Error(`could not download the TUI binary and checksum for v${version} (${message}). ${hint}`, { cause: error });
297
363
  }
298
364
  const manifest = parseChecksumManifest(manifestBytes, { version, tag });
299
365
  if (sha256(gz) !== manifest.compressedSha256) {
@@ -21,9 +21,9 @@
21
21
  <key>CFBundlePackageType</key>
22
22
  <string>APPL</string>
23
23
  <key>CFBundleShortVersionString</key>
24
- <string>2.9.16</string>
24
+ <string>2.9.18</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.16</string>
26
+ <string>2.9.18</string>
27
27
  <key>LSMinimumSystemVersion</key>
28
28
  <string>11.0</string>
29
29
  <key>LSUIElement</key>
@@ -6,11 +6,11 @@
6
6
  <dict>
7
7
  <key>Resources/AppIcon.icns</key>
8
8
  <data>
9
- 0kJOhKI63m7RQF/lR1nMjIIiACY=
9
+ /fan3KhjkAUR40oxTxGrk4b03wY=
10
10
  </data>
11
11
  <key>Resources/Assets.car</key>
12
12
  <data>
13
- 80sBn8yzZzR4ZHE3L4qFvRPqA+A=
13
+ naMXi4vqG99WTYshONwauong/wE=
14
14
  </data>
15
15
  </dict>
16
16
  <key>files2</key>
@@ -19,14 +19,14 @@
19
19
  <dict>
20
20
  <key>hash2</key>
21
21
  <data>
22
- YXdi2fa2PvtRaeXueLC7n1If41ofraB5MVZULmdCcC8=
22
+ zDoKzf7n2cp6cQedgfmNiTPwTj+gON7DS7H8ihtNVCE=
23
23
  </data>
24
24
  </dict>
25
25
  <key>Resources/Assets.car</key>
26
26
  <dict>
27
27
  <key>hash2</key>
28
28
  <data>
29
- PKQV15gCKuH8bIwdxGZgHEhWb0Rwq62t/R9Ozfnv/BA=
29
+ uTBb1swtYysiGXnkbPZAsxM01N0Fy1AUrpzAn1zAMvs=
30
30
  </data>
31
31
  </dict>
32
32
  </dict>
@@ -533,14 +533,15 @@ export class ControlChannelCore {
533
533
  }
534
534
  if (event.kind === "error" && sink.index !== sink.state.resultIndex)
535
535
  this.discardedErrors += 1;
536
- if (event.kind === "error" && sink.index === 0) {
536
+ if (event.kind === "error") {
537
+ // tmux drops the failed command's remaining group, so those replies never come.
537
538
  while (this.pending[0]?.kind === "command-list" && this.pending[0].state === sink.state)
538
539
  this.pending.shift();
539
540
  if (!sink.state.settled) {
540
541
  sink.state.settled = true;
541
542
  sink.state.onReply({
542
543
  ok: false,
543
- lines: sink.state.budget || sink.state.resultIndex === 0
544
+ lines: sink.index > 0 || sink.state.budget || sink.state.resultIndex === 0
544
545
  ? sink.state.lines
545
546
  : sink.state.leadingErrorLines,
546
547
  });
@@ -1,6 +1,8 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { setTimeout as waitForPublication } from "node:timers/promises";
2
3
  import { WindowSplitResizeTargetSchemaZ, } from "@tmux-ide/contracts";
3
4
  import { WindowSplitAuthority, WindowSplitLayoutUnavailable } from "./window-split-authority.js";
5
+ import { resizeStockSplit } from "../protocol/stock-split-resize.js";
4
6
  import { SharedWindowIndex } from "./shared-window-index.js";
5
7
  import { RegisteredWindowGuard } from "./registered-window-guard.js";
6
8
  import { accessSync, constants, realpathSync, statSync } from "node:fs";
@@ -237,9 +239,18 @@ export class MirrorService {
237
239
  catch {
238
240
  /* Unavailable owner. */
239
241
  }
240
- if (!ready || this.disposed || entry.retired || this.channels.get(session) !== entry)
242
+ if (!ready) {
243
+ // Anything but a positive "no such command" stays a refusal.
244
+ const stock = await this.#stockSplitServer();
245
+ if (!stock || this.disposed || entry.retired || this.channels.get(session) !== entry)
246
+ throw new WindowSplitLayoutUnavailable();
247
+ return this.#readStockSplitLayout(entry, target);
248
+ }
249
+ if (this.disposed || entry.retired || this.channels.get(session) !== entry)
241
250
  throw new WindowSplitLayoutUnavailable();
242
251
  }
252
+ if (entry.stockSplitEpoch)
253
+ throw new WindowSplitLayoutUnavailable();
243
254
  const epoch = this.opts.splitLayoutEpoch?.();
244
255
  let supported = false;
245
256
  try {
@@ -260,6 +271,25 @@ export class MirrorService {
260
271
  });
261
272
  return entry.splitAuthority.read(target);
262
273
  }
274
+ async #stockSplitServer() {
275
+ try {
276
+ return (await this.opts.splitLayoutStock?.()) === true;
277
+ }
278
+ catch {
279
+ return false;
280
+ }
281
+ }
282
+ #readStockSplitLayout(entry, target) {
283
+ if (entry.splitAuthority && !entry.stockSplitEpoch)
284
+ throw new WindowSplitLayoutUnavailable();
285
+ const epoch = (entry.stockSplitEpoch ??= randomUUID());
286
+ entry.splitAuthority ??= new WindowSplitAuthority({
287
+ describe: (window) => entry.channel.describeSplitLayout(window, true),
288
+ serverEpoch: () => epoch,
289
+ stock: true,
290
+ });
291
+ return entry.splitAuthority.read(target);
292
+ }
263
293
  /** Resolve only issued handles, then revalidate immediately at native dispatch. */
264
294
  async resizeWindowSplit(session, target, operationId, authorizeBeforeEffect, runNative) {
265
295
  const captured = WindowSplitResizeTargetSchemaZ.parse(target);
@@ -275,16 +305,22 @@ export class MirrorService {
275
305
  await entry.started;
276
306
  const resolved = current().resolve(captured);
277
307
  const successor = current().prepareSuccessor(captured);
278
- const result = await runNative(resolved.request, {
279
- operationId,
280
- serverEpoch: resolved.serverEpoch,
281
- session: resolved.session,
282
- anchor: resolved.anchor,
283
- authorizeBeforeEffect: () => {
284
- current().resolve(captured);
285
- authorizeBeforeEffect();
286
- },
287
- });
308
+ const authorize = () => {
309
+ current().resolve(captured);
310
+ authorizeBeforeEffect();
311
+ };
312
+ const result = entry.stockSplitEpoch
313
+ ? await resizeStockSplit(resolved.request, resolved.session.created, authorize, {
314
+ readOptions: (windowId) => entry.channel.stockSplitOptions(windowId),
315
+ send: (command) => entry.channel.stockSplitCommand(command),
316
+ })
317
+ : await runNative(resolved.request, {
318
+ operationId,
319
+ serverEpoch: resolved.serverEpoch,
320
+ session: resolved.session,
321
+ anchor: resolved.anchor,
322
+ authorizeBeforeEffect: authorize,
323
+ });
288
324
  if (result.status !== "applied")
289
325
  return result;
290
326
  // Native success is retained even if canonical publication is late or diverges.
@@ -1,3 +1,4 @@
1
+ import { STOCK_SPLIT_OPTIONS_FORMAT } from "../protocol/stock-split-resize.js";
1
2
  import { layoutContentRows } from "./layout-content-rows.js";
2
3
  import { decodeNativeAtomicSnapshot, decodeNativeAtomicDualSnapshot, nativeAtomicDualSnapshotPlan, nativeAtomicSnapshotPlan, } from "./native-atomic-snapshot.js";
3
4
  import { boundedTmuxInteractionAppendCommand } from "../../lib/tmux-interaction-retention.js";
@@ -557,7 +558,7 @@ export class SessionChannel {
557
558
  };
558
559
  }
559
560
  /** Exact native ancestry, never reconstructed from published pane rectangles. */
560
- describeSplitLayout(target) {
561
+ describeSplitLayout(target, stock = false) {
561
562
  const authority = this.windowLinkAuthority;
562
563
  const identity = this.attachedIdentity;
563
564
  const generation = this.attachedServerGeneration;
@@ -587,8 +588,7 @@ export class SessionChannel {
587
588
  pane.descriptor?.runtimeSessionId !== identity.runtimeSessionId ||
588
589
  pane.descriptor?.windowId !== resolved.runtimeWindowId ||
589
590
  this.panesBySemantic.get(pane.semanticId) !== pane ||
590
- !birth ||
591
- !/^[1-9]\d*$/u.test(birth) ||
591
+ (!stock && (!birth || !/^[1-9]\d*$/u.test(birth))) ||
592
592
  !layout.leaves.some((visible) => visible.id === leaf.id &&
593
593
  visible.left === leaf.left &&
594
594
  visible.top === leaf.top &&
@@ -598,7 +598,7 @@ export class SessionChannel {
598
598
  return Object.freeze({
599
599
  runtimePaneId: pane.runtimeId,
600
600
  semanticPaneId: pane.semanticId,
601
- nativePaneBirthId: birth,
601
+ nativePaneBirthId: stock ? "" : birth,
602
602
  });
603
603
  });
604
604
  return Object.freeze({
@@ -608,9 +608,24 @@ export class SessionChannel {
608
608
  runtimeWindowId: resolved.runtimeWindowId,
609
609
  semanticWindowId: window.semanticId,
610
610
  rawLayout: layout.rawLayout,
611
+ ...(stock ? { paneBorderStatus: window.paneBorderStatus } : {}),
611
612
  panes: Object.freeze(panes),
612
613
  });
613
614
  }
615
+ stockSplitOptions(windowId) {
616
+ return this.io.request(`display-message -p -t ${windowId} "${STOCK_SPLIT_OPTIONS_FORMAT}"`);
617
+ }
618
+ /** One guarded resize on this control connection, for a stock tmux server. */
619
+ stockSplitCommand(command) {
620
+ return new Promise((resolve, reject) => {
621
+ const onReply = (reply) => reply.ok ? resolve(reply.lines) : reject(new Error("Stock split command failed"));
622
+ const limits = { maxBytes: 16 * 1024, maxLines: 4 };
623
+ if (this.io.commandListBoundedInline)
624
+ this.io.commandListBoundedInline(command, 3, 2, limits, onReply);
625
+ else
626
+ this.io.commandListInline(command, 3, 2, onReply);
627
+ });
628
+ }
614
629
  async executeWindowLinkAction(request) {
615
630
  const authority = this.windowLinkAuthority;
616
631
  if (!authority || this.disposed)
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import { NativeJournalUint64SchemaZ, WindowLinkTargetSchemaZ, WindowSplitLayoutResourceSchemaZ, WindowSplitResizeTargetSchemaZ, } from "@tmux-ide/contracts";
4
4
  import { supportsNativeSessionGuard } from "../../lib/native-operation-command.js";
5
5
  import { parseLayoutTree } from "../protocol/layout-parse.js";
6
+ import { stockSplitMovable } from "../protocol/stock-split-resize.js";
6
7
  import { SplitLayoutPublicationPending, } from "./session-channel.js";
7
8
  const MAX_RETAINED_WINDOWS = 32;
8
9
  export class WindowSplitLayoutUnavailable extends Error {
@@ -43,7 +44,8 @@ export class WindowSplitAuthority {
43
44
  snapshot.panes.forEach((pane) => {
44
45
  if (!/^%(0|[1-9][0-9]{0,9})$/u.test(pane.runtimePaneId) ||
45
46
  Number(pane.runtimePaneId.slice(1)) > 0xffffffff ||
46
- !NativeJournalUint64SchemaZ.refine((birth) => birth !== "0").safeParse(pane.nativePaneBirthId).success)
47
+ (!this.options.stock &&
48
+ !NativeJournalUint64SchemaZ.refine((birth) => birth !== "0").safeParse(pane.nativePaneBirthId).success))
47
49
  throw new WindowSplitLayoutUnavailable();
48
50
  });
49
51
  const mapping = new Map(snapshot.panes.map((pane) => [pane.runtimePaneId, pane]));
@@ -71,7 +73,12 @@ export class WindowSplitAuthority {
71
73
  }
72
74
  node.children.forEach((child, index) => {
73
75
  const childPath = [...path, index];
74
- if (index < node.children.length - 1) {
76
+ if (index < node.children.length - 1 &&
77
+ (!this.options.stock ||
78
+ stockSplitMovable(tree, childPath, node.axis, {
79
+ borderStatus: snapshot.paneBorderStatus ?? "off",
80
+ scrollbar: 0,
81
+ }))) {
75
82
  const splitId = randomUUID();
76
83
  paths.set(splitId, childPath);
77
84
  splits.push({
@@ -11,7 +11,7 @@ function json(text, limit) {
11
11
  throw new Error("Bounded native response required");
12
12
  return JSON.parse(text);
13
13
  }
14
- function capability(text) {
14
+ export function nativeSplitCapability(text) {
15
15
  const value = json(text, 1024);
16
16
  return (object(value, [
17
17
  "schemaVersion",
@@ -31,13 +31,13 @@ function capability(text) {
31
31
  /** Read-only, uncached probe; the caller pins and bounds the selected server. */
32
32
  export async function supportsNativeSplitResize(runTmux) {
33
33
  try {
34
- return capability(await runTmux(["tmux-ide-resize-split", "-V"]));
34
+ return nativeSplitCapability(await runTmux(["tmux-ide-resize-split", "-V"]));
35
35
  }
36
36
  catch {
37
37
  return false;
38
38
  }
39
39
  }
40
- function validTree(tree) {
40
+ export function validSplitTree(tree) {
41
41
  let budget = 5;
42
42
  const visit = (node) => {
43
43
  if (node.left + node.width > 4096 || node.top + node.height > 4096)
@@ -55,7 +55,7 @@ function validTree(tree) {
55
55
  };
56
56
  return visit(tree);
57
57
  }
58
- function locate(tree, path) {
58
+ export function locateSplit(tree, path) {
59
59
  let node = tree;
60
60
  let parent;
61
61
  for (const index of path) {
@@ -66,7 +66,7 @@ function locate(tree, path) {
66
66
  }
67
67
  return parent && path.at(-1) < parent.children.length - 1 ? { parent, node } : null;
68
68
  }
69
- function edge(node, axis) {
69
+ export function splitEdge(node, axis) {
70
70
  return axis === "cols" ? node.left + node.width : node.top + node.height;
71
71
  }
72
72
  function sameRect(a, b) {
@@ -75,7 +75,7 @@ function sameRect(a, b) {
75
75
  /** Only geometry inside the exact parent may change, along the requested axis.
76
76
  * Native redistribution can affect multiple siblings. This verifies convergence,
77
77
  * not exclusive causation or authentication of the returned layout. */
78
- function preservesTree(before, after, affected, axis, inside = false) {
78
+ export function preservesSplitTree(before, after, affected, axis, inside = false) {
79
79
  const begins = before === affected;
80
80
  if (before.kind !== after.kind || ((!inside || begins) && !sameRect(before, after)))
81
81
  return false;
@@ -90,7 +90,7 @@ function preservesTree(before, after, affected, axis, inside = false) {
90
90
  return (after.kind === "split" &&
91
91
  before.axis === after.axis &&
92
92
  before.children.length === after.children.length &&
93
- before.children.every((child, index) => preservesTree(child, after.children[index], affected, axis, inside)));
93
+ before.children.every((child, index) => preservesSplitTree(child, after.children[index], affected, axis, inside)));
94
94
  }
95
95
  /** Internal foundation only; no route or native capability is enabled here.
96
96
  * Capability is checked on every invocation, never cached across generations.
@@ -117,9 +117,9 @@ export async function resizeNativeSplit(request, runTmux) {
117
117
  request.boundary > 4096)
118
118
  return { status: "refused", reason: "invalid-request" };
119
119
  const tree = parseLayoutTree(request.expectedLayout);
120
- if (!tree || !validTree(tree))
120
+ if (!tree || !validSplitTree(tree))
121
121
  return { status: "refused", reason: "invalid-request" };
122
- const selected = locate(tree, request.path);
122
+ const selected = locateSplit(tree, request.path);
123
123
  if (!selected || selected.parent.axis !== request.axis)
124
124
  return { status: "refused", reason: "invalid-request" };
125
125
  before = tree;
@@ -130,7 +130,7 @@ export async function resizeNativeSplit(request, runTmux) {
130
130
  return { status: "refused", reason: "invalid-request" };
131
131
  }
132
132
  try {
133
- if (!capability(await runTmux(["tmux-ide-resize-split", "-V"])))
133
+ if (!nativeSplitCapability(await runTmux(["tmux-ide-resize-split", "-V"])))
134
134
  return { status: "refused", reason: "unsupported" };
135
135
  }
136
136
  catch {
@@ -168,14 +168,14 @@ export async function resizeNativeSplit(request, runTmux) {
168
168
  receipt.boundary > 4096)
169
169
  return { status: "uncertain", reason: "invalid-receipt" };
170
170
  const after = parseLayoutTree(receipt.layout);
171
- const original = locate(before, captured.path);
172
- const actual = after && locate(after, captured.path);
173
- const previous = edge(original.node, captured.axis);
171
+ const original = locateSplit(before, captured.path);
172
+ const actual = after && locateSplit(after, captured.path);
173
+ const previous = splitEdge(original.node, captured.axis);
174
174
  if (!after ||
175
- !validTree(after) ||
175
+ !validSplitTree(after) ||
176
176
  !actual ||
177
- !preservesTree(before, after, original.parent, captured.axis) ||
178
- receipt.boundary !== edge(actual.node, captured.axis) ||
177
+ !preservesSplitTree(before, after, original.parent, captured.axis) ||
178
+ receipt.boundary !== splitEdge(actual.node, captured.axis) ||
179
179
  receipt.boundary < Math.min(previous, captured.boundary) ||
180
180
  receipt.boundary > Math.max(previous, captured.boundary))
181
181
  return { status: "uncertain", reason: "invalid-receipt" };