tmux-ide 2.9.23 → 2.9.24

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 (39) hide show
  1. package/bin/cli.js +285 -36
  2. package/package.json +1 -1
  3. package/packages/daemon/dist/command-center/tmux-servers.js +11 -0
  4. package/packages/daemon/dist/lib/daemon-embed.js +16 -8
  5. package/packages/daemon/dist/lib/home-agent-observer.js +50 -0
  6. package/packages/daemon/dist/lib/machine-agents.js +18 -1
  7. package/packages/daemon/dist/lib/orphaned-control-clients.js +162 -0
  8. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +32 -9
  9. package/packages/daemon/dist/lib/tmux-server-owner.js +26 -4
  10. package/packages/daemon/dist/lib/workspace-promotion.js +24 -3
  11. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  12. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  13. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  14. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  15. package/packages/daemon/dist/terminal/attachments/native-runtime.js +17 -2
  16. package/packages/daemon/dist/terminal/mirror/session-channel.js +2 -1
  17. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +8 -0
  18. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +57 -4
  19. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +18 -7
  20. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +17 -0
  21. package/packages/daemon/dist/tui/mirror/runtime/application-machine-navigation.js +4 -2
  22. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +55 -14
  23. package/packages/daemon/src/command-center/tmux-servers.ts +11 -0
  24. package/packages/daemon/src/lib/daemon-embed.ts +52 -7
  25. package/packages/daemon/src/lib/home-agent-observer.ts +53 -0
  26. package/packages/daemon/src/lib/machine-agents.ts +25 -1
  27. package/packages/daemon/src/lib/orphaned-control-clients.ts +215 -0
  28. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +32 -8
  29. package/packages/daemon/src/lib/tmux-server-owner.ts +28 -3
  30. package/packages/daemon/src/lib/workspace-promotion.ts +26 -3
  31. package/packages/daemon/src/terminal/attachments/native-runtime.ts +21 -2
  32. package/packages/daemon/src/terminal/mirror/session-channel.ts +2 -1
  33. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +8 -0
  34. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +69 -4
  35. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +30 -13
  36. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +38 -1
  37. package/packages/daemon/src/tui/mirror/runtime/application-machine-navigation.ts +7 -2
  38. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +4 -4
  39. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +71 -17
@@ -0,0 +1,215 @@
1
+ import { execFile } from "node:child_process";
2
+ import { logger } from "./log.ts";
3
+
4
+ /**
5
+ * A daemon that dies without running its stop (SIGKILL, a crash) can leave a
6
+ * tmux control client behind. Measured on a private server: with pane output
7
+ * flowing and the daemon stopped for a few seconds before the kill, the
8
+ * client stays alive with init as its parent. tmux no longer lists it as a
9
+ * client, yet a later `kill-server` never finishes while it lives: the socket
10
+ * keeps a server with no sessions and no new server can take its place.
11
+ * A daemon therefore ends the control clients a dead daemon left on a server
12
+ * it owns: when it takes ownership, and when that server answers a catalog
13
+ * read with no sessions or does not answer it at all.
14
+ */
15
+ export type TmuxServerSelector =
16
+ | { readonly kind: "path"; readonly path: string }
17
+ | { readonly kind: "name"; readonly name: string };
18
+
19
+ export interface ProcessRow {
20
+ readonly pid: number;
21
+ readonly ppid: number;
22
+ readonly command: string;
23
+ }
24
+
25
+ export interface OrphanedControlClientIo {
26
+ /** Every process of this user: tmux does not list a client that is leaving. */
27
+ readonly listProcesses: () => Promise<readonly ProcessRow[]>;
28
+ kill: (pid: number, signal: "SIGTERM" | "SIGKILL") => void;
29
+ readonly isAlive: (pid: number) => boolean;
30
+ readonly delay: (ms: number) => Promise<void>;
31
+ }
32
+
33
+ export const ORPHAN_KILL_GRACE_MS = 500;
34
+
35
+ /** PURE. `ps -o pid=,ppid=,command=` output, one process per line. */
36
+ export function parseProcessTable(text: string): ProcessRow[] {
37
+ const rows: ProcessRow[] = [];
38
+ for (const line of text.split("\n")) {
39
+ const match = /^\s*([0-9]+)\s+([0-9]+)\s+(.+)$/u.exec(line);
40
+ if (match) rows.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3]! });
41
+ }
42
+ return rows;
43
+ }
44
+
45
+ /** The attach flags only this daemon's control client uses (mirrorControlAttachArgs). */
46
+ export function isTmuxIdeControlClientCommand(command: string): boolean {
47
+ return (
48
+ /(?:^|\s)-C(?:\s|$)/u.test(command) &&
49
+ /ignore-size,pause-after=[0-9]+,active-pane/u.test(command)
50
+ );
51
+ }
52
+
53
+ const withoutPrivate = (path: string): string => path.replace(/^\/private(?=\/)/u, "");
54
+
55
+ /** PURE. Does this tmux command line address the given server? */
56
+ export function commandTargetsServer(command: string, selector: TmuxServerSelector): boolean {
57
+ const words = command.split(/\s+/u);
58
+ for (let index = 0; index < words.length; index += 1) {
59
+ const word = words[index]!;
60
+ if (word === "-C") return false;
61
+ const flag = selector.kind === "path" ? "-S" : "-L";
62
+ const value = word === flag ? words[index + 1] : word.startsWith(flag) ? word.slice(2) : null;
63
+ if (value === null || value === undefined || value === "") continue;
64
+ return selector.kind === "path"
65
+ ? withoutPrivate(value) === withoutPrivate(selector.path)
66
+ : value === selector.name;
67
+ }
68
+ return false;
69
+ }
70
+
71
+ /** init, or a service manager that adopts orphans in its place. */
72
+ function adoptsOrphans(pid: number, command: string | null): boolean {
73
+ if (pid === 1) return true;
74
+ // The command's own name (its first word, with or without a path), never a
75
+ // word further on: a daemon run as `… --supervised launchd-user` is no manager.
76
+ return command !== null && /^(?:\S*\/)?(?:systemd|launchd|init)(?:\s|$)/u.test(command);
77
+ }
78
+
79
+ /**
80
+ * Ends tmux-ide control clients of this server whose daemon is gone. Never
81
+ * this daemon's own clients, another live daemon's, another server's, or any
82
+ * other program's. Returns the pids it ended. Failures end the pass; they
83
+ * never throw.
84
+ */
85
+ export async function evictOrphanedControlClients(
86
+ io: OrphanedControlClientIo,
87
+ ownPid: number,
88
+ selector: TmuxServerSelector,
89
+ ): Promise<number[]> {
90
+ let processes: readonly ProcessRow[];
91
+ try {
92
+ processes = await io.listProcesses();
93
+ } catch {
94
+ return [];
95
+ }
96
+ const byPid = new Map(processes.map((row) => [row.pid, row]));
97
+ const evicted: number[] = [];
98
+ for (const client of processes) {
99
+ if (
100
+ client.pid <= 1 ||
101
+ client.pid === ownPid ||
102
+ client.ppid === ownPid ||
103
+ !isTmuxIdeControlClientCommand(client.command) ||
104
+ !commandTargetsServer(client.command, selector) ||
105
+ !adoptsOrphans(client.ppid, byPid.get(client.ppid)?.command ?? null)
106
+ )
107
+ continue;
108
+ try {
109
+ io.kill(client.pid, "SIGTERM");
110
+ await io.delay(ORPHAN_KILL_GRACE_MS);
111
+ if (io.isAlive(client.pid)) io.kill(client.pid, "SIGKILL");
112
+ evicted.push(client.pid);
113
+ } catch {
114
+ // One client that cannot be signalled does not stop the pass.
115
+ }
116
+ }
117
+ return evicted;
118
+ }
119
+
120
+ /** The real process table and signals. */
121
+ export function orphanedControlClientIo(): OrphanedControlClientIo {
122
+ return {
123
+ listProcesses: () =>
124
+ new Promise((resolve, reject) => {
125
+ execFile(
126
+ "/bin/ps",
127
+ ["-xww", "-o", "pid=,ppid=,command="],
128
+ {
129
+ encoding: "utf8",
130
+ timeout: 3_000,
131
+ maxBuffer: 16 * 1024 * 1024,
132
+ env: { LC_ALL: "C", PATH: "/usr/bin:/bin" },
133
+ },
134
+ (error, stdout) => (error ? reject(error) : resolve(parseProcessTable(stdout))),
135
+ );
136
+ }),
137
+ kill: (pid, signal) => {
138
+ process.kill(pid, signal);
139
+ },
140
+ isAlive: (pid) => {
141
+ try {
142
+ process.kill(pid, 0);
143
+ return true;
144
+ } catch (error) {
145
+ return (error as NodeJS.ErrnoException).code === "EPERM";
146
+ }
147
+ },
148
+ delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
149
+ };
150
+ }
151
+
152
+ /** What a catalog read found: an answer without sessions, or no answer. */
153
+ export type TmuxServerTrouble = "no-sessions" | "unanswered";
154
+
155
+ export const EMPTY_SERVER_PASS_INTERVAL_MS = 10_000;
156
+ export const EMPTY_SERVER_LOG_INTERVAL_MS = 60_000;
157
+
158
+ /**
159
+ * One per owned server. Neither call is awaited by the owner, delays it or
160
+ * fails it.
161
+ * - `onOwnership`: one pass when the daemon takes the server.
162
+ * - `onTrouble`: a catalog read found the server with no sessions, or got no
163
+ * answer from a server whose socket is still there. A tmux server normally
164
+ * exits with its last session, so either it is configured to stay or it
165
+ * cannot exit. At most one pass per 10 s, and one warning per minute that
166
+ * names the state: scoped reads fail in it, and nothing else says why.
167
+ */
168
+ export function createOrphanedControlClientWatch(options: {
169
+ readonly selector: TmuxServerSelector;
170
+ readonly serverId: string | null;
171
+ readonly io?: OrphanedControlClientIo;
172
+ readonly now?: () => number;
173
+ }): { onOwnership(): Promise<void>; onTrouble(kind: TmuxServerTrouble): Promise<void> } {
174
+ const io = options.io ?? orphanedControlClientIo();
175
+ const now = options.now ?? Date.now;
176
+ const fields = options.serverId ? { serverId: options.serverId } : {};
177
+ let lastPassAt = Number.NEGATIVE_INFINITY;
178
+ let lastLogAt = Number.NEGATIVE_INFINITY;
179
+ let running: Promise<number[]> | null = null;
180
+ const pass = (): Promise<number[]> => {
181
+ if (running) return running;
182
+ lastPassAt = now();
183
+ const current = evictOrphanedControlClients(io, process.pid, options.selector)
184
+ .catch((): number[] => [])
185
+ .then((pids) => {
186
+ if (pids.length > 0)
187
+ logger.warn("tmux-server-owners", "ended control clients a dead daemon left attached", {
188
+ ...fields,
189
+ pids,
190
+ });
191
+ return pids;
192
+ })
193
+ .finally(() => {
194
+ if (running === current) running = null;
195
+ });
196
+ running = current;
197
+ return current;
198
+ };
199
+ return {
200
+ onOwnership: () => pass().then(() => undefined),
201
+ async onTrouble(kind) {
202
+ if (now() - lastPassAt < EMPTY_SERVER_PASS_INTERVAL_MS) return;
203
+ const pids = await pass();
204
+ if (now() - lastLogAt < EMPTY_SERVER_LOG_INTERVAL_MS) return;
205
+ lastLogAt = now();
206
+ logger.warn(
207
+ "tmux-server-owners",
208
+ kind === "no-sessions"
209
+ ? "tmux server answers with no sessions"
210
+ : "tmux server does not answer its catalog",
211
+ { ...fields, endedControlClients: pids.length },
212
+ );
213
+ },
214
+ };
215
+ }
@@ -77,15 +77,26 @@ export const DEFAULT_HOOK_HEALTHCHECK_SCHEDULE: HookHealthcheckSchedule = Object
77
77
 
78
78
  export type HookHealthcheckOutcome = "healthy" | "repaired" | "failed";
79
79
 
80
- /** Pure cadence rule: healthy checks double the wait up to the cap; anything else resets it. */
80
+ /**
81
+ * Pure cadence rule: healthy checks double the wait up to the cap; a repair or
82
+ * failure resets it to the base. A check that is unhealthy again right after
83
+ * one that was (`consecutiveUnhealthy` of 2 or more) backs off as well: on a
84
+ * tmux server that is shutting down but cannot exit, every repair "succeeds"
85
+ * and is gone at the next check, and the base cadence then cost about 400 tmux
86
+ * calls a minute for as long as the server lingered.
87
+ */
81
88
  export function nextHookHealthcheckDelay(
82
89
  previousMs: number,
83
90
  outcome: HookHealthcheckOutcome,
84
91
  schedule: HookHealthcheckSchedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE,
92
+ consecutiveUnhealthy = 1,
85
93
  ): number {
86
94
  const base = Math.max(1, Math.floor(schedule.baseMs));
87
95
  const max = Math.max(base, Math.floor(schedule.maxMs));
88
- if (outcome !== "healthy") return base;
96
+ if (outcome !== "healthy") {
97
+ const streak = Math.max(1, Math.min(32, Math.floor(consecutiveUnhealthy) || 1));
98
+ return Math.min(base * 2 ** (streak - 1), max);
99
+ }
89
100
  const previous = Number.isFinite(previousMs) ? Math.max(base, Math.floor(previousMs)) : base;
90
101
  return Math.min(previous * 2, max);
91
102
  }
@@ -371,6 +382,8 @@ export class TmuxExternalInteractionObserver {
371
382
  readonly #healthcheckSchedule: HookHealthcheckSchedule;
372
383
  #healthcheckDelayMs: number;
373
384
  #lastHealthcheckOutcome: HookHealthcheckOutcome = "failed";
385
+ /** Scheduled checks in a row that did not find the hooks intact. */
386
+ #unhealthyChecks = 0;
374
387
  readonly #onAvailability: ((available: boolean) => void) | undefined;
375
388
  readonly #onGap: ((gap: ExternalTmuxInteractionGap) => void) | undefined;
376
389
  #tmuxWork: Promise<unknown> = Promise.resolve();
@@ -520,12 +533,14 @@ export class TmuxExternalInteractionObserver {
520
533
  if (!this.#abort.signal.aborted) this.#reportGap("hook-repair-failed");
521
534
  outcome = "failed";
522
535
  }
536
+ this.#unhealthyChecks = outcome === "healthy" ? 0 : this.#unhealthyChecks + 1;
523
537
  // A signal-path reset that landed during this check wins over the outcome.
524
538
  if (this.#healthcheckDelayMs === delayBefore) {
525
539
  this.#healthcheckDelayMs = nextHookHealthcheckDelay(
526
540
  delayBefore,
527
541
  outcome,
528
542
  this.#healthcheckSchedule,
543
+ this.#unhealthyChecks,
529
544
  );
530
545
  }
531
546
  if (this.#hookHealthcheck === null) this.#scheduleHealthcheck();
@@ -647,11 +662,20 @@ export class TmuxExternalInteractionObserver {
647
662
  const work = this.#serializeTmux(async () => {
648
663
  const finish = this.#beginDiagnostic("healthcheck");
649
664
  try {
650
- if (await this.#ownedHooksPresent(this.#abort.signal)) {
665
+ const hooks = await this.#ownedHooksPresent(this.#abort.signal);
666
+ if (hooks === "present") {
651
667
  this.#lastHealthcheckOutcome = "healthy";
652
668
  finish(true);
653
669
  return;
654
670
  }
671
+ if (hooks === "unknown") {
672
+ // The check could not be made (tmux timed out or could not be
673
+ // started). That says nothing about the hooks: leave them, report
674
+ // no gap, and ask again at the base cadence.
675
+ this.#lastHealthcheckOutcome = "failed";
676
+ finish(false);
677
+ return;
678
+ }
655
679
  // Hooks that were installed and are now gone dropped every interaction
656
680
  // since their removal; the repair restores future observation only.
657
681
  if (this.#installed) this.#reportGap("hooks-replaced");
@@ -917,7 +941,7 @@ export class TmuxExternalInteractionObserver {
917
941
  this.#setInstalled(false);
918
942
  }
919
943
 
920
- async #ownedHooksPresent(signal?: AbortSignal): Promise<boolean> {
944
+ async #ownedHooksPresent(signal?: AbortSignal): Promise<"present" | "missing" | "unknown"> {
921
945
  // One client verifies both hook arrays: tmux runs the `;`-separated list in
922
946
  // a single command queue and prints each array's lines in order.
923
947
  let output: string;
@@ -927,12 +951,12 @@ export class TmuxExternalInteractionObserver {
927
951
  signal,
928
952
  );
929
953
  } catch {
930
- return false;
954
+ return "unknown";
931
955
  }
932
- return (
933
- ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
956
+ return ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
934
957
  ownedHookInstalled(output, "after-capture-pane", this.#bufferName)
935
- );
958
+ ? "present"
959
+ : "missing";
936
960
  }
937
961
 
938
962
  get available(): boolean {
@@ -54,6 +54,7 @@ import { liveSessionIdForNativeIdentity } from "../terminal/protocol/live-sessio
54
54
  import { SessionRuntimeRegistry } from "../terminal/session-runtime/registry.ts";
55
55
  import { createSessionRuntimeMultiplexerBackend } from "../terminal/session-runtime/multiplexer-backend.ts";
56
56
  import { TmuxExternalInteractionObserver } from "./tmux-external-interaction-observer.ts";
57
+ import { createOrphanedControlClientWatch } from "./orphaned-control-clients.ts";
57
58
  import { InteractionReceiptJournal } from "./interaction-receipt-journal.ts";
58
59
  import { InteractionObservationStatusStore } from "./interaction-observation-status.ts";
59
60
  import { InteractionEvidenceAuthority } from "./interaction-evidence-authority.ts";
@@ -118,9 +119,18 @@ export function createNativeTmuxServerCatalog(
118
119
  workspaceRegistry: WorkspaceRegistry,
119
120
  run: (args: readonly string[], signal?: AbortSignal) => Promise<string>,
120
121
  assertOpen: () => void = () => undefined,
122
+ /** Told when the server has no sessions or does not answer; never awaited. */
123
+ onTrouble?: (kind: "no-sessions" | "unanswered") => unknown,
121
124
  ): () => Promise<NativeLiveSessionSummary[]> {
122
125
  return async (): Promise<NativeLiveSessionSummary[]> => {
123
126
  assertOpen();
127
+ const tell = (kind: "no-sessions" | "unanswered"): void => {
128
+ try {
129
+ void Promise.resolve(onTrouble?.(kind)).catch(() => undefined);
130
+ } catch {
131
+ /* A watcher never decides the catalog. */
132
+ }
133
+ };
124
134
  const raw = await run(
125
135
  [
126
136
  "-N",
@@ -139,7 +149,10 @@ export function createNativeTmuxServerCatalog(
139
149
  .join(" "),
140
150
  ],
141
151
  AbortSignal.timeout(2_000),
142
- );
152
+ ).catch((error: unknown) => {
153
+ tell("unanswered");
154
+ throw error;
155
+ });
143
156
  assertOpen();
144
157
  const rows = new Map<
145
158
  string,
@@ -153,7 +166,9 @@ export function createNativeTmuxServerCatalog(
153
166
  >();
154
167
  // Only the successful server-side zero-session branch proves emptiness.
155
168
  // Command errors, unsupported formats and unwitnessed blank output stay failures.
156
- const lines = raw.trim() === "tmux-ide-empty-catalog-v1" ? [] : raw.trim().split("\n");
169
+ const empty = raw.trim() === "tmux-ide-empty-catalog-v1";
170
+ if (empty) tell("no-sessions");
171
+ const lines = empty ? [] : raw.trim().split("\n");
157
172
  for (const line of lines) {
158
173
  const [pid, id, created, name, pane, window, activity, ...pathParts] = line.split("\t");
159
174
  const dir = pathParts.join("\t");
@@ -241,6 +256,11 @@ export async function createNativeTmuxServerOwner(options: NativeTmuxServerOwner
241
256
  authority,
242
257
  nativeServerIdentity,
243
258
  );
259
+ const orphanWatch = createOrphanedControlClientWatch({
260
+ selector: authority.socketSelector,
261
+ serverId: options.serverId,
262
+ });
263
+ void orphanWatch.onOwnership();
244
264
  const multiplexer = new WorkspaceMultiplexerAuthority({
245
265
  daemonInstanceId: generation,
246
266
  registry: workspaceRegistry,
@@ -540,7 +560,12 @@ export async function createNativeTmuxServerOwner(options: NativeTmuxServerOwner
540
560
  registry: sessionRuntimeRegistry,
541
561
  resolveSession: (name) => workspaceRegistry.get(name)?.sessionName ?? null,
542
562
  });
543
- const catalog = createNativeTmuxServerCatalog(workspaceRegistry, generationRunAsync, assertOpen);
563
+ const catalog = createNativeTmuxServerCatalog(
564
+ workspaceRegistry,
565
+ generationRunAsync,
566
+ assertOpen,
567
+ orphanWatch.onTrouble,
568
+ );
544
569
  const sessionCreator = createNativeTmuxSessionCreator({
545
570
  generation,
546
571
  registry: workspaceRegistry,
@@ -149,6 +149,12 @@ const ERROR_MESSAGES: Readonly<Record<WorkspacePromotionErrorCode, string>> = {
149
149
  operation_capacity: "The daemon has reached its bounded workspace-promote operation capacity.",
150
150
  };
151
151
 
152
+ /**
153
+ * How often a promotion stamps and proves a session whose pane inventory
154
+ * changed between the proof's two reads, before it refuses.
155
+ */
156
+ export const PROMOTION_PROOF_ATTEMPTS = 3;
157
+
152
158
  export class WorkspacePromotionError extends Error {
153
159
  readonly code: WorkspacePromotionErrorCode;
154
160
  readonly context: Readonly<Record<string, string>>;
@@ -594,9 +600,26 @@ export class WorkspacePromotionAuthority {
594
600
  : derivePromotionIdentity(session.sessionName);
595
601
  this.#assertConflictFreeIdentity(identity);
596
602
 
597
- const canonicalRoot = await this.#stampSession(request, session, identity);
598
- this.#assertActive(request.operationId);
599
- await this.#verifyPromotedInventory(session.sessionId, identity);
603
+ // Another tmux client may split or close a pane while the session is
604
+ // being proved (an agent does it all day). The proof then cannot hold:
605
+ // stamp what is there now and prove again, a bounded number of times.
606
+ let canonicalRoot!: string;
607
+ for (let attempt = 1; ; attempt += 1) {
608
+ canonicalRoot = await this.#stampSession(request, session, identity);
609
+ this.#assertActive(request.operationId);
610
+ try {
611
+ await this.#verifyPromotedInventory(session.sessionId, identity);
612
+ break;
613
+ } catch (error) {
614
+ if (
615
+ attempt >= PROMOTION_PROOF_ATTEMPTS ||
616
+ !(error instanceof WorkspacePromotionError) ||
617
+ error.context.reason !== "inventory_changed_during_proof"
618
+ )
619
+ throw error;
620
+ this.#assertActive(request.operationId);
621
+ }
622
+ }
600
623
  await this.#publishFleetEnrollment(request, session, identity);
601
624
 
602
625
  // Catalog discovery can admit this session while the native stamping
@@ -1628,6 +1628,25 @@ export class WorkspaceTerminalInventoryRuntime {
1628
1628
  if (this.#disposed) throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
1629
1629
  const epoch = this.#inventoryEpoch;
1630
1630
  const nativeEpoch = this.#nativeServerEpoch?.() ?? null;
1631
+ // An invalidation can also land while the snapshot is being adopted. That
1632
+ // publication is refused, as before, and the inventory is read again: it
1633
+ // used to fail the caller, and at startup the caller is the daemon.
1634
+ const publish = async (
1635
+ value: NativeTerminalInventorySnapshot,
1636
+ publicationSignal: AbortSignal,
1637
+ ): Promise<NativeTerminalInventorySnapshot> => {
1638
+ try {
1639
+ return await this.#publishInventory(value, nativeEpoch, publicationSignal, epoch);
1640
+ } catch (error) {
1641
+ if (this.#disposed || signal?.aborted || this.#inventoryEpoch === epoch) throw error;
1642
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1643
+ return this.#readInventory(signal, staleRetry + 1);
1644
+ throw new NativeTerminalAttachmentRuntimeError(
1645
+ "discovery-failed",
1646
+ "overtaken-by-invalidations",
1647
+ );
1648
+ }
1649
+ };
1631
1650
  if (signal) {
1632
1651
  if (signal.aborted) throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
1633
1652
  let snapshot: NativeTerminalInventorySnapshot;
@@ -1653,7 +1672,7 @@ export class WorkspaceTerminalInventoryRuntime {
1653
1672
  "overtaken-by-invalidations",
1654
1673
  );
1655
1674
  }
1656
- return this.#publishInventory(snapshot, nativeEpoch, signal, epoch);
1675
+ return publish(snapshot, signal);
1657
1676
  }
1658
1677
  if (this.#inventoryRead?.epoch === epoch) return this.#inventoryRead.promise;
1659
1678
  const abort = new AbortController();
@@ -1680,7 +1699,7 @@ export class WorkspaceTerminalInventoryRuntime {
1680
1699
  "overtaken-by-invalidations",
1681
1700
  );
1682
1701
  }
1683
- return this.#publishInventory(value, nativeEpoch, abort.signal, epoch);
1702
+ return publish(value, abort.signal);
1684
1703
  })().finally(() => {
1685
1704
  if (this.#inventoryRead?.promise === promise) this.#inventoryRead = null;
1686
1705
  });
@@ -3825,7 +3825,8 @@ export class SessionChannel {
3825
3825
  !leftLayout ||
3826
3826
  !rightLayout ||
3827
3827
  leftWindow.semanticId !== rightWindow.semanticId ||
3828
- leftWindow.name !== rightWindow.name ||
3828
+ // Not the name: tmux derives it from the running command, and the
3829
+ // pane rows' own check ignores it too (sameSessionPaneInventory, #730).
3829
3830
  leftWindow.paneBorderStatus !== rightWindow.paneBorderStatus ||
3830
3831
  leftWindow.modeKeys !== rightWindow.modeKeys ||
3831
3832
  !layoutIdentitiesEqual(leftLayout, rightLayout)
@@ -3238,6 +3238,14 @@ export class PaneStreamLiveConnection {
3238
3238
  ].includes(rawCode)
3239
3239
  ? rawCode
3240
3240
  : "stream-unavailable";
3241
+ // A refused intent is answered to the client only; without this line a
3242
+ // click that did nothing leaves no trace in either log (#764).
3243
+ logger.info("pane-stream", "intent rejected", {
3244
+ session: this.#descriptor.sessionName,
3245
+ clientId: this.#clientId,
3246
+ verb: intent.verb,
3247
+ code,
3248
+ });
3241
3249
  this.#sendFrame(null, {
3242
3250
  type: "semantic-intent-ack",
3243
3251
  operationId,
@@ -1,5 +1,6 @@
1
1
  import type { HomeAgentRow } from "./application-home-agents.ts";
2
2
  import type { ApplicationGenerationStartResult } from "./application-generation-starter.ts";
3
+ import type { AdmittedPaneSelectionOutcome } from "./application-terminal-interaction-controller.ts";
3
4
 
4
5
  export type HomeAgentNavigationSource = "keyboard" | "mouse";
5
6
  export type HomeAgentNavigationTarget = Pick<
@@ -22,6 +23,7 @@ export type HomeAgentNavigationFailure =
22
23
  | "attach-failed"
23
24
  | "generation-changed"
24
25
  | "pane-removed"
26
+ | "selection-failed"
25
27
  | "superseded";
26
28
 
27
29
  export interface HomeAgentNavigationResult {
@@ -53,7 +55,7 @@ export function createApplicationHomeAgentNavigator(options: {
53
55
  paneId: string,
54
56
  source: HomeAgentNavigationSource,
55
57
  admission?: Promise<boolean>,
56
- ) => void;
58
+ ) => void | Promise<AdmittedPaneSelectionOutcome> | undefined;
57
59
  /**
58
60
  * Home's roster can list an agent a moment before the attached session does.
59
61
  * Resolves true once `listed()` holds, false on the bound, abort or a
@@ -64,6 +66,16 @@ export function createApplicationHomeAgentNavigator(options: {
64
66
  listed: () => boolean,
65
67
  signal: AbortSignal,
66
68
  ) => Promise<boolean>;
69
+ /**
70
+ * "Is it current" answers no while the roster re-reads a session, which it
71
+ * does whenever an agent appears or changes: exactly when a row gets clicked.
72
+ * Resolves once the roster has settled for this target (true: current again)
73
+ * or a bound passed. Without it a click during a re-read is refused at once.
74
+ */
75
+ readonly waitForCurrentTarget?: (
76
+ target: HomeAgentNavigationTarget,
77
+ signal: AbortSignal,
78
+ ) => Promise<boolean>;
67
79
  readonly showTerminals: (source: HomeAgentNavigationSource) => void;
68
80
  readonly setNote: (note: string | null) => void;
69
81
  }) {
@@ -90,6 +102,23 @@ export function createApplicationHomeAgentNavigator(options: {
90
102
  !!current?.agents.some(
91
103
  (agent) => agent.id === target.agentId && agent.paneId === target.paneId,
92
104
  );
105
+ /** Before a check that would refuse a stale target: let a re-reading roster finish. */
106
+ const settleTarget = async (
107
+ token: number,
108
+ target: HomeAgentNavigationTarget,
109
+ signal: AbortSignal,
110
+ ): Promise<void> => {
111
+ if (!options.waitForCurrentTarget || !active(token) || options.isCurrentTarget(target)) return;
112
+ if (waitingNote !== token) {
113
+ options.setNote(`Waiting for agent in ${target.sessionName}…`);
114
+ waitingNote = token;
115
+ }
116
+ try {
117
+ await options.waitForCurrentTarget(target, signal);
118
+ } catch {
119
+ // A failed wait decides nothing; the check that follows does.
120
+ }
121
+ };
93
122
  /** Every admission check; null admits. Notes are set only for a refusal. */
94
123
  const refusal = (
95
124
  token: number,
@@ -160,7 +189,7 @@ export function createApplicationHomeAgentNavigator(options: {
160
189
  const admission = new Promise<boolean>((resolve) => {
161
190
  settle = resolve;
162
191
  });
163
- options.selectPane(target.paneId!, source, admission);
192
+ const selection = options.selectPane(target.paneId!, source, admission);
164
193
  // The cold path's "Opening agent in …" note, for the warm wait.
165
194
  options.setNote(`Waiting for agent in ${target.sessionName}…`);
166
195
  waitingNote = token;
@@ -169,11 +198,36 @@ export function createApplicationHomeAgentNavigator(options: {
169
198
  } catch {
170
199
  // A failed wait is a refusal below, never an admission.
171
200
  }
172
- if (waitingNote === token) waitingNote = null;
201
+ if (options.waitForCurrentTarget && !options.isCurrentTarget(target))
202
+ await settleTarget(token, target, signal);
173
203
  // A refusal replaces the note; an admission clears it below.
174
204
  const refused = refusal(token, target, generationKey);
175
205
  settle(refused === null);
176
- if (refused) return refused;
206
+ if (refused) {
207
+ if (waitingNote === token) waitingNote = null;
208
+ return refused;
209
+ }
210
+ // Admitted is not selected: the runtime may still refuse the pane, or take
211
+ // a moment for a pane that was just created. The wait note stays until it
212
+ // answers, and the terminals are shown only for a pane that was selected.
213
+ let selected: AdmittedPaneSelectionOutcome;
214
+ try {
215
+ selected = (await selection) ?? "selected";
216
+ } catch {
217
+ selected = "failed";
218
+ }
219
+ if (waitingNote === token) waitingNote = null;
220
+ if (!active(token)) return { opened: false, failure: "superseded" };
221
+ if (selected === "superseded" || selected === "not-admitted") {
222
+ options.setNote(null);
223
+ return { opened: false, failure: "superseded" };
224
+ }
225
+ if (selected === "failed")
226
+ return failure(
227
+ token,
228
+ "selection-failed",
229
+ "That agent's terminal could not be selected yet. Select the agent again.",
230
+ );
177
231
  options.showTerminals(source);
178
232
  options.setNote(null);
179
233
  return { opened: true };
@@ -193,6 +247,12 @@ export function createApplicationHomeAgentNavigator(options: {
193
247
  try {
194
248
  if (!target.paneId)
195
249
  return failure(token, "unavailable", "This agent has no available terminal to open.");
250
+ // Only when it is needed: a warm open of a current target stays synchronous.
251
+ if (options.waitForCurrentTarget && !options.isCurrentTarget(target)) {
252
+ await settleTarget(token, target, controller.signal);
253
+ if (!active(token)) return { opened: false, failure: "superseded" };
254
+ if (waitingNote === token) waitingNote = null;
255
+ }
196
256
  if (!options.isCurrentTarget(target))
197
257
  return failure(
198
258
  token,
@@ -247,6 +307,11 @@ export function createApplicationHomeAgentNavigator(options: {
247
307
  "The session opened, but agent details are not ready. Return Home and retry.",
248
308
  );
249
309
  }
310
+ if (options.waitForCurrentTarget && !options.isCurrentTarget(target)) {
311
+ await settleTarget(token, target, controller.signal);
312
+ if (!active(token)) return { opened: false, failure: "superseded" };
313
+ if (waitingNote === token) waitingNote = null;
314
+ }
250
315
  return admit(token, target, source, opened.generationKey);
251
316
  } catch {
252
317
  return failure(