tmux-ide 2.9.22 → 2.9.23

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 (85) hide show
  1. package/bin/cli.js +3434 -7568
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +1 -0
  4. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  5. package/packages/daemon/dist/command-center/automation.js +1 -1
  6. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  7. package/packages/daemon/dist/command-center/discovery.js +28 -2
  8. package/packages/daemon/dist/command-center/server.js +8 -2
  9. package/packages/daemon/dist/command-center/tmux-servers.js +1 -1
  10. package/packages/daemon/dist/doctor.js +41 -0
  11. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  12. package/packages/daemon/dist/lib/daemon-embed.js +111 -55
  13. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  14. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  15. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  16. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  17. package/packages/daemon/dist/lib/log.js +18 -1
  18. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  19. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  20. package/packages/daemon/dist/lib/tmux-pane-reader.js +4 -2
  21. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  22. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  23. package/packages/daemon/dist/lib/tmux-server-owner.js +29 -37
  24. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  25. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  26. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  27. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  29. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  30. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  31. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  32. package/packages/daemon/dist/plugins/cli.js +1 -2
  33. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  34. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  35. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  36. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  37. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  38. package/packages/daemon/dist/terminal/mirror/session-channel.js +9 -11
  39. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +111 -22
  40. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  41. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +23 -0
  42. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  43. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  44. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  45. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  46. package/packages/daemon/src/command-center/automation.ts +1 -1
  47. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  48. package/packages/daemon/src/command-center/discovery.ts +35 -2
  49. package/packages/daemon/src/command-center/server.ts +22 -8
  50. package/packages/daemon/src/command-center/tmux-servers.ts +1 -1
  51. package/packages/daemon/src/doctor.ts +46 -0
  52. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  53. package/packages/daemon/src/lib/daemon-embed.ts +159 -64
  54. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  55. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  56. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  57. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  58. package/packages/daemon/src/lib/log.ts +18 -1
  59. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  60. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  61. package/packages/daemon/src/lib/tmux-pane-reader.ts +4 -3
  62. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  63. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  64. package/packages/daemon/src/lib/tmux-server-owner.ts +32 -35
  65. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  66. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  67. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  68. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  69. package/packages/daemon/src/plugins/cli.ts +1 -2
  70. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  71. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  72. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  73. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  74. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  75. package/packages/daemon/src/terminal/mirror/session-channel.ts +9 -13
  76. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +125 -21
  77. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  78. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +31 -0
  79. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  80. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  81. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  82. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  83. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  84. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  85. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
@@ -56,6 +56,31 @@ import type { TerminalGraphicsState } from "@tmux-ide/contracts";
56
56
  // Bound parser work per turn without changing byte-stream semantics. This is a
57
57
  // batch bound, not a producer queue cap: upstream pressure must preserve bytes.
58
58
  const MAX_INGEST_BATCH_BYTES = 256 * 1024;
59
+ /**
60
+ * Under a flood, publish at most one commit per display interval (daemon perf
61
+ * F1). Each commit projects, diffs and hashes the replica; committing after
62
+ * every parsed chunk kept the daemon off tmux's control pipe, so tmux itself
63
+ * ran about 4× slower while a pane was viewed. Rows that scroll through
64
+ * history between two commits are never projected or hashed. A write with no
65
+ * output queued behind it (a keystroke echo, the end of a burst) still
66
+ * commits at once.
67
+ */
68
+ export const COALESCED_COMMIT_INTERVAL_MS = 16;
69
+ /**
70
+ * A flood commit costs far more than the display interval (about 35 ms with a
71
+ * full 2,000-row history), so an interval counted from the commit's start
72
+ * alone never skips anything: the next chunk always arrives "late". After a
73
+ * commit the interpreter therefore also reads queued output for this many
74
+ * times the commit's own cost before it commits again, so at most one part in
75
+ * (1 + factor) of a flood goes to commits (half, at 1).
76
+ */
77
+ export const COALESCED_COMMIT_REST_FACTOR = 1;
78
+ /**
79
+ * Upper bound of that rest. A skipped frame can still wait longer when the
80
+ * queued write behind it opens a synchronized update: then it is published
81
+ * with that update, at its end or by the 250 ms sync recovery.
82
+ */
83
+ export const COALESCED_COMMIT_MAX_REST_MS = 100;
59
84
  type PendingWrite = {
60
85
  data: Uint8Array;
61
86
  offset: number;
@@ -184,6 +209,11 @@ export class TerminalReplicaInterpreter {
184
209
  #needsSeed = true;
185
210
  #closed = false;
186
211
  #walkCount = 0;
212
+ #lastCommitAtMs = Number.NEGATIVE_INFINITY;
213
+ #lastCommitEndMs = Number.NEGATIVE_INFINITY;
214
+ #lastCommitCostMs = 0;
215
+ // A coalesced write skipped its commit and counts on a queued write to publish.
216
+ #coalescedCommitOwed = false;
187
217
  #pendingWrites: WriteGroup | null = null;
188
218
  #widgetGate = false;
189
219
  // kitty graphics: images outlive reseeds; the scanner owns split APCs.
@@ -528,7 +558,11 @@ export class TerminalReplicaInterpreter {
528
558
  this.#emit(update);
529
559
  }
530
560
 
531
- async #write(data: Uint8Array, continuedTrace: SessionRuntimeTraceContext | null): Promise<void> {
561
+ async #write(
562
+ data: Uint8Array,
563
+ continuedTrace: SessionRuntimeTraceContext | null,
564
+ hasBacklog: () => boolean = () => false,
565
+ ): Promise<void> {
532
566
  if (this.#closed || this.#nativeReseedRequested) return;
533
567
  // This optional id is only a controlled next-output probe. It is not a
534
568
  // causal assertion: unrelated external tmux output arriving first may
@@ -547,7 +581,17 @@ export class TerminalReplicaInterpreter {
547
581
  // see. Skipping it matters: every parser write settles on a later timer
548
582
  // turn, so a frame split into dozens of %output chunks would otherwise
549
583
  // serialize dozens of turns and fall behind a 30 fps image stream.
550
- if (scanned.forward.byteLength === 0) return;
584
+ if (scanned.forward.byteLength === 0) {
585
+ // The queued write a coalesced commit was counting on turned out to be
586
+ // all image payload, and nothing else is queued: publish what it skipped.
587
+ // Not inside a synchronized update: its end, or the sync recovery,
588
+ // publishes the owed commit with the whole frame.
589
+ if (this.#coalescedCommitOwed && !hasBacklog() && !this.#backend.modes().synchronizedOutput) {
590
+ this.#commit(false, this.#pendingWriteDirty ?? undefined, trace);
591
+ this.#publishGraphics();
592
+ }
593
+ return;
594
+ }
551
595
  // Scanning can prepend an escape retained from the previous chunk. Bound
552
596
  // the actual parser calls too, and union damage across every fragment.
553
597
  for (let offset = 0; offset < scanned.forward.length; offset += MAX_INGEST_BATCH_BYTES) {
@@ -592,6 +636,20 @@ export class TerminalReplicaInterpreter {
592
636
  if (pendingResize) {
593
637
  this.#commit(false, undefined, trace);
594
638
  } else {
639
+ // Coalesce under a flood: more output is already queued, the last commit
640
+ // is recent, and nobody is timing this write. The dirty range stays in
641
+ // #pendingWriteDirty and the next commit (the queued write's, or any
642
+ // control operation's) merges it, so nothing is dropped. The bootstrap
643
+ // seed is never held: before it no commit has run, so one is always due.
644
+ if (
645
+ trace === null &&
646
+ this.#causalCell === null &&
647
+ hasBacklog() &&
648
+ !this.#coalescedCommitIsDue()
649
+ ) {
650
+ this.#coalescedCommitOwed = true;
651
+ return;
652
+ }
595
653
  this.#commit(false, this.#backend.dirtyRange(), trace);
596
654
  }
597
655
  this.#publishGraphics();
@@ -629,10 +687,36 @@ export class TerminalReplicaInterpreter {
629
687
  this.#syncRecovery = null;
630
688
  }
631
689
 
690
+ /** True once a queued flood may publish again: see the two constants above. */
691
+ #coalescedCommitIsDue(): boolean {
692
+ const now = this.#scheduler.nowMs();
693
+ if (now - this.#lastCommitAtMs < COALESCED_COMMIT_INTERVAL_MS) return false;
694
+ const rest = Math.min(
695
+ COALESCED_COMMIT_MAX_REST_MS,
696
+ COALESCED_COMMIT_REST_FACTOR * this.#lastCommitCostMs,
697
+ );
698
+ return now - this.#lastCommitEndMs >= rest;
699
+ }
700
+
632
701
  #commit(
633
702
  forceSeed: boolean,
634
703
  dirty?: { start: number; end: number },
635
704
  trace: SessionRuntimeTraceContext | null = null,
705
+ ): void {
706
+ this.#lastCommitAtMs = this.#scheduler.nowMs();
707
+ this.#coalescedCommitOwed = false;
708
+ try {
709
+ this.#commitNow(forceSeed, dirty, trace);
710
+ } finally {
711
+ this.#lastCommitEndMs = this.#scheduler.nowMs();
712
+ this.#lastCommitCostMs = this.#lastCommitEndMs - this.#lastCommitAtMs;
713
+ }
714
+ }
715
+
716
+ #commitNow(
717
+ forceSeed: boolean,
718
+ dirty: { start: number; end: number } | undefined,
719
+ trace: SessionRuntimeTraceContext | null,
636
720
  ): void {
637
721
  if (this.#backend.requiresNativeReseed()) {
638
722
  if (!this.#nativeReseedRequested) {
@@ -916,7 +1000,20 @@ export class TerminalReplicaInterpreter {
916
1000
  group.entries.splice(0, completed.length);
917
1001
  group.bytes -= length;
918
1002
  try {
919
- await this.#write(data, group.trace);
1003
+ // Backlog: bytes still in this group, or a newer untraced group
1004
+ // already waiting behind it (a group that has not run yet always
1005
+ // holds an entry). A traced group is a boundary: its commit must
1006
+ // not carry these external bytes. Checked after parsing, when it
1007
+ // is current.
1008
+ await this.#write(
1009
+ data,
1010
+ group.trace,
1011
+ () =>
1012
+ group.entries.length > 0 ||
1013
+ (this.#pendingWrites !== null &&
1014
+ this.#pendingWrites !== group &&
1015
+ this.#pendingWrites.trace === null),
1016
+ );
920
1017
  } catch (error) {
921
1018
  for (const entry of completed) entry.reject(error);
922
1019
  throw error;
@@ -42,6 +42,12 @@ export interface TerminalReplicaSubscription {
42
42
  }
43
43
 
44
44
  export type TerminalReplicaSourceSubscription = TerminalReplicaSubscription;
45
+ /**
46
+ * How long a pane may have no listener before it is parked (perf F2). Long
47
+ * enough that switching away and back stays warm.
48
+ */
49
+ export const PARK_AFTER_MS = 10_000;
50
+
45
51
  export interface TerminalReplicaCommittedRaw {
46
52
  readonly baseRevision: number;
47
53
  readonly revision: number;
@@ -103,6 +109,11 @@ export class SessionRuntimeTerminalReplicaOwner {
103
109
  readonly #start: Promise<void>;
104
110
  #upstream: MirrorSubscription | null = null;
105
111
  #disposed = false;
112
+ #parkTimer: SessionRuntimeTimer | null = null;
113
+ #parked = false;
114
+ // From the park until the next reseed lands, the replica is older than tmux.
115
+ // Native backing and history anchors must not pair it with current tmux state.
116
+ #stale = false;
106
117
  readonly #historyAnchors = new HistoryAnchorOwner();
107
118
  #cols = 80;
108
119
  #rows = 24;
@@ -243,13 +254,13 @@ export class SessionRuntimeTerminalReplicaOwner {
243
254
  }
244
255
 
245
256
  captureHistoryAnchor(proof: HistoryAnchorProof, historyIndex: number) {
246
- if (this.#disposed || this.#reseed || this.#waitingForGeometryCapture)
257
+ if (this.#disposed || this.#stale || this.#reseed || this.#waitingForGeometryCapture)
247
258
  return { status: "unavailable" as const };
248
259
  return this.#historyAnchors.capture(proof, historyIndex);
249
260
  }
250
261
 
251
262
  resolveHistoryAnchor(proof: HistoryAnchorIdentity, token: string) {
252
- if (this.#disposed || this.#reseed || this.#waitingForGeometryCapture)
263
+ if (this.#disposed || this.#stale || this.#reseed || this.#waitingForGeometryCapture)
253
264
  return { status: "unavailable" as const };
254
265
  return this.#historyAnchors.resolve(proof, token);
255
266
  }
@@ -287,7 +298,8 @@ export class SessionRuntimeTerminalReplicaOwner {
287
298
  const upstream = this.#upstream;
288
299
  if (!upstream?.captureNativeBacking) return { status: "unsupported" };
289
300
  const initial = this.#interpreter.currentSeed();
290
- if (!initial || this.#reseed || this.#waitingForGeometryCapture) return { status: "changed" };
301
+ if (!initial || this.#stale || this.#reseed || this.#waitingForGeometryCapture)
302
+ return { status: "changed" };
291
303
  const epoch = this.#subscriptionEpoch;
292
304
  const captured = await upstream.captureNativeBacking();
293
305
  if (captured.status !== "captured") return captured;
@@ -298,6 +310,7 @@ export class SessionRuntimeTerminalReplicaOwner {
298
310
  !this.#disposed &&
299
311
  this.#upstream === upstream &&
300
312
  this.#subscriptionEpoch === epoch &&
313
+ !this.#stale &&
301
314
  !this.#reseed &&
302
315
  !this.#waitingForGeometryCapture &&
303
316
  captured.isCurrent() &&
@@ -362,6 +375,8 @@ export class SessionRuntimeTerminalReplicaOwner {
362
375
  } catch {
363
376
  // Bootstrap delivery has the same client-isolation rule as live frames.
364
377
  }
378
+ // The last frame is out; now ask for the reseed that makes it current.
379
+ this.#unpark();
365
380
  } catch (error) {
366
381
  this.#listeners.delete(listener);
367
382
  throw error;
@@ -374,10 +389,47 @@ export class SessionRuntimeTerminalReplicaOwner {
374
389
  if (closed) return;
375
390
  closed = true;
376
391
  this.#listeners.delete(listener);
392
+ if (this.#listeners.size === 0) this.#schedulePark();
377
393
  },
378
394
  };
379
395
  }
380
396
 
397
+ /**
398
+ * Park this pane PARK_AFTER_MS after its last listener leaves (perf F2).
399
+ * The owner is the pane's only channel subscriber, so freezing it pauses the
400
+ * pane's output to the daemon's control client (the channel's all-frozen
401
+ * path). tmux keeps running the pane; nothing here is parsed or hashed. The
402
+ * last committed seed stays, so the next listener sees it at once, and
403
+ * thawing runs the channel's requested-pause recovery, which reseeds.
404
+ * Until that reseed lands the replica is stale: history anchors and native
405
+ * backing answer as they do during any reseed, and the reseed's reset then
406
+ * drops every anchor taken before the park.
407
+ */
408
+ #schedulePark(): void {
409
+ if (this.#disposed || this.#parked) return;
410
+ this.#parkTimer?.cancel();
411
+ this.#parkTimer = this.#scheduler.timer(() => {
412
+ this.#parkTimer = null;
413
+ if (this.#disposed || this.#parked || this.#listeners.size > 0 || !this.#upstream) return;
414
+ this.#parked = true;
415
+ this.#stale = true;
416
+ this.#upstream.freeze();
417
+ }, PARK_AFTER_MS);
418
+ }
419
+
420
+ #unpark(): void {
421
+ this.#parkTimer?.cancel();
422
+ this.#parkTimer = null;
423
+ if (!this.#parked) return;
424
+ this.#parked = false;
425
+ this.#upstream?.thaw();
426
+ }
427
+
428
+ /** True while the pane is parked (tests and qualification). */
429
+ get parked(): boolean {
430
+ return this.#parked;
431
+ }
432
+
381
433
  /** Kitty graphics side channel: current state now (if any), then every change. */
382
434
  subscribeGraphics(listener: (state: TerminalGraphicsState) => void): () => void {
383
435
  const current = this.#interpreter.currentGraphics();
@@ -420,6 +472,8 @@ export class SessionRuntimeTerminalReplicaOwner {
420
472
  this.#historyAnchors.invalidate();
421
473
  this.#historyTimer?.cancel();
422
474
  this.#historyTimer = null;
475
+ this.#parkTimer?.cancel();
476
+ this.#parkTimer = null;
423
477
  this.#subscriptionEpoch += 1;
424
478
  await this.#interpreter.enqueue({ type: "close", reason });
425
479
  await this.#start.catch(() => undefined);
@@ -454,6 +508,7 @@ export class SessionRuntimeTerminalReplicaOwner {
454
508
  // Output received during the probe makes its count incomparable with
455
509
  // the newer parser state. The dirty flag schedules another check.
456
510
  this.#historyDirty ||
511
+ this.#stale ||
457
512
  this.#reseed ||
458
513
  this.#waitingForGeometryCapture ||
459
514
  size === null
@@ -511,6 +566,8 @@ export class SessionRuntimeTerminalReplicaOwner {
511
566
  this.#waitingForGeometryCapture = false;
512
567
  const reseed = this.#reseed;
513
568
  this.#reseed = null;
569
+ // A completed capture after the park makes the replica current again.
570
+ if (reseed && !this.#parked) this.#stale = false;
514
571
  const lease = reseed ? this.#qualifyReseed(reseed, event.x, event.y) : null;
515
572
  this.#supervise(
516
573
  reseed && lease
@@ -368,6 +368,19 @@ export function createDirectLoopbackDaemonTransport(
368
368
  };
369
369
  let terminalReconnectTimer: unknown | null = null;
370
370
  let terminalReconnectController: AbortController | null = null;
371
+ // Failed terminal reconnects back off as the catalog-only one does (#764):
372
+ // a daemon that keeps refusing the inventory is asked at 1, 2, 4 … 30 s,
373
+ // never at a fixed 1 Hz forever. A committed reconnect resets it.
374
+ let terminalReconnectAttempt = 0;
375
+ // The target the backoff was counted for: another workspace or session
376
+ // starts again at 1 s. Kept apart from supervisorTargetKey, which a
377
+ // retirement clears before its own reconnect.
378
+ let terminalReconnectTargetKey: string | null = null;
379
+ const terminalReconnectDelay = (): number => {
380
+ const delayMs = Math.min(1_000 * 2 ** terminalReconnectAttempt, 30_000);
381
+ terminalReconnectAttempt += 1;
382
+ return delayMs;
383
+ };
371
384
  let catalogReconnectTimer: unknown | null = null;
372
385
  let catalogReconnectAttempt = 0;
373
386
  let scheduleCatalogOnlyReconnect = (): void => undefined;
@@ -457,6 +470,10 @@ export function createDirectLoopbackDaemonTransport(
457
470
  ): WorkspaceEventSupervisor => {
458
471
  const key = `${safeTarget.daemon.instanceId}\0${safeTarget.workspaceName}\0${sessionName}`;
459
472
  if (eventSupervisor && supervisorTargetKey === key) return eventSupervisor;
473
+ if (terminalReconnectTargetKey !== key) {
474
+ terminalReconnectTargetKey = key;
475
+ terminalReconnectAttempt = 0;
476
+ }
460
477
  eventSupervisor?.dispose();
461
478
  const socket = createWebSocket(eventSocketUrl(descriptor, "semantic"), {
462
479
  headers: dependencies.ownerToken
@@ -544,7 +561,7 @@ export function createDirectLoopbackDaemonTransport(
544
561
  terminalReconnectTimer = terminalReconnectClock.setTimeout(() => {
545
562
  terminalReconnectTimer = null;
546
563
  reconnect();
547
- }, 1_000);
564
+ }, terminalReconnectDelay());
548
565
  };
549
566
  const commitReplacement = (): void => {
550
567
  if (
@@ -563,6 +580,7 @@ export function createDirectLoopbackDaemonTransport(
563
580
  retryReplacement();
564
581
  return;
565
582
  }
583
+ terminalReconnectAttempt = 0;
566
584
  sink(resource);
567
585
  if (retainedWorkspaceCatalogReady?.subscriber === catalogSubscriber)
568
586
  retainedWorkspaceCatalogReady.resolve();
@@ -589,14 +607,14 @@ export function createDirectLoopbackDaemonTransport(
589
607
  terminalReconnectTimer = terminalReconnectClock.setTimeout(() => {
590
608
  terminalReconnectTimer = null;
591
609
  reconnect();
592
- }, 1_000);
610
+ }, terminalReconnectDelay());
593
611
  });
594
612
  };
595
613
  if (retiredDuringReconnect) {
596
614
  terminalReconnectTimer = terminalReconnectClock.setTimeout(() => {
597
615
  terminalReconnectTimer = null;
598
616
  reconnect();
599
- }, 1_000);
617
+ }, terminalReconnectDelay());
600
618
  } else {
601
619
  queueMicrotask(reconnect);
602
620
  }
@@ -142,6 +142,18 @@ function deferred(): {
142
142
  return { promise, resolve, reject };
143
143
  }
144
144
 
145
+ /**
146
+ * After the fast retries, a read that keeps failing (the daemon answering 503
147
+ * while it re-qualifies a session, #764) is retried on this slow backoff while
148
+ * the sink is attached; the last step repeats until the budget is spent.
149
+ */
150
+ const TERMINAL_REFRESH_BACKOFF_MS = [250, 500, 1_000] as const;
151
+ const TERMINAL_REFRESH_BACKOFF_LAST_MS = 1_000;
152
+ /** Past this much backoff the stale authority is retired, not shown on. */
153
+ const TERMINAL_REFRESH_BACKOFF_BUDGET_MS = 15_000;
154
+ /** The delay between a sink-requeued or fast-retried refresh and the next. */
155
+ const TERMINAL_REFRESH_STEP_MS = 25;
156
+
145
157
  /**
146
158
  * One permanent parser and physical event socket for a WorkspaceClient generation.
147
159
  * Logical resource barriers are independent; a socket hello never makes a resource live.
@@ -209,6 +221,13 @@ export function createWorkspaceEventSupervisor(
209
221
  let terminalRefreshCoalesced = 0;
210
222
  let terminalRefreshDelayed = false;
211
223
  let terminalRefreshRetryAttempt = 0;
224
+ // The slow backoff after the fast retries (#764): its next step, how much
225
+ // of the budget it has spent, the delay before the next run, and whether
226
+ // the pending timer is a backoff a new request may cut short.
227
+ let terminalRefreshBackoffStep = 0;
228
+ let terminalRefreshBackoffSpent = 0;
229
+ let terminalRefreshNextDelay: number = TERMINAL_REFRESH_STEP_MS;
230
+ let terminalRefreshBackingOff = false;
212
231
  let applicationShellHandlers: ApplicationShellEventHandlers | null = null;
213
232
  let workspaceCatalogInvalidate: (() => void) | null = null;
214
233
  let retirementNotified = false;
@@ -346,6 +365,20 @@ export function createWorkspaceEventSupervisor(
346
365
  reason: "event" | "gap" | "snapshot" | "consumer" = "consumer",
347
366
  continuation = false,
348
367
  ): void => {
368
+ if (!continuation) {
369
+ // A daemon event starts a fresh budget; any new request reads now
370
+ // rather than waiting out a backoff.
371
+ if (reason !== "consumer") {
372
+ terminalRefreshBackoffStep = 0;
373
+ terminalRefreshBackoffSpent = 0;
374
+ }
375
+ if (terminalRefreshBackingOff && terminalRefreshTimer !== null) {
376
+ refreshClock.clearTimeout(terminalRefreshTimer);
377
+ terminalRefreshTimer = null;
378
+ terminalRefreshBackingOff = false;
379
+ terminalRefreshQueued = false;
380
+ }
381
+ }
349
382
  if (!continuation && !terminalRefreshQueued && !terminalRefreshRunning)
350
383
  terminalRefreshRetryAttempt = 0;
351
384
  if (!continuation && reason !== "consumer") {
@@ -376,7 +409,8 @@ export function createWorkspaceEventSupervisor(
376
409
  terminalRefreshDelayed = false;
377
410
  const controller = new AbortController();
378
411
  terminalRefreshController = controller;
379
- let outcome: "success" | "retry" | "exhausted" | "aborted" = "success";
412
+ let outcome: "success" | "retry" | "backoff" | "exhausted" | "aborted" = "success";
413
+ let retire = false;
380
414
  let failure: "read-failed" | "stale-revision" | null = null;
381
415
  try {
382
416
  const resource = await readTerminal(controller.signal, false);
@@ -388,6 +422,8 @@ export function createWorkspaceEventSupervisor(
388
422
  terminalSink(resource);
389
423
  }
390
424
  terminalRefreshRetryAttempt = 0;
425
+ terminalRefreshBackoffStep = 0;
426
+ terminalRefreshBackoffSpent = 0;
391
427
  } catch {
392
428
  if (failure === null && !controller.signal.aborted) failure = "read-failed";
393
429
  const recoverable = !controller.signal.aborted && !disposed && terminalSink !== null;
@@ -398,9 +434,26 @@ export function createWorkspaceEventSupervisor(
398
434
  terminalRefreshRetryAttempt += 1;
399
435
  terminalRefreshQueued = true;
400
436
  outcome = "retry";
437
+ } else if (
438
+ recoverable &&
439
+ failure === "read-failed" &&
440
+ terminalRefreshBackoffSpent < TERMINAL_REFRESH_BACKOFF_BUDGET_MS
441
+ ) {
442
+ // Nothing else will ask again: the daemon publishes no event once
443
+ // it can answer (#764). Keep asking, slowly, within a budget.
444
+ const delay =
445
+ TERMINAL_REFRESH_BACKOFF_MS[terminalRefreshBackoffStep] ??
446
+ TERMINAL_REFRESH_BACKOFF_LAST_MS;
447
+ terminalRefreshBackoffStep += 1;
448
+ terminalRefreshBackoffSpent += delay;
449
+ terminalRefreshNextDelay = delay;
450
+ terminalRefreshQueued = true;
451
+ outcome = "backoff";
401
452
  } else {
402
453
  terminalRefreshQueued = false;
403
454
  outcome = controller.signal.aborted ? "aborted" : "exhausted";
455
+ // A budget spent on failed reads: the terminal on screen is stale.
456
+ retire = outcome === "exhausted" && failure === "read-failed" && recoverable;
404
457
  }
405
458
  } finally {
406
459
  const discardedCoalesced =
@@ -413,9 +466,11 @@ export function createWorkspaceEventSupervisor(
413
466
  attempt,
414
467
  outcome,
415
468
  failure,
469
+ ...(outcome === "backoff" ? { delayMs: terminalRefreshNextDelay } : {}),
416
470
  });
417
471
  if (terminalRefreshController === controller) terminalRefreshController = null;
418
472
  }
473
+ if (retire) notifyRetired();
419
474
  };
420
475
  void run().finally(() => {
421
476
  terminalRefreshRunning = false;
@@ -424,11 +479,15 @@ export function createWorkspaceEventSupervisor(
424
479
  // just-read snapshot. Keep that recovery live, but never let it form a
425
480
  // microtask spin loop against a stale same-revision authority.
426
481
  terminalRefreshDelayed = true;
482
+ const delay = terminalRefreshNextDelay;
483
+ terminalRefreshNextDelay = TERMINAL_REFRESH_STEP_MS;
484
+ terminalRefreshBackingOff = delay > TERMINAL_REFRESH_STEP_MS;
427
485
  terminalRefreshTimer = refreshClock.setTimeout(() => {
428
486
  terminalRefreshTimer = null;
487
+ terminalRefreshBackingOff = false;
429
488
  terminalRefreshQueued = false;
430
489
  refreshTerminalAuthority(terminalRefreshReason, true);
431
- }, 25);
490
+ }, delay);
432
491
  });
433
492
  });
434
493
  };
@@ -683,6 +742,7 @@ export function createWorkspaceEventSupervisor(
683
742
  terminalRefreshQueued = false;
684
743
  if (terminalRefreshTimer !== null) refreshClock.clearTimeout(terminalRefreshTimer);
685
744
  terminalRefreshTimer = null;
745
+ terminalRefreshBackingOff = false;
686
746
  terminalRefreshDelayed = false;
687
747
  terminalRefreshController?.abort();
688
748
  terminalRefreshController = null;
@@ -698,6 +758,7 @@ export function createWorkspaceEventSupervisor(
698
758
  disposed = true;
699
759
  if (terminalRefreshTimer !== null) refreshClock.clearTimeout(terminalRefreshTimer);
700
760
  terminalRefreshTimer = null;
761
+ terminalRefreshBackingOff = false;
701
762
  terminalRefreshQueued = false;
702
763
  terminalRefreshDelayed = false;
703
764
  terminalRefreshController?.abort();