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
@@ -10,6 +10,31 @@ import { KITTY_PLACEMENT_OSC, KittyApcScanner, KittyImageStore, } from "../graph
10
10
  // Bound parser work per turn without changing byte-stream semantics. This is a
11
11
  // batch bound, not a producer queue cap: upstream pressure must preserve bytes.
12
12
  const MAX_INGEST_BATCH_BYTES = 256 * 1024;
13
+ /**
14
+ * Under a flood, publish at most one commit per display interval (daemon perf
15
+ * F1). Each commit projects, diffs and hashes the replica; committing after
16
+ * every parsed chunk kept the daemon off tmux's control pipe, so tmux itself
17
+ * ran about 4× slower while a pane was viewed. Rows that scroll through
18
+ * history between two commits are never projected or hashed. A write with no
19
+ * output queued behind it (a keystroke echo, the end of a burst) still
20
+ * commits at once.
21
+ */
22
+ export const COALESCED_COMMIT_INTERVAL_MS = 16;
23
+ /**
24
+ * A flood commit costs far more than the display interval (about 35 ms with a
25
+ * full 2,000-row history), so an interval counted from the commit's start
26
+ * alone never skips anything: the next chunk always arrives "late". After a
27
+ * commit the interpreter therefore also reads queued output for this many
28
+ * times the commit's own cost before it commits again, so at most one part in
29
+ * (1 + factor) of a flood goes to commits (half, at 1).
30
+ */
31
+ export const COALESCED_COMMIT_REST_FACTOR = 1;
32
+ /**
33
+ * Upper bound of that rest. A skipped frame can still wait longer when the
34
+ * queued write behind it opens a synchronized update: then it is published
35
+ * with that update, at its end or by the 250 ms sync recovery.
36
+ */
37
+ export const COALESCED_COMMIT_MAX_REST_MS = 100;
13
38
  /** Daemon-owned, sans-I/O VT interpreter with one FIFO for bytes and geometry. */
14
39
  export class TerminalReplicaInterpreter {
15
40
  #nativeSeedBackingCandidate;
@@ -38,6 +63,11 @@ export class TerminalReplicaInterpreter {
38
63
  #needsSeed = true;
39
64
  #closed = false;
40
65
  #walkCount = 0;
66
+ #lastCommitAtMs = Number.NEGATIVE_INFINITY;
67
+ #lastCommitEndMs = Number.NEGATIVE_INFINITY;
68
+ #lastCommitCostMs = 0;
69
+ // A coalesced write skipped its commit and counts on a queued write to publish.
70
+ #coalescedCommitOwed = false;
41
71
  #pendingWrites = null;
42
72
  #widgetGate = false;
43
73
  // kitty graphics: images outlive reseeds; the scanner owns split APCs.
@@ -349,7 +379,7 @@ export class TerminalReplicaInterpreter {
349
379
  this.#backend.dispose();
350
380
  this.#emit(update);
351
381
  }
352
- async #write(data, continuedTrace) {
382
+ async #write(data, continuedTrace, hasBacklog = () => false) {
353
383
  if (this.#closed || this.#nativeReseedRequested)
354
384
  return;
355
385
  // This optional id is only a controlled next-output probe. It is not a
@@ -370,8 +400,17 @@ export class TerminalReplicaInterpreter {
370
400
  // see. Skipping it matters: every parser write settles on a later timer
371
401
  // turn, so a frame split into dozens of %output chunks would otherwise
372
402
  // serialize dozens of turns and fall behind a 30 fps image stream.
373
- if (scanned.forward.byteLength === 0)
403
+ if (scanned.forward.byteLength === 0) {
404
+ // The queued write a coalesced commit was counting on turned out to be
405
+ // all image payload, and nothing else is queued: publish what it skipped.
406
+ // Not inside a synchronized update: its end, or the sync recovery,
407
+ // publishes the owed commit with the whole frame.
408
+ if (this.#coalescedCommitOwed && !hasBacklog() && !this.#backend.modes().synchronizedOutput) {
409
+ this.#commit(false, this.#pendingWriteDirty ?? undefined, trace);
410
+ this.#publishGraphics();
411
+ }
374
412
  return;
413
+ }
375
414
  // Scanning can prepend an escape retained from the previous chunk. Bound
376
415
  // the actual parser calls too, and union damage across every fragment.
377
416
  for (let offset = 0; offset < scanned.forward.length; offset += MAX_INGEST_BATCH_BYTES) {
@@ -408,6 +447,18 @@ export class TerminalReplicaInterpreter {
408
447
  this.#commit(false, undefined, trace);
409
448
  }
410
449
  else {
450
+ // Coalesce under a flood: more output is already queued, the last commit
451
+ // is recent, and nobody is timing this write. The dirty range stays in
452
+ // #pendingWriteDirty and the next commit (the queued write's, or any
453
+ // control operation's) merges it, so nothing is dropped. The bootstrap
454
+ // seed is never held: before it no commit has run, so one is always due.
455
+ if (trace === null &&
456
+ this.#causalCell === null &&
457
+ hasBacklog() &&
458
+ !this.#coalescedCommitIsDue()) {
459
+ this.#coalescedCommitOwed = true;
460
+ return;
461
+ }
411
462
  this.#commit(false, this.#backend.dirtyRange(), trace);
412
463
  }
413
464
  this.#publishGraphics();
@@ -444,7 +495,26 @@ export class TerminalReplicaInterpreter {
444
495
  this.#syncRecovery.cancel();
445
496
  this.#syncRecovery = null;
446
497
  }
498
+ /** True once a queued flood may publish again: see the two constants above. */
499
+ #coalescedCommitIsDue() {
500
+ const now = this.#scheduler.nowMs();
501
+ if (now - this.#lastCommitAtMs < COALESCED_COMMIT_INTERVAL_MS)
502
+ return false;
503
+ const rest = Math.min(COALESCED_COMMIT_MAX_REST_MS, COALESCED_COMMIT_REST_FACTOR * this.#lastCommitCostMs);
504
+ return now - this.#lastCommitEndMs >= rest;
505
+ }
447
506
  #commit(forceSeed, dirty, trace = null) {
507
+ this.#lastCommitAtMs = this.#scheduler.nowMs();
508
+ this.#coalescedCommitOwed = false;
509
+ try {
510
+ this.#commitNow(forceSeed, dirty, trace);
511
+ }
512
+ finally {
513
+ this.#lastCommitEndMs = this.#scheduler.nowMs();
514
+ this.#lastCommitCostMs = this.#lastCommitEndMs - this.#lastCommitAtMs;
515
+ }
516
+ }
517
+ #commitNow(forceSeed, dirty, trace) {
448
518
  if (this.#backend.requiresNativeReseed()) {
449
519
  if (!this.#nativeReseedRequested) {
450
520
  this.#nativeReseedRequested = true;
@@ -710,7 +780,15 @@ export class TerminalReplicaInterpreter {
710
780
  group.entries.splice(0, completed.length);
711
781
  group.bytes -= length;
712
782
  try {
713
- await this.#write(data, group.trace);
783
+ // Backlog: bytes still in this group, or a newer untraced group
784
+ // already waiting behind it (a group that has not run yet always
785
+ // holds an entry). A traced group is a boundary: its commit must
786
+ // not carry these external bytes. Checked after parsing, when it
787
+ // is current.
788
+ await this.#write(data, group.trace, () => group.entries.length > 0 ||
789
+ (this.#pendingWrites !== null &&
790
+ this.#pendingWrites !== group &&
791
+ this.#pendingWrites.trace === null));
714
792
  }
715
793
  catch (error) {
716
794
  for (const entry of completed)
@@ -5,6 +5,11 @@ import { projectNativeGridRow } from "../mirror/native-grid-projection.js";
5
5
  import { TerminalReplicaInterpreter, } from "./terminal-replica-interpreter.js";
6
6
  import { SYSTEM_SESSION_RUNTIME_SCHEDULER, } from "./runtime-scheduler.js";
7
7
  import { DISABLED_SESSION_RUNTIME_OBSERVABILITY } from "./runtime-observability.js";
8
+ /**
9
+ * How long a pane may have no listener before it is parked (perf F2). Long
10
+ * enough that switching away and back stays warm.
11
+ */
12
+ export const PARK_AFTER_MS = 10_000;
8
13
  /** One parser/replica owner for one semantic pane inside one SessionRuntime. */
9
14
  export class SessionRuntimeTerminalReplicaOwner {
10
15
  generation;
@@ -21,6 +26,11 @@ export class SessionRuntimeTerminalReplicaOwner {
21
26
  #start;
22
27
  #upstream = null;
23
28
  #disposed = false;
29
+ #parkTimer = null;
30
+ #parked = false;
31
+ // From the park until the next reseed lands, the replica is older than tmux.
32
+ // Native backing and history anchors must not pair it with current tmux state.
33
+ #stale = false;
24
34
  #historyAnchors = new HistoryAnchorOwner();
25
35
  #cols = 80;
26
36
  #rows = 24;
@@ -142,12 +152,12 @@ export class SessionRuntimeTerminalReplicaOwner {
142
152
  this.#interpreter.failCausalCell(reason, traceId);
143
153
  }
144
154
  captureHistoryAnchor(proof, historyIndex) {
145
- if (this.#disposed || this.#reseed || this.#waitingForGeometryCapture)
155
+ if (this.#disposed || this.#stale || this.#reseed || this.#waitingForGeometryCapture)
146
156
  return { status: "unavailable" };
147
157
  return this.#historyAnchors.capture(proof, historyIndex);
148
158
  }
149
159
  resolveHistoryAnchor(proof, token) {
150
- if (this.#disposed || this.#reseed || this.#waitingForGeometryCapture)
160
+ if (this.#disposed || this.#stale || this.#reseed || this.#waitingForGeometryCapture)
151
161
  return { status: "unavailable" };
152
162
  return this.#historyAnchors.resolve(proof, token);
153
163
  }
@@ -183,7 +193,7 @@ export class SessionRuntimeTerminalReplicaOwner {
183
193
  if (!upstream?.captureNativeBacking)
184
194
  return { status: "unsupported" };
185
195
  const initial = this.#interpreter.currentSeed();
186
- if (!initial || this.#reseed || this.#waitingForGeometryCapture)
196
+ if (!initial || this.#stale || this.#reseed || this.#waitingForGeometryCapture)
187
197
  return { status: "changed" };
188
198
  const epoch = this.#subscriptionEpoch;
189
199
  const captured = await upstream.captureNativeBacking();
@@ -195,6 +205,7 @@ export class SessionRuntimeTerminalReplicaOwner {
195
205
  return (!this.#disposed &&
196
206
  this.#upstream === upstream &&
197
207
  this.#subscriptionEpoch === epoch &&
208
+ !this.#stale &&
198
209
  !this.#reseed &&
199
210
  !this.#waitingForGeometryCapture &&
200
211
  captured.isCurrent() &&
@@ -250,6 +261,8 @@ export class SessionRuntimeTerminalReplicaOwner {
250
261
  catch {
251
262
  // Bootstrap delivery has the same client-isolation rule as live frames.
252
263
  }
264
+ // The last frame is out; now ask for the reseed that makes it current.
265
+ this.#unpark();
253
266
  }
254
267
  catch (error) {
255
268
  this.#listeners.delete(listener);
@@ -264,9 +277,47 @@ export class SessionRuntimeTerminalReplicaOwner {
264
277
  return;
265
278
  closed = true;
266
279
  this.#listeners.delete(listener);
280
+ if (this.#listeners.size === 0)
281
+ this.#schedulePark();
267
282
  },
268
283
  };
269
284
  }
285
+ /**
286
+ * Park this pane PARK_AFTER_MS after its last listener leaves (perf F2).
287
+ * The owner is the pane's only channel subscriber, so freezing it pauses the
288
+ * pane's output to the daemon's control client (the channel's all-frozen
289
+ * path). tmux keeps running the pane; nothing here is parsed or hashed. The
290
+ * last committed seed stays, so the next listener sees it at once, and
291
+ * thawing runs the channel's requested-pause recovery, which reseeds.
292
+ * Until that reseed lands the replica is stale: history anchors and native
293
+ * backing answer as they do during any reseed, and the reseed's reset then
294
+ * drops every anchor taken before the park.
295
+ */
296
+ #schedulePark() {
297
+ if (this.#disposed || this.#parked)
298
+ return;
299
+ this.#parkTimer?.cancel();
300
+ this.#parkTimer = this.#scheduler.timer(() => {
301
+ this.#parkTimer = null;
302
+ if (this.#disposed || this.#parked || this.#listeners.size > 0 || !this.#upstream)
303
+ return;
304
+ this.#parked = true;
305
+ this.#stale = true;
306
+ this.#upstream.freeze();
307
+ }, PARK_AFTER_MS);
308
+ }
309
+ #unpark() {
310
+ this.#parkTimer?.cancel();
311
+ this.#parkTimer = null;
312
+ if (!this.#parked)
313
+ return;
314
+ this.#parked = false;
315
+ this.#upstream?.thaw();
316
+ }
317
+ /** True while the pane is parked (tests and qualification). */
318
+ get parked() {
319
+ return this.#parked;
320
+ }
270
321
  /** Kitty graphics side channel: current state now (if any), then every change. */
271
322
  subscribeGraphics(listener) {
272
323
  const current = this.#interpreter.currentGraphics();
@@ -301,6 +352,8 @@ export class SessionRuntimeTerminalReplicaOwner {
301
352
  this.#historyAnchors.invalidate();
302
353
  this.#historyTimer?.cancel();
303
354
  this.#historyTimer = null;
355
+ this.#parkTimer?.cancel();
356
+ this.#parkTimer = null;
304
357
  this.#subscriptionEpoch += 1;
305
358
  await this.#interpreter.enqueue({ type: "close", reason });
306
359
  await this.#start.catch(() => undefined);
@@ -335,6 +388,7 @@ export class SessionRuntimeTerminalReplicaOwner {
335
388
  // Output received during the probe makes its count incomparable with
336
389
  // the newer parser state. The dirty flag schedules another check.
337
390
  this.#historyDirty ||
391
+ this.#stale ||
338
392
  this.#reseed ||
339
393
  this.#waitingForGeometryCapture ||
340
394
  size === null)
@@ -398,6 +452,9 @@ export class SessionRuntimeTerminalReplicaOwner {
398
452
  this.#waitingForGeometryCapture = false;
399
453
  const reseed = this.#reseed;
400
454
  this.#reseed = null;
455
+ // A completed capture after the park makes the replica current again.
456
+ if (reseed && !this.#parked)
457
+ this.#stale = false;
401
458
  const lease = reseed ? this.#qualifyReseed(reseed, event.x, event.y) : null;
402
459
  this.#supervise(reseed && lease
403
460
  ? this.#interpreter.enqueue({
@@ -171,7 +171,7 @@ export function mountAutomationRoutes(app: Hono, options: AutomationRoutesOption
171
171
  const panes: AutomationPanesResponse["panes"] = [];
172
172
  const credential = c.req.header(PANE_SOURCE_CREDENTIAL_HEADER);
173
173
  let source: Endpoint | null = null;
174
- for (const scope of await options.owners.refresh()) {
174
+ for (const scope of await options.owners.observe()) {
175
175
  if (!scope.generation) continue;
176
176
  await options.owners.withOwner(
177
177
  { serverId: scope.serverId, generation: scope.generation },
@@ -29,6 +29,8 @@ export interface DaemonFleetFactsObserverOptions {
29
29
  readonly onAgentSessionsChanged: (sessions: readonly string[]) => void;
30
30
  readonly onAgentTurnCompleted: (completion: AgentTurnCompletion) => void;
31
31
  readonly intervalMs?: number;
32
+ /** Interval after {@link FLEET_FACTS_UNCHANGED_TICKS_BEFORE_BACKOFF} unchanged ticks. */
33
+ readonly idleIntervalMs?: number;
32
34
  readonly readTimeoutMs?: number;
33
35
  readonly setTimer?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
34
36
  readonly clearTimer?: (timer: ReturnType<typeof setTimeout>) => void;
@@ -64,6 +66,9 @@ interface ReadyWaiter {
64
66
  export class DaemonFleetFactsObserver {
65
67
  readonly #options: DaemonFleetFactsObserverOptions;
66
68
  readonly #intervalMs: number;
69
+ readonly #idleIntervalMs: number;
70
+ #unchangedTicks = 0;
71
+ #changedThisTick = false;
67
72
  readonly #setTimer: NonNullable<DaemonFleetFactsObserverOptions["setTimer"]>;
68
73
  readonly #clearTimer: NonNullable<DaemonFleetFactsObserverOptions["clearTimer"]>;
69
74
  readonly #refs = new Map<FleetFactsDemand, number>();
@@ -91,6 +96,10 @@ export class DaemonFleetFactsObserver {
91
96
  constructor(options: DaemonFleetFactsObserverOptions) {
92
97
  this.#options = options;
93
98
  this.#intervalMs = options.intervalMs ?? FLEET_FACTS_POLL_MS;
99
+ this.#idleIntervalMs = Math.max(
100
+ this.#intervalMs,
101
+ options.idleIntervalMs ?? FLEET_FACTS_IDLE_POLL_MS,
102
+ );
94
103
  this.#setTimer =
95
104
  options.setTimer ??
96
105
  ((callback, delayMs) => {
@@ -116,6 +125,8 @@ export class DaemonFleetFactsObserver {
116
125
  resolveReady = resolve;
117
126
  });
118
127
  const waiter = { demands: unique, resolve: resolveReady };
128
+ // A new subscriber is activity: poll at the base rate again.
129
+ this.#unchangedTicks = 0;
119
130
  this.#waiters.add(waiter);
120
131
  this.#settleWaiters();
121
132
  this.#queueStart();
@@ -182,10 +193,18 @@ export class DaemonFleetFactsObserver {
182
193
  void this.#runOnce(true);
183
194
  return;
184
195
  }
185
- this.#timer = this.#setTimer(() => {
186
- this.#timer = null;
187
- void this.runOnce();
188
- }, this.#intervalMs);
196
+ // Back off while nothing changes (perf F6); any change resets it.
197
+ this.#unchangedTicks = this.#changedThisTick ? 0 : this.#unchangedTicks + 1;
198
+ this.#changedThisTick = false;
199
+ this.#timer = this.#setTimer(
200
+ () => {
201
+ this.#timer = null;
202
+ void this.runOnce();
203
+ },
204
+ this.#unchangedTicks >= FLEET_FACTS_UNCHANGED_TICKS_BEFORE_BACKOFF
205
+ ? this.#idleIntervalMs
206
+ : this.#intervalMs,
207
+ );
189
208
  },
190
209
  );
191
210
  return this.#running;
@@ -434,31 +453,44 @@ export class DaemonFleetFactsObserver {
434
453
  if (acceptSessions) {
435
454
  const previous = this.#sessionNames;
436
455
  const previousTopology = this.#terminalTopology;
456
+ if (!previous) this.#changedThisTick = true;
437
457
  this.#sessionNames = next.sessions;
438
458
  this.#terminalTopology = next.terminalTopology ?? next.sessions;
439
- if (previous && JSON.stringify(previous) !== JSON.stringify(next.sessions))
459
+ if (previous && JSON.stringify(previous) !== JSON.stringify(next.sessions)) {
460
+ this.#changedThisTick = true;
440
461
  this.#options.onSessionsChanged();
462
+ }
441
463
  if (
442
464
  previousTopology &&
443
465
  JSON.stringify(previousTopology) !== JSON.stringify(this.#terminalTopology)
444
466
  ) {
467
+ this.#changedThisTick = true;
445
468
  this.#options.onTerminalTopologyChanged?.();
446
469
  }
447
470
  }
448
471
  if (acceptAdopted) {
449
472
  const previous = this.#adoptedNames;
450
473
  this.#adoptedNames = next.adopted;
451
- if (previous && JSON.stringify(previous) !== JSON.stringify(next.adopted))
474
+ if (previous && JSON.stringify(previous) !== JSON.stringify(next.adopted)) {
475
+ this.#changedThisTick = true;
452
476
  this.#options.onAdoptedChanged();
477
+ }
453
478
  }
454
479
  }
455
480
 
456
481
  #acceptAgents(next: AgentStateReading): void {
457
482
  const previous = this.#agentFacts;
458
483
  this.#agentFacts = next;
459
- if (!previous) return;
484
+ if (!previous) {
485
+ // A baseline read is not an idle tick.
486
+ this.#changedThisTick = true;
487
+ return;
488
+ }
460
489
  const changed = diffChangedSessions(previous, next);
461
- if (changed.length > 0) this.#options.onAgentSessionsChanged(changed);
490
+ if (changed.length > 0) {
491
+ this.#changedThisTick = true;
492
+ this.#options.onAgentSessionsChanged(changed);
493
+ }
462
494
  for (const completion of diffTurnCompletions(previous, next))
463
495
  this.#options.onAgentTurnCompleted(completion);
464
496
  }
@@ -556,6 +588,15 @@ export function createDefaultFleetFactsReaders(): Pick<
556
588
  * only while a client is subscribed.
557
589
  */
558
590
  export const FLEET_FACTS_POLL_MS = 500;
591
+ /**
592
+ * After this many ticks in a row with no change, re-read every
593
+ * {@link FLEET_FACTS_IDLE_POLL_MS} instead (perf F6). With the app connected
594
+ * and nothing happening, the 500 ms poll was most of the daemon's idle CPU.
595
+ * Any change returns to 500 ms on the next tick, and 1 s still keeps an agent
596
+ * flip visible within about 1 s (#716).
597
+ */
598
+ export const FLEET_FACTS_UNCHANGED_TICKS_BEFORE_BACKOFF = 10;
599
+ export const FLEET_FACTS_IDLE_POLL_MS = 1_000;
559
600
 
560
601
  export const SESSION_COMPOSITION_TMUX_ARGS = [
561
602
  "list-panes",
@@ -99,6 +99,39 @@ export interface LiveSessionSummary {
99
99
  export function discoverLiveSessionSummaries(
100
100
  runTmux: TmuxRunner = _tmuxRunner,
101
101
  ): LiveSessionSummary[] {
102
+ return readLiveSessionSummaries(runTmux) ?? [];
103
+ }
104
+
105
+ /**
106
+ * Whether a failed tmux client says its server is not running. tmux prints
107
+ * "no server running" for a refused connection and names ENOENT for a missing
108
+ * socket; a socket path that is gone before the client starts fails in `lstat`.
109
+ */
110
+ function serverNotRunning(error: unknown): boolean {
111
+ type Failure = { stderr?: unknown; code?: unknown; syscall?: unknown; cause?: unknown };
112
+ // The tmux runners wrap the child-process failure as the `cause` of a TmuxError.
113
+ for (const failure of [error as Failure | null, (error as Failure | null)?.cause as Failure]) {
114
+ if (!failure) continue;
115
+ if (failure.code === "ENOENT" && failure.syscall === "lstat") return true;
116
+ if (
117
+ /^(?:no server running on |error connecting to .* \(No such file or directory\)$)/mu.test(
118
+ String(failure.stderr ?? ""),
119
+ )
120
+ )
121
+ return true;
122
+ }
123
+ return false;
124
+ }
125
+
126
+ /**
127
+ * {@link discoverLiveSessionSummaries}, but null when tmux could not be asked:
128
+ * an unreadable socket, a timeout, a client that would not start. Only a server
129
+ * that is not running has no sessions. An empty list for the other failures
130
+ * tells the user their sessions are gone while they are still running (#753).
131
+ */
132
+ export function readLiveSessionSummaries(
133
+ runTmux: TmuxRunner = _tmuxRunner,
134
+ ): LiveSessionSummary[] | null {
102
135
  let raw: string;
103
136
  try {
104
137
  raw = runTmux([
@@ -107,8 +140,8 @@ export function discoverLiveSessionSummaries(
107
140
  "-F",
108
141
  "#{pid}\t#{session_id}\t#{session_created}\t#{session_name}",
109
142
  ]);
110
- } catch {
111
- return [];
143
+ } catch (error) {
144
+ return serverNotRunning(error) ? [] : null;
112
145
  }
113
146
  if (!raw) return [];
114
147
  const sessions = new Map<string, LiveSessionSummary>();
@@ -16,7 +16,7 @@ import { streamSSE } from "hono/streaming";
16
16
  import { cors } from "hono/cors";
17
17
  import {
18
18
  discoverSessions,
19
- discoverLiveSessionSummaries,
19
+ readLiveSessionSummaries,
20
20
  buildOverviews,
21
21
  buildProjectDetail,
22
22
  type FleetSessionFacts,
@@ -220,12 +220,17 @@ export interface CreateAppOptions {
220
220
  operation: "terminal-resource-handler-admitted" | "terminal-resource-response-projection",
221
221
  ): void;
222
222
  } | null;
223
- /** Injectable live tmux projection for catalog tests and alternate hosts. */
224
- catalogLiveSessions?: () => readonly {
225
- readonly liveSessionId: `live-session.${string}`;
226
- readonly sessionName: string;
227
- readonly paneCount: number;
228
- }[];
223
+ /**
224
+ * Injectable live tmux projection for catalog tests and alternate hosts.
225
+ * Null when tmux could not be asked; an empty list only for no sessions.
226
+ */
227
+ catalogLiveSessions?: () =>
228
+ | readonly {
229
+ readonly liveSessionId: `live-session.${string}`;
230
+ readonly sessionName: string;
231
+ readonly paneCount: number;
232
+ }[]
233
+ | null;
229
234
  /** Injectable daemon-generation-pinned adopted fleet projection. */
230
235
  catalogFleet?: () => FleetSessionFacts[] | null | Promise<FleetSessionFacts[] | null>;
231
236
  fleetPreviewCapture?: (
@@ -881,7 +886,16 @@ export function createApp(options: CreateAppOptions = {}): Hono {
881
886
  },
882
887
  ],
883
888
  );
884
- const observedSessions = options.catalogLiveSessions?.() ?? discoverLiveSessionSummaries();
889
+ const observedSessions = options.catalogLiveSessions
890
+ ? options.catalogLiveSessions()
891
+ : readLiveSessionSummaries();
892
+ // As for the fleet catalog: an unreachable tmux must not replace the
893
+ // client's last known sessions with a successful empty list (#753).
894
+ if (observedSessions === null)
895
+ return c.json(
896
+ { error: "Tmux session discovery is unavailable", code: "tmux-unavailable" },
897
+ 503,
898
+ );
885
899
  const liveSessions = observedSessions.map(({ sessionName, paneCount }) => ({
886
900
  sessionName,
887
901
  fleetSessionId: fleetSessionIdForName(sessionName),
@@ -126,7 +126,7 @@ export function mountTmuxServerRoutes(app: Hono, options: TmuxServerRoutesOption
126
126
  base,
127
127
  route(async (c) =>
128
128
  c.json(
129
- TmuxServersResourceSchemaZ.parse({ version: 1, servers: await options.owners.refresh() }),
129
+ TmuxServersResourceSchemaZ.parse({ version: 1, servers: await options.owners.observe() }),
130
130
  ),
131
131
  ),
132
132
  );
@@ -350,6 +350,50 @@ function runTmuxFeatureProbes(executable: string): CheckResult {
350
350
  }
351
351
  }
352
352
 
353
+ /**
354
+ * PURE — which tmux server the daemon uses, and whether this shell's `tmux`
355
+ * means the same one.
356
+ *
357
+ * A daemon started outside tmux (launchd, systemd, `--headless` from a plain
358
+ * shell) addresses the socket named "default" and gives its tmux clients a
359
+ * scrubbed environment, so it always looks in /tmp/tmux-<uid>/ and ignores
360
+ * TMUX_TMPDIR. A shell that exports TMUX_TMPDIR, or sits in a tmux started
361
+ * with -S or -L, is then on a server that daemon cannot see. The explicit
362
+ * TMUX_IDE_TMUX_SOCKET_PATH / TMUX_IDE_TMUX_SOCKET_NAME settings apply to both.
363
+ */
364
+ export function tmuxServerSocketRow(environment: NodeJS.ProcessEnv, uid: number): CheckResult {
365
+ const defaultDirectory = join("/tmp", `tmux-${String(uid)}`);
366
+ const explicitPath = environment[TMUX_SOCKET_PATH_ENV];
367
+ const explicitName = environment.TMUX_IDE_TMUX_SOCKET_NAME;
368
+ const daemonSocket = explicitPath
369
+ ? explicitPath
370
+ : join(defaultDirectory, explicitName ? explicitName : "default");
371
+ const insideTmux = /^(.*),[0-9]+,[0-9]+$/u.exec(environment.TMUX ?? "")?.[1];
372
+ const shellSocket =
373
+ insideTmux ?? join(environment.TMUX_TMPDIR || "/tmp", `tmux-${String(uid)}`, "default");
374
+ const same = (left: string, right: string): boolean =>
375
+ left.replace(/^\/private\/tmp\//u, "/tmp/") === right.replace(/^\/private\/tmp\//u, "/tmp/");
376
+ if (explicitPath || explicitName || same(shellSocket, daemonSocket))
377
+ return {
378
+ label: "tmux server",
379
+ pass: true,
380
+ detail: `the daemon uses ${daemonSocket}${explicitPath || explicitName ? " (set explicitly)" : ""}`,
381
+ optional: true,
382
+ };
383
+ const why = insideTmux
384
+ ? "this shell is inside a tmux on another socket"
385
+ : "TMUX_TMPDIR is set, and the daemon ignores it";
386
+ return {
387
+ label: "tmux server",
388
+ pass: false,
389
+ detail:
390
+ `this shell's tmux uses ${shellSocket}, a background daemon uses ${daemonSocket} (${why}): ` +
391
+ `it will not see this shell's sessions. Set ${TMUX_SOCKET_PATH_ENV}=${shellSocket} in the daemon's environment` +
392
+ (insideTmux ? "" : ", or unset TMUX_TMPDIR"),
393
+ optional: true,
394
+ };
395
+ }
396
+
353
397
  export function nodeVersionRow(version: string): CheckResult {
354
398
  const major = Number(version.split(".")[0]);
355
399
  const pass = Number.isInteger(major) && major >= 20;
@@ -552,6 +596,8 @@ export async function doctor({
552
596
  ),
553
597
  );
554
598
 
599
+ checks.push(tmuxServerSocketRow(process.env, process.getuid?.() ?? 0));
600
+
555
601
  // Canonical daemon identity + log provenance (credential-free), so a triage
556
602
  // never chases a stale, manually redirected log file.
557
603
  checks.push(
@@ -1,6 +1,12 @@
1
1
  import { withBundledTmuxResources } from "./bundled-tmux.ts";
2
2
  import { execFile } from "node:child_process";
3
- /** Read-only child ownership: TERM at deadline/abort, KILL after grace; settle after close. */
3
+ export const BOUNDED_TMUX_KILL_GRACE_MS = 250;
4
+ /**
5
+ * Read-only child ownership: TERM at deadline/abort, KILL after grace; settle
6
+ * after close. "close" needs every holder of the pipes to let go, so once the
7
+ * child has been killed the read settles one more grace later regardless: a
8
+ * wrapper's lingering grandchild must not turn a deadline into a hang (#839).
9
+ */
4
10
  export function boundedTmuxRead(
5
11
  executable: string,
6
12
  args: readonly string[],
@@ -30,11 +36,31 @@ export function boundedTmuxRead(
30
36
  output = stdout;
31
37
  },
32
38
  );
39
+ let abandon: ReturnType<typeof setTimeout> | null = null;
40
+ let settled = false;
41
+ const settle = () => {
42
+ if (settled) return;
43
+ settled = true;
44
+ clearTimeout(deadline);
45
+ if (escalation) clearTimeout(escalation);
46
+ if (abandon) clearTimeout(abandon);
47
+ options.signal?.removeEventListener("abort", stop);
48
+ if (failure) reject(failure);
49
+ else resolve(output);
50
+ };
33
51
  const stop = () => {
34
52
  failure ??= new Error("Tmux read cancelled or deadline exceeded");
35
53
  if (escalation) return;
36
54
  child.kill("SIGTERM");
37
- escalation = setTimeout(() => child.kill("SIGKILL"), 250);
55
+ escalation = setTimeout(() => {
56
+ child.kill("SIGKILL");
57
+ abandon = setTimeout(() => {
58
+ child.stdout?.destroy();
59
+ child.stderr?.destroy();
60
+ settle();
61
+ }, BOUNDED_TMUX_KILL_GRACE_MS);
62
+ abandon.unref?.();
63
+ }, BOUNDED_TMUX_KILL_GRACE_MS);
38
64
  escalation.unref?.();
39
65
  };
40
66
  const deadline = setTimeout(stop, options.timeoutMs ?? 5000);
@@ -43,13 +69,7 @@ export function boundedTmuxRead(
43
69
  child.once("error", (error) => {
44
70
  failure ??= error;
45
71
  });
46
- child.once("close", () => {
47
- clearTimeout(deadline);
48
- if (escalation) clearTimeout(escalation);
49
- options.signal?.removeEventListener("abort", stop);
50
- if (failure) reject(failure);
51
- else resolve(output);
52
- });
72
+ child.once("close", settle);
53
73
  if (options.signal?.aborted) stop();
54
74
  });
55
75
  }