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.
- package/bin/cli.js +6235 -8473
- package/package.json +3 -3
- package/packages/contracts/src/index.ts +2 -0
- package/packages/contracts/src/pane-reader.ts +121 -0
- package/packages/contracts/src/pane-stream.ts +18 -0
- package/packages/contracts/src/visual-theme-presets.ts +58 -2
- package/packages/contracts/src/websocket-heartbeat.ts +41 -0
- package/packages/daemon/dist/command-center/automation.js +1 -1
- package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
- package/packages/daemon/dist/command-center/discovery.js +28 -2
- package/packages/daemon/dist/command-center/server.js +8 -2
- package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
- package/packages/daemon/dist/command-center/tmux-servers.js +7 -1
- package/packages/daemon/dist/doctor.js +147 -43
- package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
- package/packages/daemon/dist/lib/cli-command.js +13 -0
- package/packages/daemon/dist/lib/daemon-embed.js +126 -55
- package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
- package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
- package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
- package/packages/daemon/dist/lib/headless-daemon.js +177 -10
- package/packages/daemon/dist/lib/log.js +18 -1
- package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
- package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
- package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
- package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
- package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
- package/packages/daemon/dist/lib/tmux-pane-reader.js +107 -0
- package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
- package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
- package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
- package/packages/daemon/dist/lib/tmux-server-owner.js +38 -37
- package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
- package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
- package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
- package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
- package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
- package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
- package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
- package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
- package/packages/daemon/dist/open-browser.js +26 -12
- package/packages/daemon/dist/open-reader.js +84 -0
- package/packages/daemon/dist/plugins/cli.js +1 -2
- package/packages/daemon/dist/plugins/daemon-plugins.js +2 -10
- package/packages/daemon/dist/restore.js +57 -40
- package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
- package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
- package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
- package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
- package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
- package/packages/daemon/dist/terminal/mirror/session-channel.js +13 -12
- package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +123 -25
- package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
- package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
- package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +30 -2
- package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
- package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
- package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
- package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
- package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
- package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
- package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
- package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
- package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
- package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
- package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +35 -5
- package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
- package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
- package/packages/daemon/src/command-center/automation.ts +1 -1
- package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
- package/packages/daemon/src/command-center/discovery.ts +35 -2
- package/packages/daemon/src/command-center/server.ts +22 -8
- package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
- package/packages/daemon/src/command-center/tmux-servers.ts +7 -1
- package/packages/daemon/src/doctor.ts +164 -45
- package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
- package/packages/daemon/src/lib/cli-command.ts +16 -0
- package/packages/daemon/src/lib/daemon-embed.ts +176 -64
- package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
- package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
- package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
- package/packages/daemon/src/lib/headless-daemon.ts +205 -12
- package/packages/daemon/src/lib/log.ts +18 -1
- package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
- package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
- package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
- package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
- package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
- package/packages/daemon/src/lib/tmux-pane-reader.ts +145 -0
- package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
- package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
- package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
- package/packages/daemon/src/lib/tmux-server-owner.ts +41 -35
- package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
- package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
- package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
- package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
- package/packages/daemon/src/open-browser.ts +59 -18
- package/packages/daemon/src/open-reader.ts +148 -0
- package/packages/daemon/src/plugins/cli.ts +1 -2
- package/packages/daemon/src/plugins/daemon-plugins.ts +2 -12
- package/packages/daemon/src/restore.ts +80 -44
- package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
- package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
- package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
- package/packages/daemon/src/terminal/mirror/events.ts +2 -0
- package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
- package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
- package/packages/daemon/src/terminal/mirror/session-channel.ts +15 -14
- package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +140 -23
- package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
- package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
- package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +41 -1
- package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
- package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
- package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
- package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
- package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
- package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
- package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
- package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
- package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
- package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
- package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
- package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +58 -6
- package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
- package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
- package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
- package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
- package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
- package/packages/tmux-bridge/src/runner.ts +3 -1
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The real io behind `tmux-ide servers upgrade` (#766). Every tmux call names
|
|
3
|
+
* its server with `-S <socket>`; nothing here reaches a server by default.
|
|
4
|
+
*/
|
|
5
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
6
|
+
import {
|
|
7
|
+
closeSync,
|
|
8
|
+
fsyncSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
mkdtempSync,
|
|
11
|
+
openSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
readlinkSync,
|
|
14
|
+
realpathSync,
|
|
15
|
+
renameSync,
|
|
16
|
+
rmSync,
|
|
17
|
+
writeFileSync,
|
|
18
|
+
writeSync,
|
|
19
|
+
} from "node:fs";
|
|
20
|
+
import { hostname, tmpdir } from "node:os";
|
|
21
|
+
import { dirname, join } from "node:path";
|
|
22
|
+
import { createInterface } from "node:readline/promises";
|
|
23
|
+
import { z } from "zod";
|
|
24
|
+
import { configureTmuxClientResolver } from "@tmux-ide/tmux-bridge";
|
|
25
|
+
import { restoreFleet } from "../restore.ts";
|
|
26
|
+
import {
|
|
27
|
+
collectFleetSnapshot,
|
|
28
|
+
readSnapshot,
|
|
29
|
+
resolvePaneCommand,
|
|
30
|
+
SNAPSHOT_PANE_FORMAT,
|
|
31
|
+
SNAPSHOT_SESSION_FORMAT,
|
|
32
|
+
type FleetSnapshot,
|
|
33
|
+
} from "../tui/chrome/snapshot.ts";
|
|
34
|
+
import { readProcessTable } from "../tui/detect/process-tree.ts";
|
|
35
|
+
import { isListableSession } from "../tui/team/sessions.ts";
|
|
36
|
+
import { resolveBundledTmux, withBundledTmuxResources } from "../lib/bundled-tmux.ts";
|
|
37
|
+
import { IdeError } from "../lib/errors.ts";
|
|
38
|
+
import { resolveRuntimeNamespace } from "../lib/runtime-namespace.ts";
|
|
39
|
+
import {
|
|
40
|
+
nativeCommands,
|
|
41
|
+
type ServerFeatures,
|
|
42
|
+
type TmuxProbe,
|
|
43
|
+
} from "../lib/tmux-server-features.ts";
|
|
44
|
+
import { COVERAGE_PANE_FORMAT } from "./plan.ts";
|
|
45
|
+
import type { ServerFacts, UpgradeIo, UpgradeResult, WorkerState } from "./run.ts";
|
|
46
|
+
|
|
47
|
+
/** A hidden session that starts the new server before restore rebuilds into it. */
|
|
48
|
+
export const UPGRADE_HOLD_SESSION = "_tmux-ide-upgrade";
|
|
49
|
+
|
|
50
|
+
/** Which server the command targets, as the user named it. */
|
|
51
|
+
export interface UpgradeTarget {
|
|
52
|
+
socketPath?: string;
|
|
53
|
+
socketName?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The socket to upgrade: `--socket-path`, `--socket-name`, then the
|
|
58
|
+
* TMUX_IDE_TMUX_SOCKET_PATH / _NAME environment (as doctor reads them), the
|
|
59
|
+
* server this shell runs in, else tmux's default socket.
|
|
60
|
+
*/
|
|
61
|
+
export function targetSocket(
|
|
62
|
+
target: UpgradeTarget,
|
|
63
|
+
environment: NodeJS.ProcessEnv = process.env,
|
|
64
|
+
): string {
|
|
65
|
+
if (target.socketPath && target.socketName)
|
|
66
|
+
throw new IdeError("Pass --socket-path or --socket-name, not both.", {
|
|
67
|
+
code: "USAGE",
|
|
68
|
+
exitCode: 2,
|
|
69
|
+
});
|
|
70
|
+
const directory = join(environment.TMUX_TMPDIR || "/tmp", `tmux-${process.getuid?.() ?? 0}`);
|
|
71
|
+
if (target.socketPath) return target.socketPath;
|
|
72
|
+
if (target.socketName) return join(directory, target.socketName);
|
|
73
|
+
const envPath = environment.TMUX_IDE_TMUX_SOCKET_PATH?.trim();
|
|
74
|
+
if (envPath) return envPath;
|
|
75
|
+
const envName = environment.TMUX_IDE_TMUX_SOCKET_NAME?.trim();
|
|
76
|
+
if (envName) return join(directory, envName);
|
|
77
|
+
const inside = environment.TMUX?.split(",")[0];
|
|
78
|
+
if (inside) return inside;
|
|
79
|
+
return join(directory, "default");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sameFile(a: string, b: string): boolean {
|
|
83
|
+
try {
|
|
84
|
+
return realpathSync(a) === realpathSync(b);
|
|
85
|
+
} catch {
|
|
86
|
+
return a === b;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function tmux(client: string, socket: string, args: readonly string[]): string {
|
|
91
|
+
return execFileSync(client, ["-S", socket, ...args], {
|
|
92
|
+
encoding: "utf8",
|
|
93
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
94
|
+
timeout: 10_000,
|
|
95
|
+
env: withBundledTmuxResources(client, process.env),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function stderrOf(error: unknown): string {
|
|
100
|
+
const failure = error as { stderr?: unknown; message?: string };
|
|
101
|
+
return String(failure.stderr ?? failure.message ?? "");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const NO_SERVER = /no server running|error connecting|failed to connect|connection refused/u;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* PURE: the executable from `lsof -a -p PID -d txt -Fn` output. The first `n`
|
|
108
|
+
* line of the txt descriptors is the program itself; dylibs follow.
|
|
109
|
+
*/
|
|
110
|
+
export function executableFromLsof(output: string): string {
|
|
111
|
+
const line = output.split("\n").find((entry) => entry.startsWith("n/"));
|
|
112
|
+
return line ? line.slice(1) : "";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* PURE: a `/proc/<pid>/exe` link as a path to run. After a package upgrade
|
|
117
|
+
* replaced the file, Linux appends " (deleted)"; the path then names the new
|
|
118
|
+
* binary, which is what a fallback restore should run.
|
|
119
|
+
*/
|
|
120
|
+
export function procExePath(link: string): string {
|
|
121
|
+
return link.replace(/ \(deleted\)$/u, "");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The binary a process runs, or "" when it can't be read. `ps -o comm=` gives
|
|
126
|
+
* only "tmux" for a server started by its PATH name, so macOS asks lsof.
|
|
127
|
+
*/
|
|
128
|
+
export function processExecutable(pid: number): string {
|
|
129
|
+
try {
|
|
130
|
+
if (process.platform === "linux") return procExePath(readlinkSync(`/proc/${pid}/exe`));
|
|
131
|
+
const lsof = executableFromLsof(
|
|
132
|
+
execFileSync("/usr/sbin/lsof", ["-a", "-p", String(pid), "-d", "txt", "-Fn"], {
|
|
133
|
+
encoding: "utf8",
|
|
134
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
135
|
+
timeout: 5000,
|
|
136
|
+
}),
|
|
137
|
+
);
|
|
138
|
+
if (lsof) return lsof;
|
|
139
|
+
} catch {
|
|
140
|
+
// Fall through to ps.
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const comm = execFileSync("/bin/ps", ["-o", "comm=", "-p", String(pid)], {
|
|
144
|
+
encoding: "utf8",
|
|
145
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
146
|
+
timeout: 3000,
|
|
147
|
+
}).trim();
|
|
148
|
+
return comm.startsWith("/") ? comm : "";
|
|
149
|
+
} catch {
|
|
150
|
+
return "";
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** PURE: tmux ends the server only when both its pid and start time still match. */
|
|
155
|
+
export function killGuardArgs(server: { pid: number; startTime: number }): string[] {
|
|
156
|
+
const guard = `#{&&:#{==:#{pid},${server.pid}},#{==:#{start_time},${server.startTime}}}`;
|
|
157
|
+
return ["if-shell", "-F", guard, "kill-server", "display-message -p identity-mismatch"];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** PURE: what the guarded kill's output means. */
|
|
161
|
+
export function killOutcome(
|
|
162
|
+
result: { stdout: string } | { stderr: string },
|
|
163
|
+
): "ended" | "mismatch" | { error: string } {
|
|
164
|
+
if ("stdout" in result) return result.stdout.includes("identity-mismatch") ? "mismatch" : "ended";
|
|
165
|
+
// kill-server ends the server under the client; that is success.
|
|
166
|
+
if (NO_SERVER.test(result.stderr) || /server exited|lost server/u.test(result.stderr))
|
|
167
|
+
return "ended";
|
|
168
|
+
return { error: result.stderr.trim() || "tmux refused" };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The pids of this process and its ancestors, nearest first. */
|
|
172
|
+
function ancestry(): number[] {
|
|
173
|
+
const pids: number[] = [];
|
|
174
|
+
let pid = process.pid;
|
|
175
|
+
for (let step = 0; step < 64 && pid > 1; step++) {
|
|
176
|
+
pids.push(pid);
|
|
177
|
+
try {
|
|
178
|
+
pid = Number(
|
|
179
|
+
execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], {
|
|
180
|
+
encoding: "utf8",
|
|
181
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
182
|
+
timeout: 3000,
|
|
183
|
+
}).trim(),
|
|
184
|
+
);
|
|
185
|
+
} catch {
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
if (!Number.isInteger(pid)) break;
|
|
189
|
+
}
|
|
190
|
+
return pids;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* PURE: the pane (`session:window.pane`) whose process is this process or one
|
|
195
|
+
* of its ancestors, from `#{pane_pid}\t<target>` lines; null when none is.
|
|
196
|
+
*/
|
|
197
|
+
export function ownPaneFrom(ancestors: readonly number[], lines: readonly string[]): string | null {
|
|
198
|
+
const panes = new Map(
|
|
199
|
+
lines.map((line) => {
|
|
200
|
+
const [pid = "", target = ""] = line.split("\t");
|
|
201
|
+
return [Number(pid), target] as const;
|
|
202
|
+
}),
|
|
203
|
+
);
|
|
204
|
+
const mine = ancestors.find((pid) => panes.has(pid));
|
|
205
|
+
return mine === undefined ? null : (panes.get(mine) ?? null);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Ask at a terminal. No terminal, a failed read or anything but y/yes is No. */
|
|
209
|
+
export async function confirmAt(
|
|
210
|
+
question: string,
|
|
211
|
+
terminal: { isTTY: boolean; ask(text: string): Promise<string>; print(text: string): void },
|
|
212
|
+
): Promise<boolean> {
|
|
213
|
+
if (!terminal.isTTY) {
|
|
214
|
+
terminal.print("No terminal to ask in. Pass --yes to go ahead. Nothing was stopped.");
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
return answerIsYes(await terminal.ask(question));
|
|
219
|
+
} catch {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** PURE: the prompt's answer. Anything but y or yes, including nothing, is No. */
|
|
225
|
+
export function answerIsYes(answer: string | null): boolean {
|
|
226
|
+
return answer !== null && /^y(es)?$/iu.test(answer.trim());
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Write a new file, fsync it and its folder. Never overwrites. */
|
|
230
|
+
function writeDurably(path: string, text: string): void {
|
|
231
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
232
|
+
const fd = openSync(path, "wx", 0o600);
|
|
233
|
+
try {
|
|
234
|
+
writeSync(fd, text);
|
|
235
|
+
fsyncSync(fd);
|
|
236
|
+
} finally {
|
|
237
|
+
closeSync(fd);
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
const dir = openSync(dirname(path), "r");
|
|
241
|
+
try {
|
|
242
|
+
fsyncSync(dir);
|
|
243
|
+
} finally {
|
|
244
|
+
closeSync(dir);
|
|
245
|
+
}
|
|
246
|
+
} catch {
|
|
247
|
+
// Some filesystems refuse a directory fsync; the file itself is synced.
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** `~/.tmux-ide/upgrades/<timestamp>`, unique per run. */
|
|
252
|
+
export function newUpgradeDirectory(now: Date = new Date()): string {
|
|
253
|
+
const stamp = now.toISOString().replace(/[:.]/gu, "-");
|
|
254
|
+
return join(resolveRuntimeNamespace().stateHome, "upgrades", stamp);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const ServerIdentitySchemaZ = z
|
|
258
|
+
.object({
|
|
259
|
+
host: z.string(),
|
|
260
|
+
socketPath: z.string().min(1),
|
|
261
|
+
pid: z.number().int().positive(),
|
|
262
|
+
startTime: z.number().int().nonnegative(),
|
|
263
|
+
version: z.string(),
|
|
264
|
+
executable: z.string(),
|
|
265
|
+
features: z.enum(["full", "stock", "older", "partial", "unknown"]),
|
|
266
|
+
})
|
|
267
|
+
.strict();
|
|
268
|
+
const WorkerStateSchemaZ = z
|
|
269
|
+
.object({
|
|
270
|
+
server: ServerIdentitySchemaZ,
|
|
271
|
+
client: z.string().min(1),
|
|
272
|
+
snapshotPath: z.string().min(1),
|
|
273
|
+
resumeAgents: z.boolean(),
|
|
274
|
+
})
|
|
275
|
+
.strict();
|
|
276
|
+
|
|
277
|
+
export function parseWorkerState(text: string): WorkerState {
|
|
278
|
+
return WorkerStateSchemaZ.parse(JSON.parse(text));
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const WorkerResultSchemaZ = z.object({
|
|
282
|
+
status: z.enum([
|
|
283
|
+
"already-full",
|
|
284
|
+
"preview",
|
|
285
|
+
"declined",
|
|
286
|
+
"refused",
|
|
287
|
+
"handed-off",
|
|
288
|
+
"upgraded",
|
|
289
|
+
"failed",
|
|
290
|
+
]),
|
|
291
|
+
message: z.string(),
|
|
292
|
+
restored: z.array(z.string()).optional(),
|
|
293
|
+
failed: z.array(z.string()).optional(),
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
/** The worker's result, written once at the end; null while it is still running. */
|
|
297
|
+
export function readWorkerResult(path: string): UpgradeResult | null {
|
|
298
|
+
try {
|
|
299
|
+
return WorkerResultSchemaZ.parse(JSON.parse(readFileSync(path, "utf8")));
|
|
300
|
+
} catch {
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Write the worker's result atomically, so the foreground never reads half a file. */
|
|
306
|
+
export function writeWorkerResult(path: string, result: UpgradeResult): void {
|
|
307
|
+
const { status, message, restored, failed } = result;
|
|
308
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
309
|
+
writeFileSync(temporary, JSON.stringify({ status, message, restored, failed }) + "\n", {
|
|
310
|
+
mode: 0o600,
|
|
311
|
+
});
|
|
312
|
+
renameSync(temporary, path);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function processAlive(pid: number): boolean {
|
|
316
|
+
try {
|
|
317
|
+
process.kill(pid, 0);
|
|
318
|
+
return true;
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export interface UpgradeIoOptions {
|
|
325
|
+
target: UpgradeTarget;
|
|
326
|
+
/** The CLI entry the detached worker runs (`node <entry> servers upgrade --continue`). */
|
|
327
|
+
cliEntry: string;
|
|
328
|
+
/** Under `--json` the plan and notes go to stderr, so stdout stays one JSON value. */
|
|
329
|
+
json: boolean;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function createUpgradeIo(options: UpgradeIoOptions): UpgradeIo {
|
|
333
|
+
const socket = targetSocket(options.target);
|
|
334
|
+
let directory: string | null = null;
|
|
335
|
+
const runDirectory = () => (directory ??= newUpgradeDirectory());
|
|
336
|
+
const print = (text: string) => (options.json ? console.error(text) : console.log(text));
|
|
337
|
+
return {
|
|
338
|
+
host: () => hostname(),
|
|
339
|
+
bundled() {
|
|
340
|
+
let executable: string | null;
|
|
341
|
+
try {
|
|
342
|
+
executable = resolveBundledTmux();
|
|
343
|
+
} catch (error) {
|
|
344
|
+
throw new IdeError(
|
|
345
|
+
`tmux-ide's own tmux is damaged (${(error as Error).message}). Reinstall tmux-ide. Nothing was stopped.`,
|
|
346
|
+
{ code: "BUNDLED_TMUX_INVALID", exitCode: 1 },
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
if (!executable) return null;
|
|
350
|
+
const version = execFileSync(executable, ["-V"], {
|
|
351
|
+
encoding: "utf8",
|
|
352
|
+
timeout: 3000,
|
|
353
|
+
env: withBundledTmuxResources(executable, process.env),
|
|
354
|
+
})
|
|
355
|
+
.trim()
|
|
356
|
+
.replace(/^tmux\s+/u, "");
|
|
357
|
+
return { executable, version };
|
|
358
|
+
},
|
|
359
|
+
configuredBinary: () => process.env.TMUX_IDE_TMUX_BIN || undefined,
|
|
360
|
+
identify(client): ServerFacts | null {
|
|
361
|
+
let line: string;
|
|
362
|
+
try {
|
|
363
|
+
line =
|
|
364
|
+
tmux(client, socket, [
|
|
365
|
+
"list-sessions",
|
|
366
|
+
"-F",
|
|
367
|
+
"#{socket_path}\t#{pid}\t#{start_time}\t#{version}",
|
|
368
|
+
]).split("\n")[0] ?? "";
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (NO_SERVER.test(stderrOf(error))) return null;
|
|
371
|
+
throw new IdeError(`Could not read the server at ${socket}: ${stderrOf(error).trim()}`, {
|
|
372
|
+
code: "SERVER_UNREADABLE",
|
|
373
|
+
exitCode: 1,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
const [socketPath = "", pid = "", startTime = "", version = ""] = line.split("\t");
|
|
377
|
+
if (!/^\d+$/u.test(pid) || !/^\d+$/u.test(startTime)) return null;
|
|
378
|
+
return {
|
|
379
|
+
socketPath: socketPath || socket,
|
|
380
|
+
pid: Number(pid),
|
|
381
|
+
startTime: Number(startTime),
|
|
382
|
+
version,
|
|
383
|
+
executable: processExecutable(Number(pid)),
|
|
384
|
+
};
|
|
385
|
+
},
|
|
386
|
+
features(client, at) {
|
|
387
|
+
const probe: TmuxProbe = (args) => tmux(client, at, args);
|
|
388
|
+
const answer = nativeCommands(probe);
|
|
389
|
+
return answer === "no-server" ? "unknown" : answer;
|
|
390
|
+
},
|
|
391
|
+
scratchFeatures(client): ServerFeatures {
|
|
392
|
+
const scratch = mkdtempSync(join(tmpdir(), "tmi-upgrade-"));
|
|
393
|
+
const at = join(scratch, "s");
|
|
394
|
+
const run = (args: readonly string[]) =>
|
|
395
|
+
execFileSync(client, ["-S", at, "-f", "/dev/null", ...args], {
|
|
396
|
+
encoding: "utf8",
|
|
397
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
398
|
+
timeout: 5000,
|
|
399
|
+
env: withBundledTmuxResources(client, process.env),
|
|
400
|
+
});
|
|
401
|
+
try {
|
|
402
|
+
run(["new-session", "-d", "-s", "probe"]);
|
|
403
|
+
const answer = nativeCommands(run);
|
|
404
|
+
return answer === "no-server" ? "unknown" : answer;
|
|
405
|
+
} catch {
|
|
406
|
+
return "unknown";
|
|
407
|
+
} finally {
|
|
408
|
+
try {
|
|
409
|
+
run(["kill-server"]);
|
|
410
|
+
} catch {
|
|
411
|
+
// Already gone.
|
|
412
|
+
}
|
|
413
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
endingPanes(client, at) {
|
|
417
|
+
const table = readProcessTable();
|
|
418
|
+
return tmux(client, at, ["list-panes", "-a", "-F", SNAPSHOT_PANE_FORMAT])
|
|
419
|
+
.split("\n")
|
|
420
|
+
.filter(Boolean)
|
|
421
|
+
.flatMap((line) => {
|
|
422
|
+
const [
|
|
423
|
+
session = "",
|
|
424
|
+
window = "",
|
|
425
|
+
,
|
|
426
|
+
,
|
|
427
|
+
,
|
|
428
|
+
pane = "",
|
|
429
|
+
cwd = "",
|
|
430
|
+
cmd = "",
|
|
431
|
+
pid = "0",
|
|
432
|
+
,
|
|
433
|
+
,
|
|
434
|
+
hint = "",
|
|
435
|
+
] = line.split("\t");
|
|
436
|
+
// tmux-ide's own hidden sessions (updater, app host) hold no user work.
|
|
437
|
+
if (isListableSession(session) || session.startsWith("_tmux-ide")) return [];
|
|
438
|
+
const { agent, command } = resolvePaneCommand(cmd, Number(pid) || 0, hint, table);
|
|
439
|
+
return [{ target: `${session}:${window}.${pane}`, cwd, agent, command }];
|
|
440
|
+
});
|
|
441
|
+
},
|
|
442
|
+
listPanes: (client, at) =>
|
|
443
|
+
tmux(client, at, ["list-panes", "-a", "-F", COVERAGE_PANE_FORMAT])
|
|
444
|
+
.split("\n")
|
|
445
|
+
.filter(Boolean),
|
|
446
|
+
collect: (client, at): FleetSnapshot =>
|
|
447
|
+
// Strict: any tmux error throws, so a partial listing never becomes the snapshot.
|
|
448
|
+
collectFleetSnapshot({
|
|
449
|
+
listPanes: () => tmux(client, at, ["list-panes", "-a", "-F", SNAPSHOT_PANE_FORMAT]),
|
|
450
|
+
listSessions: () => tmux(client, at, ["list-sessions", "-F", SNAPSHOT_SESSION_FORMAT]),
|
|
451
|
+
processTable: () => readProcessTable(),
|
|
452
|
+
}),
|
|
453
|
+
saveSnapshot(snapshot) {
|
|
454
|
+
const path = join(runDirectory(), "snapshot.json");
|
|
455
|
+
writeDurably(path, JSON.stringify(snapshot, null, 2) + "\n");
|
|
456
|
+
return path;
|
|
457
|
+
},
|
|
458
|
+
loadSnapshot: (path) => readSnapshot(path),
|
|
459
|
+
ownPane(client, at) {
|
|
460
|
+
let lines: string[];
|
|
461
|
+
try {
|
|
462
|
+
lines = tmux(client, at, [
|
|
463
|
+
"list-panes",
|
|
464
|
+
"-a",
|
|
465
|
+
"-F",
|
|
466
|
+
"#{pane_pid}\t#{session_name}:#{window_index}.#{pane_index}",
|
|
467
|
+
])
|
|
468
|
+
.split("\n")
|
|
469
|
+
.filter(Boolean);
|
|
470
|
+
} catch {
|
|
471
|
+
return null;
|
|
472
|
+
}
|
|
473
|
+
return ownPaneFrom(ancestry(), lines);
|
|
474
|
+
},
|
|
475
|
+
insideTarget(client, at) {
|
|
476
|
+
const inside = process.env.TMUX?.split(",")[0];
|
|
477
|
+
if (inside && sameFile(inside, at)) return true;
|
|
478
|
+
// $TMUX can be unset or wrong; the process tree can't.
|
|
479
|
+
return this.ownPane(client, at) !== null;
|
|
480
|
+
},
|
|
481
|
+
confirm: (question) =>
|
|
482
|
+
confirmAt(question, {
|
|
483
|
+
isTTY: Boolean(process.stdin.isTTY),
|
|
484
|
+
print,
|
|
485
|
+
ask: async (text) => {
|
|
486
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
487
|
+
try {
|
|
488
|
+
return await prompt.question(text);
|
|
489
|
+
} finally {
|
|
490
|
+
prompt.close();
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
}),
|
|
494
|
+
startWorker(work) {
|
|
495
|
+
const folder = runDirectory();
|
|
496
|
+
const statePath = join(folder, "worker.json");
|
|
497
|
+
writeDurably(statePath, JSON.stringify(work, null, 2) + "\n");
|
|
498
|
+
const log = join(folder, "log");
|
|
499
|
+
const resultPath = join(folder, "result.json");
|
|
500
|
+
const fd = openSync(log, "a", 0o600);
|
|
501
|
+
let pid: number;
|
|
502
|
+
try {
|
|
503
|
+
const child = spawn(
|
|
504
|
+
process.execPath,
|
|
505
|
+
[options.cliEntry, "servers", "upgrade", "--continue", statePath],
|
|
506
|
+
// A session of its own and no terminal: a closing pane, a hangup or
|
|
507
|
+
// Ctrl-C in the foreground does not reach it.
|
|
508
|
+
{ detached: true, stdio: ["ignore", fd, fd], env: process.env },
|
|
509
|
+
);
|
|
510
|
+
child.unref();
|
|
511
|
+
if (!child.pid) throw new Error("the background worker did not start");
|
|
512
|
+
pid = child.pid;
|
|
513
|
+
} finally {
|
|
514
|
+
closeSync(fd);
|
|
515
|
+
}
|
|
516
|
+
return { log, resultPath, pid };
|
|
517
|
+
},
|
|
518
|
+
async waitForWorker(handle) {
|
|
519
|
+
const note = () => print(`\nThe restart continues in the background. Log: ${handle.log}`);
|
|
520
|
+
const onSignal = () => {
|
|
521
|
+
note();
|
|
522
|
+
process.exit(130);
|
|
523
|
+
};
|
|
524
|
+
process.once("SIGINT", onSignal);
|
|
525
|
+
process.once("SIGTERM", onSignal);
|
|
526
|
+
try {
|
|
527
|
+
const deadline = Date.now() + 10 * 60_000;
|
|
528
|
+
for (;;) {
|
|
529
|
+
const result = readWorkerResult(handle.resultPath);
|
|
530
|
+
if (result) return result;
|
|
531
|
+
if (!processAlive(handle.pid) || Date.now() > deadline) {
|
|
532
|
+
// One last look: it may have written the result just before it exited.
|
|
533
|
+
return readWorkerResult(handle.resultPath);
|
|
534
|
+
}
|
|
535
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
536
|
+
}
|
|
537
|
+
} finally {
|
|
538
|
+
process.off("SIGINT", onSignal);
|
|
539
|
+
process.off("SIGTERM", onSignal);
|
|
540
|
+
}
|
|
541
|
+
},
|
|
542
|
+
kill(client, server) {
|
|
543
|
+
// tmux checks the identity itself, so a newer server on the socket is never ended.
|
|
544
|
+
let outcome: ReturnType<typeof killOutcome>;
|
|
545
|
+
try {
|
|
546
|
+
outcome = killOutcome({ stdout: tmux(client, server.socketPath, killGuardArgs(server)) });
|
|
547
|
+
} catch (error) {
|
|
548
|
+
outcome = killOutcome({ stderr: stderrOf(error) });
|
|
549
|
+
}
|
|
550
|
+
if (outcome === "mismatch") throw new Error("another server now answers on that socket");
|
|
551
|
+
if (typeof outcome === "object") throw new Error(outcome.error);
|
|
552
|
+
},
|
|
553
|
+
serverGone(client, at) {
|
|
554
|
+
const deadline = Date.now() + 5000;
|
|
555
|
+
for (;;) {
|
|
556
|
+
try {
|
|
557
|
+
tmux(client, at, ["list-sessions", "-F", "#{pid}"]);
|
|
558
|
+
} catch (error) {
|
|
559
|
+
if (NO_SERVER.test(stderrOf(error))) return true;
|
|
560
|
+
}
|
|
561
|
+
if (Date.now() > deadline) return false;
|
|
562
|
+
execFileSync("/bin/sleep", ["0.1"]);
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
async restore({ client, socket: at, snapshotPath, resumeAgents }) {
|
|
566
|
+
const environment = withBundledTmuxResources(client, process.env);
|
|
567
|
+
// Every runTmux in restore goes to this binary and this socket.
|
|
568
|
+
const release = configureTmuxClientResolver(() => ({
|
|
569
|
+
executable: client,
|
|
570
|
+
environment,
|
|
571
|
+
globalArgs: ["-S", at],
|
|
572
|
+
}));
|
|
573
|
+
try {
|
|
574
|
+
// Start the server explicitly, so a binary that can't start one throws here
|
|
575
|
+
// instead of failing each session one by one.
|
|
576
|
+
tmux(client, at, ["new-session", "-d", "-s", UPGRADE_HOLD_SESSION]);
|
|
577
|
+
const outcome = await restoreFleet({
|
|
578
|
+
from: snapshotPath,
|
|
579
|
+
snapshotOnly: true,
|
|
580
|
+
resumeAgents,
|
|
581
|
+
resumeFromConfig: false,
|
|
582
|
+
});
|
|
583
|
+
return { restored: outcome.restored, failed: outcome.failed };
|
|
584
|
+
} finally {
|
|
585
|
+
release();
|
|
586
|
+
try {
|
|
587
|
+
tmux(client, at, ["kill-session", "-t", `=${UPGRADE_HOLD_SESSION}`]);
|
|
588
|
+
} catch {
|
|
589
|
+
// Never started, or already gone.
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
},
|
|
593
|
+
print,
|
|
594
|
+
nowSec: () => Math.floor(Date.now() / 1000),
|
|
595
|
+
};
|
|
596
|
+
}
|