tmux-ide 2.9.21 → 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 (131) hide show
  1. package/bin/cli.js +6235 -8473
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +2 -0
  4. package/packages/contracts/src/pane-reader.ts +121 -0
  5. package/packages/contracts/src/pane-stream.ts +18 -0
  6. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  7. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  8. package/packages/daemon/dist/command-center/automation.js +1 -1
  9. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  10. package/packages/daemon/dist/command-center/discovery.js +28 -2
  11. package/packages/daemon/dist/command-center/server.js +8 -2
  12. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  13. package/packages/daemon/dist/command-center/tmux-servers.js +7 -1
  14. package/packages/daemon/dist/doctor.js +147 -43
  15. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  16. package/packages/daemon/dist/lib/cli-command.js +13 -0
  17. package/packages/daemon/dist/lib/daemon-embed.js +126 -55
  18. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  19. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  20. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  21. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  22. package/packages/daemon/dist/lib/log.js +18 -1
  23. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  24. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  25. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  26. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  27. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  28. package/packages/daemon/dist/lib/tmux-pane-reader.js +107 -0
  29. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  30. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  31. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  32. package/packages/daemon/dist/lib/tmux-server-owner.js +38 -37
  33. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  34. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  35. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  36. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  37. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  38. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  39. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  40. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  41. package/packages/daemon/dist/open-browser.js +26 -12
  42. package/packages/daemon/dist/open-reader.js +84 -0
  43. package/packages/daemon/dist/plugins/cli.js +1 -2
  44. package/packages/daemon/dist/plugins/daemon-plugins.js +2 -10
  45. package/packages/daemon/dist/restore.js +57 -40
  46. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  47. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  48. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  49. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  50. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  51. package/packages/daemon/dist/terminal/mirror/session-channel.js +13 -12
  52. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +123 -25
  53. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  54. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  55. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +30 -2
  56. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  57. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  58. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  59. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  60. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  61. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  62. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  63. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  64. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  65. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  66. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +35 -5
  67. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  68. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  69. package/packages/daemon/src/command-center/automation.ts +1 -1
  70. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  71. package/packages/daemon/src/command-center/discovery.ts +35 -2
  72. package/packages/daemon/src/command-center/server.ts +22 -8
  73. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  74. package/packages/daemon/src/command-center/tmux-servers.ts +7 -1
  75. package/packages/daemon/src/doctor.ts +164 -45
  76. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  77. package/packages/daemon/src/lib/cli-command.ts +16 -0
  78. package/packages/daemon/src/lib/daemon-embed.ts +176 -64
  79. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  80. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  81. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  82. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  83. package/packages/daemon/src/lib/log.ts +18 -1
  84. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  85. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  86. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  87. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  88. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  89. package/packages/daemon/src/lib/tmux-pane-reader.ts +145 -0
  90. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  91. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  92. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +41 -35
  94. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  95. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  96. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  97. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  98. package/packages/daemon/src/open-browser.ts +59 -18
  99. package/packages/daemon/src/open-reader.ts +148 -0
  100. package/packages/daemon/src/plugins/cli.ts +1 -2
  101. package/packages/daemon/src/plugins/daemon-plugins.ts +2 -12
  102. package/packages/daemon/src/restore.ts +80 -44
  103. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  104. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  105. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  106. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  107. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  108. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  109. package/packages/daemon/src/terminal/mirror/session-channel.ts +15 -14
  110. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +140 -23
  111. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  112. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  113. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +41 -1
  114. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  115. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  116. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  117. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  118. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  119. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  120. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  121. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  122. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  123. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  124. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  125. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +58 -6
  126. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  127. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  128. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  129. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  130. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
  131. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -0,0 +1,353 @@
1
+ /**
2
+ * PURE — the plan for moving a tmux server onto tmux-ide's own tmux (#766):
3
+ * snapshot coverage, the agent and program lists, the text shown before the
4
+ * question, and the confirmation rule. The io lives in ./run.ts.
5
+ */
6
+ import { paneResumeCommand } from "../restore.ts";
7
+ import type { FleetSnapshot } from "../tui/chrome/snapshot.ts";
8
+ import { parseAuthority } from "../tui/detect/classify.ts";
9
+ import { isListableSession } from "../tui/team/sessions.ts";
10
+ import { UPDATER_SESSION } from "../lib/chrome-front-door.ts";
11
+ import type { ServerFeatures } from "../lib/tmux-server-features.ts";
12
+
13
+ /** The server to move, pinned by socket path and by pid plus start time. */
14
+ export interface ServerIdentity {
15
+ /** The machine's hostname, as the user knows it. */
16
+ host: string;
17
+ socketPath: string;
18
+ pid: number;
19
+ /** `#{start_time}`; with pid it tells this server from a later one on the same socket. */
20
+ startTime: number;
21
+ /** `#{version}` of the running server. */
22
+ version: string;
23
+ /** The binary the server runs, or "" when it can't be read. */
24
+ executable: string;
25
+ features: ServerFeatures;
26
+ }
27
+
28
+ /** `list-panes -a` lines: `session \t window_index \t pane_index`. */
29
+ export const COVERAGE_PANE_FORMAT = "#{session_name}\t#{window_index}\t#{pane_index}";
30
+
31
+ export interface CoverageResult {
32
+ ok: boolean;
33
+ problems: string[];
34
+ /** Sessions that end and are not restored (`_…`, `zz-…`), minus the updater's own. */
35
+ notRestored: string[];
36
+ }
37
+
38
+ function parseListing(listing: readonly string[]) {
39
+ const sessions = new Map<string, Map<number, number[]>>();
40
+ const notRestored = new Set<string>();
41
+ for (const line of listing) {
42
+ if (!line) continue;
43
+ const [session = "", window = "", pane = ""] = line.split("\t");
44
+ if (!session) continue;
45
+ if (!isListableSession(session)) {
46
+ if (session !== UPDATER_SESSION) notRestored.add(session);
47
+ continue;
48
+ }
49
+ let windows = sessions.get(session);
50
+ if (!windows) sessions.set(session, (windows = new Map()));
51
+ const panes = windows.get(Number(window)) ?? [];
52
+ panes.push(Number(pane));
53
+ windows.set(Number(window), panes);
54
+ }
55
+ return { sessions, notRestored: [...notRestored].sort() };
56
+ }
57
+
58
+ /**
59
+ * Does the snapshot hold every listable session, window and pane the live
60
+ * server lists, with a layout per window and a folder per pane? Nothing may be
61
+ * killed unless this is ok against a listing taken after the file was read back.
62
+ */
63
+ export function coverage(snapshot: FleetSnapshot, listing: readonly string[]): CoverageResult {
64
+ const live = parseListing(listing);
65
+ const problems: string[] = [];
66
+ if (live.sessions.size === 0 && live.notRestored.length === 0)
67
+ problems.push("the server lists no sessions");
68
+ const saved = new Map(snapshot.sessions.map((session) => [session.name, session]));
69
+ for (const [name, windows] of live.sessions) {
70
+ const session = saved.get(name);
71
+ if (!session) {
72
+ problems.push(`session ${name} is not in the snapshot`);
73
+ continue;
74
+ }
75
+ const savedWindows = new Map(session.windows.map((window) => [window.index, window]));
76
+ for (const [index, panes] of windows) {
77
+ const window = savedWindows.get(index);
78
+ if (!window) {
79
+ problems.push(`window ${name}:${index} is not in the snapshot`);
80
+ continue;
81
+ }
82
+ if (window.panes.length !== panes.length)
83
+ problems.push(
84
+ `window ${name}:${index} has ${panes.length} panes, the snapshot has ${window.panes.length}`,
85
+ );
86
+ }
87
+ for (const window of session.windows)
88
+ if (!windows.has(window.index))
89
+ problems.push(`window ${name}:${window.index} closed after the snapshot`);
90
+ }
91
+ for (const session of snapshot.sessions) {
92
+ if (!live.sessions.has(session.name)) {
93
+ problems.push(`session ${session.name} ended after the snapshot`);
94
+ continue;
95
+ }
96
+ for (const window of session.windows) {
97
+ if (!window.layout)
98
+ problems.push(`window ${session.name}:${window.index} has no layout in the snapshot`);
99
+ for (const pane of window.panes)
100
+ if (!pane.cwd)
101
+ problems.push(
102
+ `pane ${session.name}:${window.index}.${pane.index} has no folder in the snapshot`,
103
+ );
104
+ }
105
+ }
106
+ return { ok: problems.length === 0, problems, notRestored: live.notRestored };
107
+ }
108
+
109
+ /**
110
+ * After restore: the same sessions, with the same pane count per window in
111
+ * order. Window indexes may differ (base-index), so they are not compared.
112
+ */
113
+ export function sameShape(snapshot: FleetSnapshot, listing: readonly string[]): string[] {
114
+ const live = parseListing(listing).sessions;
115
+ const problems: string[] = [];
116
+ for (const session of snapshot.sessions) {
117
+ const windows = live.get(session.name);
118
+ if (!windows) {
119
+ problems.push(`session ${session.name} did not come back`);
120
+ continue;
121
+ }
122
+ const got = [...windows.entries()].sort(([a], [b]) => a - b).map(([, panes]) => panes.length);
123
+ const want = session.windows.map((window) => window.panes.length);
124
+ if (got.join("+") !== want.join("+"))
125
+ problems.push(
126
+ `session ${session.name} came back with ${got.join("+")} panes, the snapshot has ${want.join("+")}`,
127
+ );
128
+ }
129
+ return problems;
130
+ }
131
+
132
+ export type AgentTurnState = "working" | "blocked" | "idle" | "done" | "unknown";
133
+
134
+ /**
135
+ * An `idle` or `done` report older than this reads as `unknown`: the agent may
136
+ * have started a turn its hooks never reported. (`working` and `blocked` go
137
+ * stale after 10 minutes, in classify.ts.)
138
+ */
139
+ export const IDLE_STALE_SECONDS = 60 * 60;
140
+
141
+ /** PURE: the agent's turn state from its `@agent_state` report, conservatively. */
142
+ export function agentTurnState(raw: string | null, nowSec: number): AgentTurnState {
143
+ const state = parseAuthority(raw ?? undefined, nowSec);
144
+ if (!state) return "unknown";
145
+ if (state === "idle" || state === "done") {
146
+ const epoch = Number(raw!.slice(raw!.lastIndexOf(":") + 1));
147
+ if (nowSec - epoch > IDLE_STALE_SECONDS) return "unknown";
148
+ }
149
+ return state;
150
+ }
151
+
152
+ /** A pane of a session that ends and is not restored (`_…`, `zz-…`). */
153
+ export interface EndingPane {
154
+ target: string;
155
+ cwd: string;
156
+ agent: string | null;
157
+ command: string | null;
158
+ }
159
+
160
+ export interface PlannedAgent {
161
+ target: string;
162
+ agent: string;
163
+ cwd: string;
164
+ state: AgentTurnState;
165
+ /** Restore will run the agent's resume command for this pane. */
166
+ resumes: boolean;
167
+ }
168
+
169
+ export interface UpgradePlan {
170
+ server: ServerIdentity;
171
+ bundled: { executable: string; version: string };
172
+ snapshotPath: string;
173
+ savedAt: string;
174
+ sessions: { name: string; windows: number; panes: number }[];
175
+ paneCount: number;
176
+ agents: PlannedAgent[];
177
+ /** Agents working, blocked on a question, or with no fresh state report. */
178
+ midTurn: number;
179
+ /**
180
+ * Programs that are neither a shell nor a known agent. They stop, and
181
+ * tmux-ide can't tell whether one is an agent, so `--yes` alone refuses.
182
+ */
183
+ programs: { target: string; command: string }[];
184
+ /** Agents and programs in sessions that end and are not restored. */
185
+ ending: EndingPane[];
186
+ notRestored: string[];
187
+ resumeAgents: boolean;
188
+ }
189
+
190
+ export function buildUpgradePlan(input: {
191
+ server: ServerIdentity;
192
+ bundled: { executable: string; version: string };
193
+ snapshot: FleetSnapshot;
194
+ snapshotPath: string;
195
+ notRestored: string[];
196
+ /** Panes of not-restored sessions that run an agent or a program. */
197
+ ending?: EndingPane[];
198
+ /** The pane this command runs in, if any: the caller's own consent covers it. */
199
+ selfPane?: string | null;
200
+ resumeAgents: boolean;
201
+ nowSec: number;
202
+ }): UpgradePlan {
203
+ const agents: PlannedAgent[] = [];
204
+ const programs: UpgradePlan["programs"] = [];
205
+ let paneCount = 0;
206
+ const sessions = input.snapshot.sessions.map((session) => {
207
+ let panes = 0;
208
+ for (const window of session.windows)
209
+ for (const pane of window.panes) {
210
+ panes++;
211
+ const target = `${session.name}:${window.index}.${pane.index}`;
212
+ if (pane.agent) {
213
+ agents.push({
214
+ target,
215
+ agent: pane.agent,
216
+ cwd: pane.cwd,
217
+ state: agentTurnState(pane.agentState, input.nowSec),
218
+ resumes: paneResumeCommand(pane, { resumeAgents: input.resumeAgents }) !== null,
219
+ });
220
+ } else if (pane.command && target !== input.selfPane)
221
+ programs.push({ target, command: pane.command });
222
+ }
223
+ paneCount += panes;
224
+ return { name: session.name, windows: session.windows.length, panes };
225
+ });
226
+ return {
227
+ server: input.server,
228
+ bundled: input.bundled,
229
+ snapshotPath: input.snapshotPath,
230
+ savedAt: input.snapshot.savedAt,
231
+ sessions,
232
+ paneCount,
233
+ agents,
234
+ midTurn: agents.filter(
235
+ (agent) => agent.target !== input.selfPane && !["idle", "done"].includes(agent.state),
236
+ ).length,
237
+ programs,
238
+ ending: (input.ending ?? []).filter((pane) => pane.agent || pane.command),
239
+ notRestored: input.notRestored,
240
+ resumeAgents: input.resumeAgents,
241
+ };
242
+ }
243
+
244
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;
245
+
246
+ const FEATURE_NAMES: Record<ServerFeatures, string> = {
247
+ full: "tmux-ide's tmux",
248
+ stock: "stock tmux",
249
+ older: "an older tmux-ide tmux",
250
+ partial: "a tmux with only some tmux-ide commands",
251
+ unknown: "tmux",
252
+ };
253
+
254
+ /** The text shown before the question. Its first line names the machine and the server. */
255
+ export function renderPlan(plan: UpgradePlan): string {
256
+ const { server } = plan;
257
+ const lines = [
258
+ `This ends ${plural(plan.sessions.length, "session")} and ${plural(plan.agents.length, "agent")} on ${server.host} (${server.socketPath}).`,
259
+ `The server runs ${FEATURE_NAMES[server.features]} ${server.version}${server.executable ? ` (${server.executable})` : ""}.`,
260
+ `tmux-ide's own tmux (${plan.bundled.version}) has every feature. Moving restarts the server.`,
261
+ "",
262
+ "These sessions close and come back:",
263
+ ...plan.sessions.map(
264
+ (session) =>
265
+ ` ${session.name} ${plural(session.windows, "window")}, ${plural(session.panes, "pane")}`,
266
+ ),
267
+ "",
268
+ "Comes back: windows, split layouts, each pane's folder, pane titles.",
269
+ "Does not come back: running programs, scrollback, shell variables,",
270
+ "aliases you set by hand, background jobs. Save open files first.",
271
+ ];
272
+ if (plan.programs.length) {
273
+ lines.push("", "These programs stop (tmux-ide can't tell whether one is an agent):");
274
+ for (const program of plan.programs) lines.push(` ${program.target} ${program.command}`);
275
+ }
276
+ if (plan.agents.length) {
277
+ lines.push("", `Agents (${plan.agents.length}):`);
278
+ for (const agent of plan.agents) {
279
+ const outcome = agent.resumes
280
+ ? "resumes its conversation"
281
+ : plan.resumeAgents
282
+ ? "ends; no saved conversation id"
283
+ : "ends (--no-resume-agents)";
284
+ lines.push(` ${agent.target} ${agent.agent} ${agent.state} ${agent.cwd} ${outcome}`);
285
+ }
286
+ if (plan.midTurn)
287
+ lines.push(
288
+ plan.midTurn === 1
289
+ ? "1 agent is mid-turn. Its current turn will be lost."
290
+ : `${plan.midTurn} agents may be mid-turn. Their current turns will be lost.`,
291
+ );
292
+ }
293
+ if (plan.notRestored.length)
294
+ lines.push("", `Also ends, not restored: ${plan.notRestored.join(", ")}`);
295
+ for (const pane of plan.ending)
296
+ lines.push(
297
+ ` ${pane.target} ${pane.agent ?? pane.command} ${pane.cwd} ends and does not come back`,
298
+ );
299
+ lines.push("", `Snapshot saved: ${plan.snapshotPath}`);
300
+ return lines.join("\n");
301
+ }
302
+
303
+ export type Confirmation =
304
+ | { kind: "ask" }
305
+ | { kind: "preview" }
306
+ | { kind: "proceed" }
307
+ | { kind: "refuse"; reason: string };
308
+
309
+ /** What `--yes` alone may not end. */
310
+ export interface AtRisk {
311
+ /** Agents mid-turn, or with no fresh state report. */
312
+ midTurn: number;
313
+ /** Programs that may be agents tmux-ide can't recognise. */
314
+ programs: number;
315
+ /** Agents or programs in sessions that are not restored. */
316
+ ending: number;
317
+ }
318
+
319
+ export function atRisk(plan: UpgradePlan): AtRisk {
320
+ return { midTurn: plan.midTurn, programs: plan.programs.length, ending: plan.ending.length };
321
+ }
322
+
323
+ /**
324
+ * The default answer is always No. `--yes` alone never ends an agent that may
325
+ * be mid-turn, a program that may be an agent, or anything that won't come back.
326
+ */
327
+ export function confirmation(input: {
328
+ yes: boolean;
329
+ endRunningAgents: boolean;
330
+ json: boolean;
331
+ dryRun: boolean;
332
+ risk: AtRisk;
333
+ }): Confirmation {
334
+ if (input.dryRun || (input.json && !input.yes)) return { kind: "preview" };
335
+ if (!input.yes) return { kind: "ask" };
336
+ const { midTurn, programs, ending } = input.risk;
337
+ if ((midTurn > 0 || programs > 0 || ending > 0) && !input.endRunningAgents) {
338
+ const parts = [
339
+ ...(midTurn ? [`${plural(midTurn, "agent")} may be mid-turn`] : []),
340
+ ...(programs
341
+ ? [`${plural(programs, "program")} may be ${programs === 1 ? "an agent" : "agents"}`]
342
+ : []),
343
+ ...(ending
344
+ ? [`${plural(ending, "pane")} in sessions that are not restored run something`]
345
+ : []),
346
+ ];
347
+ return {
348
+ kind: "refuse",
349
+ reason: `${parts.join("; ")}. Pass --yes --end-running-agents to end them, or wait until they are idle. Nothing was stopped.`,
350
+ };
351
+ }
352
+ return { kind: "proceed" };
353
+ }
@@ -0,0 +1,325 @@
1
+ /**
2
+ * The steps of `tmux-ide servers upgrade` (#766), over an injectable io so the
3
+ * order and every refusal are unit-tested. Nothing is killed until a snapshot
4
+ * written to its own file, read back and parsed, covers a fresh listing of the
5
+ * server, and the user (or `--yes`, with `--end-running-agents` when an agent
6
+ * is mid-turn) agreed. Real io: ./io.ts.
7
+ *
8
+ * The kill and the restore always run in a detached worker, so the step that
9
+ * ends the server never depends on the invoking terminal, ssh connection or
10
+ * shell staying alive. The foreground waits for the worker's result file.
11
+ */
12
+ import { IdeError } from "../lib/errors.ts";
13
+ import type { FleetSnapshot } from "../tui/chrome/snapshot.ts";
14
+ import type { ServerFeatures } from "../lib/tmux-server-features.ts";
15
+ import {
16
+ atRisk,
17
+ buildUpgradePlan,
18
+ confirmation,
19
+ coverage,
20
+ renderPlan,
21
+ sameShape,
22
+ type EndingPane,
23
+ type ServerIdentity,
24
+ type UpgradePlan,
25
+ } from "./plan.ts";
26
+
27
+ export type ServerFacts = Omit<ServerIdentity, "host" | "features">;
28
+
29
+ /** What the detached worker needs to finish an upgrade the user agreed to. */
30
+ export interface WorkerState {
31
+ server: ServerIdentity;
32
+ client: string;
33
+ snapshotPath: string;
34
+ resumeAgents: boolean;
35
+ }
36
+
37
+ export interface UpgradeIo {
38
+ host(): string;
39
+ /** The validated bundled tmux, or null. Throws when the bundle is damaged. */
40
+ bundled(): { executable: string; version: string } | null;
41
+ configuredBinary(): string | undefined;
42
+ /** The target server as `client` reaches it; null when none runs. */
43
+ identify(client: string): ServerFacts | null;
44
+ features(client: string, socket: string): ServerFeatures;
45
+ /** Start a throwaway server from `client` on a private socket and probe it. */
46
+ scratchFeatures(client: string): ServerFeatures;
47
+ listPanes(client: string, socket: string): string[];
48
+ /** Panes of sessions the snapshot skips (`_…`, `zz-…`), with what they run. */
49
+ endingPanes(client: string, socket: string): EndingPane[];
50
+ collect(client: string, socket: string): FleetSnapshot;
51
+ /** Write the snapshot to a new file of its own (fsync'd); returns its path. */
52
+ saveSnapshot(snapshot: FleetSnapshot): string;
53
+ loadSnapshot(path: string): FleetSnapshot | null;
54
+ /** The `session:window.pane` this process runs in on that server, by process ancestry. */
55
+ ownPane(client: string, socket: string): string | null;
56
+ /** Whether this process runs in a pane of that server ($TMUX or process ancestry). */
57
+ insideTarget(client: string, socket: string): boolean;
58
+ /** Ask; the answer is No unless the user types y or yes at a terminal. */
59
+ confirm(text: string): Promise<boolean>;
60
+ /** Start a detached worker that runs {@link finishUpgrade} and writes its result. */
61
+ startWorker(state: WorkerState): WorkerHandle;
62
+ /** Wait for the worker's result; null when it exited without one or timed out. */
63
+ waitForWorker(handle: WorkerHandle): Promise<UpgradeResult | null>;
64
+ /** Kill exactly this server (guarded by pid and start time). */
65
+ kill(client: string, server: ServerIdentity): void;
66
+ /** Wait briefly; true once no server answers on the socket. */
67
+ serverGone(client: string, socket: string): boolean;
68
+ restore(input: {
69
+ client: string;
70
+ socket: string;
71
+ snapshotPath: string;
72
+ resumeAgents: boolean;
73
+ }): Promise<{ restored: string[]; failed: string[] }>;
74
+ print(text: string): void;
75
+ nowSec(): number;
76
+ }
77
+
78
+ export interface WorkerHandle {
79
+ log: string;
80
+ resultPath: string;
81
+ pid: number;
82
+ }
83
+
84
+ export interface UpgradeOptions {
85
+ yes: boolean;
86
+ endRunningAgents: boolean;
87
+ json: boolean;
88
+ dryRun: boolean;
89
+ resumeAgents: boolean;
90
+ }
91
+
92
+ export type UpgradeStatus =
93
+ | "already-full"
94
+ | "preview"
95
+ | "declined"
96
+ | "refused"
97
+ | "handed-off"
98
+ | "upgraded"
99
+ | "failed";
100
+
101
+ export interface UpgradeResult {
102
+ status: UpgradeStatus;
103
+ message: string;
104
+ plan?: UpgradePlan;
105
+ restored?: string[];
106
+ failed?: string[];
107
+ }
108
+
109
+ /** The line that rebuilds the sessions by hand from a pinned snapshot. */
110
+ export const retryCommand = (snapshotPath: string, resumeAgents: boolean) =>
111
+ `tmux-ide restore --from ${snapshotPath}${resumeAgents ? " --resume-agents" : ""}`;
112
+
113
+ const nothingChanged = (message: string, code: string) =>
114
+ new IdeError(`${message} Nothing was stopped.`, { code, exitCode: 1 });
115
+
116
+ /** Snapshot, write, read back, and prove coverage against a fresh listing. */
117
+ function pinnedSnapshot(io: UpgradeIo, client: string, socket: string) {
118
+ const snapshot = io.collect(client, socket);
119
+ let path: string;
120
+ try {
121
+ path = io.saveSnapshot(snapshot);
122
+ } catch (error) {
123
+ throw nothingChanged(
124
+ `The snapshot could not be written: ${(error as Error).message}.`,
125
+ "SNAPSHOT_WRITE",
126
+ );
127
+ }
128
+ const saved = io.loadSnapshot(path);
129
+ if (!saved)
130
+ throw nothingChanged(`The snapshot at ${path} could not be read back.`, "SNAPSHOT_READ");
131
+ const covered = coverage(saved, io.listPanes(client, socket));
132
+ if (!covered.ok)
133
+ throw nothingChanged(
134
+ `The snapshot does not cover the server: ${covered.problems.join("; ")}.`,
135
+ "SNAPSHOT_COVERAGE",
136
+ );
137
+ return { snapshot: saved, path, notRestored: covered.notRestored };
138
+ }
139
+
140
+ export async function upgradeServer(
141
+ io: UpgradeIo,
142
+ options: UpgradeOptions,
143
+ ): Promise<UpgradeResult> {
144
+ const configured = io.configuredBinary();
145
+ const bundled = io.bundled();
146
+ if (!bundled)
147
+ throw nothingChanged(
148
+ "No bundled tmux found for this machine. Reinstall tmux-ide.",
149
+ "NO_BUNDLED_TMUX",
150
+ );
151
+ if (configured && configured !== bundled.executable)
152
+ throw nothingChanged(
153
+ `TMUX_IDE_TMUX_BIN names ${configured}, not tmux-ide's own tmux. Unset it first.`,
154
+ "TMUX_BIN_OVERRIDE",
155
+ );
156
+ const client = bundled.executable;
157
+ const facts = io.identify(client);
158
+ if (!facts)
159
+ throw new IdeError("No tmux server is running here.", { code: "NO_SERVER", exitCode: 1 });
160
+ const server: ServerIdentity = {
161
+ ...facts,
162
+ host: io.host(),
163
+ features: io.features(client, facts.socketPath),
164
+ };
165
+ if (server.features === "full")
166
+ return {
167
+ status: "already-full",
168
+ message: `${server.host} (${server.socketPath}) already runs tmux-ide's own tmux.`,
169
+ };
170
+ const scratch = io.scratchFeatures(client);
171
+ if (scratch !== "full")
172
+ throw nothingChanged(
173
+ `A scratch server from the bundled tmux reports "${scratch}", not full features.`,
174
+ "BUNDLE_NOT_FULL",
175
+ );
176
+
177
+ for (let attempt = 0; ; attempt++) {
178
+ const pinned = pinnedSnapshot(io, client, server.socketPath);
179
+ const plan = buildUpgradePlan({
180
+ server,
181
+ bundled,
182
+ snapshot: pinned.snapshot,
183
+ snapshotPath: pinned.path,
184
+ notRestored: pinned.notRestored,
185
+ ending: io.endingPanes(client, server.socketPath),
186
+ selfPane: io.ownPane(client, server.socketPath),
187
+ resumeAgents: options.resumeAgents,
188
+ nowSec: io.nowSec(),
189
+ });
190
+ const decision = confirmation({ ...options, risk: atRisk(plan) });
191
+ if (decision.kind === "preview") return { status: "preview", message: renderPlan(plan), plan };
192
+ if (decision.kind === "refuse") {
193
+ if (!options.json) io.print(renderPlan(plan));
194
+ return { status: "refused", message: decision.reason, plan };
195
+ }
196
+ if (decision.kind === "ask") {
197
+ io.print(renderPlan(plan));
198
+ if (!(await io.confirm("Restart the server and restore? [y/N] ")))
199
+ return { status: "declined", message: "Nothing was stopped.", plan };
200
+ }
201
+ // The server may have changed while the question was open.
202
+ if (!coverage(pinned.snapshot, io.listPanes(client, server.socketPath)).ok) {
203
+ if (attempt >= 2)
204
+ throw nothingChanged(
205
+ "The server keeps changing; try again in a moment.",
206
+ "SERVER_CHANGING",
207
+ );
208
+ io.print("The server changed since the snapshot. Taking a new one.");
209
+ continue;
210
+ }
211
+ const work: WorkerState = {
212
+ server,
213
+ client,
214
+ snapshotPath: pinned.path,
215
+ resumeAgents: options.resumeAgents,
216
+ };
217
+ // Before anything is ended, in every mode: where the snapshot is and how to use it.
218
+ io.print(
219
+ `Snapshot saved: ${pinned.path}\nIf the sessions do not come back, run: ${retryCommand(pinned.path, options.resumeAgents)}`,
220
+ );
221
+ const inside = io.insideTarget(client, server.socketPath);
222
+ const worker = io.startWorker(work);
223
+ io.print(`The restart runs in the background. Log: ${worker.log}`);
224
+ if (inside)
225
+ return {
226
+ status: "handed-off",
227
+ message: `This terminal runs inside that server and closes in a moment. Reopen tmux-ide or run \`tmux attach\` in a few seconds. Log: ${worker.log}`,
228
+ plan,
229
+ };
230
+ const result = await io.waitForWorker(worker);
231
+ if (!result)
232
+ return {
233
+ status: "failed",
234
+ message: `The background restart did not report back. Read ${worker.log}. If the sessions are missing, run: ${retryCommand(pinned.path, options.resumeAgents)}`,
235
+ plan,
236
+ };
237
+ return { ...result, plan };
238
+ }
239
+ }
240
+
241
+ /** The detached worker's entry: confirm it is still the same server, then finish. */
242
+ export async function finishUpgrade(io: UpgradeIo, work: WorkerState): Promise<UpgradeResult> {
243
+ const facts = io.identify(work.client);
244
+ if (!facts || facts.pid !== work.server.pid || facts.startTime !== work.server.startTime)
245
+ return {
246
+ status: "failed",
247
+ message: "The server changed since the prompt. Nothing was stopped.",
248
+ };
249
+ const snapshot = io.loadSnapshot(work.snapshotPath);
250
+ if (!snapshot || !coverage(snapshot, io.listPanes(work.client, work.server.socketPath)).ok)
251
+ return {
252
+ status: "failed",
253
+ message: "The snapshot no longer covers the server. Nothing was stopped.",
254
+ };
255
+ return stopAndRestore(io, work, snapshot);
256
+ }
257
+
258
+ async function stopAndRestore(
259
+ io: UpgradeIo,
260
+ work: WorkerState,
261
+ snapshot: FleetSnapshot,
262
+ ): Promise<UpgradeResult> {
263
+ const { server, client, snapshotPath, resumeAgents } = work;
264
+ const retry = `Snapshot: ${snapshotPath}. Retry with: ${retryCommand(snapshotPath, resumeAgents)}`;
265
+ try {
266
+ io.kill(client, server);
267
+ } catch (error) {
268
+ return {
269
+ status: "failed",
270
+ message: `The kill failed (${(error as Error).message}); the server is still running. ${retry}`,
271
+ };
272
+ }
273
+ if (!io.serverGone(client, server.socketPath)) {
274
+ // Something answers on the socket. The same server: it did not end. Another
275
+ // server (someone started one in the gap): rebuild into it; live names are skipped.
276
+ const now = io.identify(client);
277
+ if (!now || (now.pid === server.pid && now.startTime === server.startTime))
278
+ return {
279
+ status: "failed",
280
+ message: `The server is still running after the kill. ${retry}`,
281
+ };
282
+ io.print(`Another server (pid ${now.pid}) now answers on the socket; restoring into it.`);
283
+ }
284
+ const input = { socket: server.socketPath, snapshotPath, resumeAgents };
285
+ let outcome: { restored: string[]; failed: string[] };
286
+ try {
287
+ outcome = await io.restore({ ...input, client });
288
+ } catch (error) {
289
+ if (!server.executable)
290
+ return {
291
+ status: "failed",
292
+ message: `tmux-ide's tmux could not start a server (${(error as Error).message}). ${retry}`,
293
+ };
294
+ try {
295
+ outcome = await io.restore({ ...input, client: server.executable });
296
+ } catch (fallback) {
297
+ return {
298
+ status: "failed",
299
+ message: `Neither tmux could start a server (${(fallback as Error).message}). ${retry}`,
300
+ };
301
+ }
302
+ return {
303
+ status: "failed",
304
+ message: `tmux-ide's tmux could not start a server (${(error as Error).message}); your sessions were restored on ${server.executable} instead. ${retry}`,
305
+ ...outcome,
306
+ };
307
+ }
308
+ const features = io.features(client, server.socketPath);
309
+ const shape = sameShape(snapshot, io.listPanes(client, server.socketPath));
310
+ const problems = [
311
+ ...outcome.failed.map((name) => `session ${name} failed to rebuild`),
312
+ ...shape.filter((line) => !outcome.failed.some((name) => line.includes(` ${name} `))),
313
+ ...(features === "full" ? [] : [`the new server reports "${features}", not full features`]),
314
+ ];
315
+ if (problems.length)
316
+ return { status: "failed", message: `${problems.join("; ")}. ${retry}`, ...outcome };
317
+ io.print(
318
+ `Restored ${outcome.restored.length} sessions. tmux features: bundled tmux: full features.`,
319
+ );
320
+ return {
321
+ status: "upgraded",
322
+ message: `${server.host} (${server.socketPath}) now runs tmux-ide's own tmux.`,
323
+ ...outcome,
324
+ };
325
+ }
@@ -151,7 +151,7 @@ function isBareShell(cmd: string): boolean {
151
151
  * BOTH the agent and the restore command; a bare shell records neither; any
152
152
  * other foreground process records its `pane_current_command` as the command.
153
153
  */
154
- function resolvePaneCommand(
154
+ export function resolvePaneCommand(
155
155
  cmd: string,
156
156
  pid: number,
157
157
  hint: string,
@@ -357,9 +357,8 @@ export function writeSnapshot(snapshot: FleetSnapshot): void {
357
357
  }
358
358
  }
359
359
 
360
- /** Read + validate the snapshot on disk. Returns null when missing or malformed. */
361
- export function readSnapshot(): FleetSnapshot | null {
362
- const path = snapshotPath();
360
+ /** Read + validate a snapshot file (default: the updater's). Returns null when missing or malformed. */
361
+ export function readSnapshot(path: string = snapshotPath()): FleetSnapshot | null {
363
362
  try {
364
363
  if (!existsSync(path)) return null;
365
364
  const raw = readFileSync(path, "utf-8");