The best way to control Claude Code, Codex and more from any computer or phone

main
ts 634 lines 27.8 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - Drives the real shell installer against a local GitHub fixture.
2 import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as NodeChildProcess from "node:child_process";
4 import * as NodeCrypto from "node:crypto";
5 import * as NodeFSP from "node:fs/promises";
6 import * as NodeHttp from "node:http";
7 import * as NodeOS from "node:os";
8 import * as NodePath from "node:path";
9 import { describe, expect, it } from "vite-plus/test";
10
11 /** The launcher install.sh, `t3 install`, and `t3 update` write; exec by absolute path. */
12 const launcherScript = (executable: string) =>
13 `#!/bin/sh\nexec '${executable.replaceAll("'", "'\\''")}' "$@"\n`;
14
15 const nightlies = Array.from({ length: 100 }, (_, index) => ({
16 tag_name: `v1.2.4-nightly.20261020.${200 - index}`,
17 }));
18
19 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer home", () => {
20 it("installs a relative home from a directory ending in a newline", async () => {
21 const temporaryRoot = await NodeFSP.realpath(
22 await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-home-")),
23 );
24 const root = NodePath.join(temporaryRoot, "cwd\n");
25 const homeName = "-custom home\\home\n";
26 const home = NodePath.join(root, homeName);
27 const version = "1.2.3";
28 const target = NodePath.join(home, "runtime/versions", version);
29 const launcher = NodePath.join(root, "bin/t3");
30 try {
31 await NodeFSP.mkdir(target, { recursive: true });
32 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
33 await NodeFSP.writeFile(NodePath.join(target, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", {
34 mode: 0o755,
35 });
36 const install = () =>
37 NodeChildProcess.spawnSync("sh", [NodePath.resolve(import.meta.dirname, "install.sh")], {
38 cwd: root,
39 env: {
40 ...process.env,
41 HOME: root,
42 T3CODE_HOME: homeName,
43 T3CODE_VERSION: version,
44 T3CODE_INSTALL_BIN_DIR: NodePath.dirname(launcher),
45 T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:1",
46 },
47 encoding: "utf8",
48 });
49 // The second run replaces the launcher the first wrote, newlines in its path and all.
50 const first = install();
51 expect(first.status, first.stdout + first.stderr).toBe(0);
52 const { status, stdout, stderr } = install();
53 expect(status, stdout + stderr).toBe(0);
54 expect(stderr).toContain(`Installed T3 Code ${version}`);
55 expect(await NodeFSP.readFile(launcher, "utf8")).toBe(
56 launcherScript(NodePath.join(target, "t3")),
57 );
58 expect(
59 NodeChildProcess.execFileSync(launcher, ["--version"], {
60 cwd: NodeOS.tmpdir(),
61 encoding: "utf8",
62 }).trim(),
63 ).toBe("t3 v1.2.3");
64 } finally {
65 await NodeFSP.rm(temporaryRoot, { recursive: true, force: true });
66 }
67 });
68 });
69
70 // regression: #22490
71 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer channel lookup", () => {
72 it.each([
73 // regression: #32897
74 ["stable", "1.2.3", 1],
75 ["preview", "1.2.4-preview.20261019.50", 0],
76 ])("finds %s %s behind nightlies and %i HTTP 504s", async (channel, version, failures) => {
77 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-index-"));
78 const target = NodePath.join(root, "home/runtime/versions", version);
79 const server = NodeHttp.createServer((request, response) => {
80 if (failures-- > 0) return response.writeHead(504).end();
81 const url = new URL(request.url ?? "/", "http://fixture");
82 const body =
83 url.pathname === "/pingdotgg/t3code/releases/latest" &&
84 request.headers.accept === "application/json"
85 ? { tag_name: "v1.2.3" }
86 : url.pathname === "/repos/pingdotgg/t3code/releases"
87 ? { "1": nightlies, "2": [{ tag_name: `v${version}` }, { tag_name: "v1.2.3" }] }[
88 url.searchParams.get("page") ?? ""
89 ]
90 : undefined;
91 if (body === undefined) response.statusCode = 404;
92 // The API pretty-prints and the installer reads it line by line.
93 response.end(JSON.stringify(body ?? [], null, 2));
94 });
95 try {
96 // An existing completed install isolates release resolution from archive downloads.
97 await NodeFSP.mkdir(target, { recursive: true });
98 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), `${version}\n`);
99 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
100 const address = server.address();
101 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
102 const origin = `http://127.0.0.1:${address.port}`;
103 const source = await NodeFSP.readFile(
104 NodePath.resolve(import.meta.dirname, "install.sh"),
105 "utf8",
106 );
107 const installer = NodePath.join(root, "install.sh");
108 await NodeFSP.writeFile(installer, source.replace(/https:\/\/(api\.)?github\.com/g, origin));
109 const { code, output } = await new Promise<{ code: number | null; output: string }>(
110 (resolve, reject) => {
111 const child = NodeChildProcess.spawn("sh", [installer], {
112 env: {
113 ...process.env,
114 T3CODE_VERSION: "",
115 T3CODE_CHANNEL: channel,
116 T3CODE_HOME: NodePath.join(root, "home"),
117 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
118 // A wrong version must fail here instead of downloading a real release.
119 T3CODE_RELEASE_BASE_URL: origin,
120 },
121 stdio: ["ignore", "pipe", "pipe"],
122 });
123 let output = "";
124 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
125 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
126 child.on("error", reject);
127 child.on("close", (code) => resolve({ code, output }));
128 },
129 );
130 expect(code, output).toBe(0);
131 expect(output).toContain(`Installed T3 Code ${version}`);
132 } finally {
133 server.closeAllConnections();
134 await new Promise<void>((resolve) => server.close(() => resolve()));
135 await NodeFSP.rm(root, { recursive: true, force: true });
136 }
137 });
138 });
139
140 // regression: #35834
141 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
142 "installer archive download",
143 () => {
144 it("names the archive when it returns 404", async () => {
145 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-archive-"));
146 const arch = HostProcess.Architecture.defaultValue() === "arm64" ? "arm64" : "x64";
147 const archive = `t3-1.2.3-linux-${arch}.tar.gz`;
148 const server = NodeHttp.createServer((request, response) => {
149 if (request.url === "/v1.2.3/SHA256SUMS")
150 return response.end(`${"0".repeat(64)} ${archive}\n`);
151 response.writeHead(404).end();
152 });
153 try {
154 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
155 const address = server.address();
156 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
157 const { code, output } = await new Promise<{ code: number | null; output: string }>(
158 (resolve, reject) => {
159 const child = NodeChildProcess.spawn(
160 "sh",
161 [NodePath.resolve(import.meta.dirname, "install.sh")],
162 {
163 env: {
164 ...process.env,
165 T3CODE_CHANNEL: "",
166 T3CODE_VERSION: "1.2.3",
167 T3CODE_HOME: NodePath.join(root, "home"),
168 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
169 T3CODE_RELEASE_BASE_URL: `http://127.0.0.1:${address.port}`,
170 },
171 stdio: ["ignore", "pipe", "pipe"],
172 },
173 );
174 let output = "";
175 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
176 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
177 child.on("error", reject);
178 child.on("close", (code) => resolve({ code, output }));
179 },
180 );
181 expect(code, output).not.toBe(0);
182 expect(output).toMatch(new RegExp(`t3 install: .*${archive.replaceAll(".", "\\.")}`));
183 } finally {
184 server.closeAllConnections();
185 await new Promise<void>((resolve) => server.close(() => resolve()));
186 await NodeFSP.rm(root, { recursive: true, force: true });
187 }
188 });
189 },
190 );
191
192 /** Runs an installer for a version that is already unpacked, so only the t3 command step runs. */
193 async function installOver(input: {
194 readonly script: "install.sh" | "install.ps1";
195 readonly home: string;
196 readonly binDir: string;
197 readonly env?: NodeJS.ProcessEnv;
198 readonly cwd?: string;
199 }) {
200 const target = NodePath.join(input.home, "runtime", "versions", "1.2.3");
201 await NodeFSP.mkdir(target, { recursive: true });
202 await NodeFSP.writeFile(NodePath.join(target, ".install-complete"), "1.2.3\n");
203 const installer = NodePath.resolve(import.meta.dirname, input.script);
204 const [command, args] =
205 input.script === "install.sh"
206 ? ["sh", [installer]]
207 : ["powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", installer]];
208 const result = NodeChildProcess.spawnSync(command, args, {
209 encoding: "utf8",
210 ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
211 env: {
212 ...process.env,
213 T3CODE_CHANNEL: "",
214 T3CODE_VERSION: "1.2.3",
215 T3CODE_HOME: input.home,
216 T3CODE_INSTALL_BIN_DIR: input.binDir,
217 T3CODE_RELEASE_BASE_URL: "http://127.0.0.1:9",
218 ...input.env,
219 },
220 });
221 return { code: result.status, output: `${result.stdout}${result.stderr}`, target };
222 }
223
224 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("install.sh t3 command", () => {
225 it("replaces only this home's own launchers and prints a PATH command", async () => {
226 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-link-"));
227 try {
228 const home = NodePath.join(root, "home");
229 const binDir = NodePath.join(root, "bin");
230 const link = NodePath.join(binDir, "t3");
231 await NodeFSP.mkdir(binDir, { recursive: true });
232
233 await NodeFSP.writeFile(link, "#!/bin/sh\necho mine\n");
234 const foreign = await installOver({ script: "install.sh", home, binDir });
235 expect(foreign.code).not.toBe(0);
236 expect(foreign.output).toContain(`another t3 is already at ${link}`);
237 expect(await NodeFSP.readFile(link, "utf8")).toBe("#!/bin/sh\necho mine\n");
238 // Not even from inside the versions folder, where `.` would resolve into it.
239 const fromVersions = await installOver({
240 script: "install.sh",
241 home,
242 binDir,
243 cwd: foreign.target,
244 });
245 expect(fromVersions.code).not.toBe(0);
246 expect(await NodeFSP.readFile(link, "utf8")).toBe("#!/bin/sh\necho mine\n");
247
248 // A link that only looks like it points into versions (join() would normalize the ..).
249 await NodeFSP.rm(link);
250 await NodeFSP.mkdir(NodePath.join(home, "other"), { recursive: true });
251 await NodeFSP.writeFile(NodePath.join(home, "other/t3"), "#!/bin/sh\n");
252 await NodeFSP.symlink(`${home}/runtime/versions/../../other/t3`, link);
253 const climbing = await installOver({ script: "install.sh", home, binDir });
254 expect(climbing.code).not.toBe(0);
255 expect(await NodeFSP.readlink(link)).toBe(`${home}/runtime/versions/../../other/t3`);
256
257 // Only `<version>/t3` counts, not another program inside a version.
258 await NodeFSP.rm(link);
259 await NodeFSP.symlink(NodePath.join(home, "runtime/versions/1.0.0/helper"), link);
260 const sibling = await installOver({ script: "install.sh", home, binDir });
261 expect(sibling.code).not.toBe(0);
262 expect(await NodeFSP.readlink(link)).toBe(
263 NodePath.join(home, "runtime/versions/1.0.0/helper"),
264 );
265
266 // An upgrade over an older version's link, written through a symlinked T3 home.
267 await NodeFSP.rm(link);
268 await NodeFSP.symlink(NodePath.join(home, "runtime/versions/1.0.0/t3"), link);
269 await NodeFSP.symlink(home, NodePath.join(root, "alias"));
270 const upgrade = await installOver({
271 script: "install.sh",
272 home: NodePath.join(root, "alias"),
273 binDir,
274 env: { HOME: root, SHELL: "/bin/zsh", PATH: "/usr/bin:/bin" },
275 });
276 expect(upgrade.code, upgrade.output).toBe(0);
277 expect(await NodeFSP.readFile(link, "utf8")).toBe(
278 launcherScript(NodePath.join(root, "alias/runtime/versions/1.2.3/t3")),
279 );
280 expect(upgrade.output).toContain(
281 `printf '\\n%s\\n' 'export PATH="$PATH:$HOME/bin"' >> ~/.zshrc`,
282 );
283
284 // Containers and CI often have no SHELL; `set -u` must not stop the installer there.
285 const noShell = await installOver({
286 script: "install.sh",
287 home,
288 binDir,
289 env: { HOME: root, SHELL: undefined, PATH: "/usr/bin:/bin" },
290 });
291 expect(noShell.code, noShell.output).toBe(0);
292 expect(noShell.output).toContain(`Add ${binDir} to your PATH`);
293
294 // Its folder on PATH with a trailing slash is still this t3, not another one.
295 const slashed = await installOver({
296 script: "install.sh",
297 home,
298 binDir,
299 env: { HOME: root, PATH: `${binDir}/:/usr/bin:/bin` },
300 });
301 expect(slashed.code, slashed.output).toBe(0);
302 expect(slashed.output).toContain("Run t3 to use T3 Code here");
303
304 // A relative folder is made absolute, so the PATH command never follows the working directory.
305 const relative = await installOver({
306 script: "install.sh",
307 home,
308 binDir: "bin",
309 cwd: root,
310 env: { HOME: root, SHELL: "/bin/zsh", PATH: "/usr/bin:/bin" },
311 });
312 expect(relative.code, relative.output).toBe(0);
313 expect(relative.output).toContain(`'export PATH="$PATH:$HOME/bin"'`);
314
315 // A launcher script someone edited is theirs now.
316 const edited = `${launcherScript(NodePath.join(home, "runtime/versions/1.2.3/t3"))}# mine\n`;
317 await NodeFSP.writeFile(link, edited);
318 const overEdited = await installOver({ script: "install.sh", home, binDir });
319 expect(overEdited.code).not.toBe(0);
320 expect(await NodeFSP.readFile(link, "utf8")).toBe(edited);
321
322 await NodeFSP.rm(link);
323 await NodeFSP.symlink(NodePath.join(home, "bin/t3"), link);
324 const overDesktop = await installOver({
325 script: "install.sh",
326 home: `${home}//`,
327 binDir: `${binDir}/`,
328 });
329 expect(overDesktop.code, overDesktop.output).toBe(0);
330 expect(await NodeFSP.readFile(link, "utf8")).toBe(
331 launcherScript(NodePath.join(home, "runtime/versions/1.2.3/t3")),
332 );
333 } finally {
334 await NodeFSP.rm(root, { recursive: true, force: true });
335 }
336 });
337 });
338
339 describe.skipIf(HostProcess.Platform.defaultValue() !== "win32")("install.ps1 t3 command", () => {
340 it("replaces only its own t3.cmd, also in non-ASCII and bracketed paths", async () => {
341 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-ps1-"));
342 try {
343 // Windows PowerShell 5.1 reads files as ANSI by default and expands wildcards in paths.
344 const home = NodePath.join(root, "José", ".t3");
345 const binDir = NodePath.join(root, "bin[t3]");
346 const shim = NodePath.join(binDir, "t3.cmd");
347 await NodeFSP.mkdir(binDir, { recursive: true });
348
349 const desktopShim = '@echo off\r\n"C:\\Program Files\\T3 Code\\T3 Code.exe" "x" %*\r\n';
350 await NodeFSP.writeFile(shim, desktopShim);
351 const foreign = await installOver({ script: "install.ps1", home, binDir });
352 expect(foreign.code).not.toBe(0);
353 expect(foreign.output).toContain("another t3 is already at");
354 expect(await NodeFSP.readFile(shim, "utf8")).toBe(desktopShim);
355
356 // A hand-edited wrapper may set its own environment; replacing it would drop that.
357 const edited = `@echo off\r\nset "T3CODE_HOME=D:\\other"\r\n"${NodePath.join(home, "runtime", "versions", "1.0.0", "t3.exe")}" %*`;
358 await NodeFSP.writeFile(shim, edited, "utf8");
359 const wrapper = await installOver({ script: "install.ps1", home, binDir });
360 expect(wrapper.code).not.toBe(0);
361 expect(await NodeFSP.readFile(shim, "utf8")).toBe(edited);
362
363 const climbing = `@echo off\r\n"${NodePath.join(home, "runtime", "versions")}\\..\\other\\t3.exe" %*`;
364 await NodeFSP.writeFile(shim, climbing, "utf8");
365 const outside = await installOver({ script: "install.ps1", home, binDir });
366 expect(outside.code).not.toBe(0);
367 expect(await NodeFSP.readFile(shim, "utf8")).toBe(climbing);
368
369 const older = NodePath.join(home, "runtime", "versions", "1.0.0", "t3.exe");
370 await NodeFSP.writeFile(shim, `@echo off\r\n"${older}" %*`, "utf8");
371 const upgrade = await installOver({ script: "install.ps1", home, binDir });
372 expect(upgrade.code, upgrade.output).toBe(0);
373 expect(await NodeFSP.readFile(shim, "utf8")).toContain(
374 NodePath.join(upgrade.target, "t3.exe"),
375 );
376
377 const again = await installOver({ script: "install.ps1", home, binDir });
378 expect(again.code, again.output).toBe(0);
379
380 // Another t3 first on PATH still runs, so the installer names this one in full.
381 const otherBin = NodePath.join(root, "other");
382 await NodeFSP.mkdir(otherBin);
383 await NodeFSP.writeFile(NodePath.join(otherBin, "t3.cmd"), "@echo off\r\n");
384 // Windows spells it Path; a second PATH key would be ambiguous.
385 const pathKey =
386 Object.keys(process.env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
387 const shadowed = await installOver({
388 script: "install.ps1",
389 home,
390 binDir,
391 env: { [pathKey]: `${otherBin};${process.env[pathKey] ?? ""}` },
392 });
393 expect(shadowed.code, shadowed.output).toBe(0);
394 expect(shadowed.output).toContain(
395 `Another t3 at ${NodePath.join(otherBin, "t3.cmd")} runs first`,
396 );
397
398 // Its own folder on PATH with a trailing separator is already on PATH.
399 const slashed = await installOver({
400 script: "install.ps1",
401 home,
402 binDir,
403 env: { [pathKey]: `${binDir}\\;${process.env[pathKey] ?? ""}` },
404 });
405 expect(slashed.code, slashed.output).toBe(0);
406 expect(slashed.output).toContain("to use T3 Code here");
407 // The same when the install folder itself is given with a trailing separator.
408 const bothSlashed = await installOver({
409 script: "install.ps1",
410 home,
411 binDir: `${binDir}\\`,
412 env: { [pathKey]: `${binDir}\\;${process.env[pathKey] ?? ""}` },
413 });
414 expect(bothSlashed.code, bothSlashed.output).toBe(0);
415 expect(bothSlashed.output).toContain("to use T3 Code here");
416 } finally {
417 await NodeFSP.rm(root, { recursive: true, force: true });
418 }
419 });
420 });
421
422 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer checksum", () => {
423 it.each(
424 ["home\\data", "home\ndata"].flatMap((homeName) =>
425 [true, false].map((validChecksum) => ({ homeName, validChecksum })),
426 ),
427 )(
428 "verifies home $homeName with valid checksum $validChecksum",
429 async ({ homeName, validChecksum }) => {
430 const availableTools = ["sha256sum", "shasum"].filter(
431 (tool) =>
432 NodeChildProcess.spawnSync("sh", ["-c", 'command -v "$1"', "sh", tool]).status === 0,
433 );
434 expect(availableTools.length).toBeGreaterThan(0);
435 for (const checksumTool of availableTools) {
436 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-checksum-"));
437 const home = NodePath.join(root, homeName);
438 const version = "1.2.3";
439 const stem = `t3-${version}-linux-${HostProcess.Architecture.defaultValue()}`;
440 const archiveName = `${stem}.tar.gz`;
441 const server = NodeHttp.createServer();
442 try {
443 const tools = NodePath.join(root, "tools");
444 await NodeFSP.mkdir(tools);
445 for (const command of [
446 "sh",
447 "uname",
448 "tar",
449 "gzip",
450 "cut",
451 "curl",
452 "grep",
453 "mkdir",
454 "mktemp",
455 "rm",
456 "mv",
457 "ln",
458 "chmod",
459 "sed",
460 checksumTool,
461 ]) {
462 const executable = NodeChildProcess.execFileSync(
463 "sh",
464 ["-c", 'command -v "$1"', "sh", command],
465 { encoding: "utf8" },
466 ).trim();
467 await NodeFSP.symlink(executable, NodePath.join(tools, command));
468 }
469 await NodeFSP.mkdir(NodePath.join(root, stem));
470 await NodeFSP.writeFile(
471 NodePath.join(root, stem, "t3"),
472 "#!/bin/sh\necho 't3 v1.2.3'\n",
473 { mode: 0o755 },
474 );
475 const archivePath = NodePath.join(root, archiveName);
476 NodeChildProcess.execFileSync("tar", ["-czf", archivePath, "-C", root, stem]);
477 const archive = await NodeFSP.readFile(archivePath);
478 const digest = NodeCrypto.createHash("sha256").update(archive).digest("hex");
479 server.on("request", (request, response) => {
480 response.end(
481 request.url?.endsWith("/SHA256SUMS")
482 ? `${validChecksum ? digest : "0".repeat(64)} ${archiveName}\n`
483 : archive,
484 );
485 });
486 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
487 const address = server.address();
488 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
489 const { code, output } = await new Promise<{ code: number | null; output: string }>(
490 (resolve, reject) => {
491 const child = NodeChildProcess.spawn(
492 "sh",
493 [NodePath.resolve(import.meta.dirname, "install.sh")],
494 {
495 env: {
496 ...process.env,
497 PATH: tools,
498 T3CODE_VERSION: version,
499 T3CODE_HOME: home,
500 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"),
501 T3CODE_RELEASE_BASE_URL: `http://127.0.0.1:${address.port}`,
502 },
503 stdio: ["ignore", "pipe", "pipe"],
504 },
505 );
506 let output = "";
507 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
508 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
509 child.on("error", reject);
510 child.on("close", (code) => resolve({ code, output }));
511 },
512 );
513 const versions = NodePath.join(home, "runtime/versions");
514 if (validChecksum) {
515 expect(code, `${checksumTool}: ${output}`).toBe(0);
516 expect(
517 await NodeFSP.readFile(NodePath.join(versions, version, ".install-complete"), "utf8"),
518 ).toBe("1.2.3\n");
519 expect(
520 NodeChildProcess.execFileSync(NodePath.join(root, "bin/t3"), ["--version"], {
521 encoding: "utf8",
522 }).trim(),
523 ).toBe("t3 v1.2.3");
524 } else {
525 expect(code).not.toBe(0);
526 expect(output).toContain("checksum mismatch");
527 expect(output).not.toContain("Installed T3 Code");
528 expect(await NodeFSP.readdir(versions)).toEqual([]);
529 }
530 } finally {
531 server.closeAllConnections();
532 await new Promise<void>((resolve) => server.close(() => resolve()));
533 await NodeFSP.rm(root, { recursive: true, force: true });
534 }
535 }
536 },
537 );
538 });
539
540 // regression: #38234
541 describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("concurrent installers", () => {
542 it("publishes one runtime without nesting the other install's staging directory", async () => {
543 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-install-concurrent-"));
544 const version = "1.2.3";
545 const stem = `t3-${version}-linux-${HostProcess.Architecture.defaultValue()}`;
546 const archiveName = `${stem}.tar.gz`;
547 const target = NodePath.join(root, "home/runtime/versions", version);
548 const waiting = new Map<string, NodeHttp.ServerResponse>();
549 const server = NodeHttp.createServer();
550 try {
551 const tools = NodePath.join(root, "tools");
552 await NodeFSP.mkdir(tools);
553 await NodeFSP.mkdir(NodePath.join(root, stem));
554 await NodeFSP.writeFile(NodePath.join(root, stem, "t3"), "#!/bin/sh\necho 't3 v1.2.3'\n", {
555 mode: 0o755,
556 });
557 const archivePath = NodePath.join(root, archiveName);
558 NodeChildProcess.execFileSync("tar", ["-czf", archivePath, "-C", root, stem]);
559 const archive = await NodeFSP.readFile(archivePath);
560 const digest = NodeCrypto.createHash("sha256").update(archive).digest("hex");
561 server.on("request", (request, response) => {
562 if (request.url?.startsWith("/ready/")) {
563 waiting.set(request.url.slice(7), response);
564 if (waiting.size === 2) waiting.get("first")!.end("go");
565 } else if (request.url === "/published") {
566 waiting.get("second")!.end("go");
567 response.end("ok");
568 } else {
569 response.end(
570 request.url?.endsWith("/SHA256SUMS") ? `${digest} ${archiveName}\n` : archive,
571 );
572 }
573 });
574 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
575 const address = server.address();
576 if (!address || typeof address === "string") throw new Error("Expected a TCP listener");
577 const origin = `http://127.0.0.1:${address.port}`;
578 const realMv = NodeChildProcess.execFileSync("sh", ["-c", "command -v mv"], {
579 encoding: "utf8",
580 }).trim();
581 // Hold publication until both installers have removed the destination, then let them rename in order.
582 const wrapper = NodePath.join(tools, "mv.mjs");
583 await NodeFSP.writeFile(
584 wrapper,
585 `
586 import { execFileSync } from 'node:child_process';
587 await fetch(process.env.T3_TEST_ORIGIN + '/ready/' + process.env.T3_TEST_INSTALLER);
588 execFileSync(${JSON.stringify(realMv)}, process.argv.slice(2));
589 if (process.env.T3_TEST_INSTALLER === 'first') await fetch(process.env.T3_TEST_ORIGIN + '/published');
590 `,
591 );
592 await NodeFSP.writeFile(
593 NodePath.join(tools, "mv"),
594 `#!/bin/sh\nexec '${process.execPath}' '${wrapper}' "$@"\n`,
595 { mode: 0o755 },
596 );
597 const install = (id: string) =>
598 new Promise<{ code: number | null; output: string }>((resolve, reject) => {
599 const child = NodeChildProcess.spawn(
600 "sh",
601 [NodePath.join(import.meta.dirname, "install.sh")],
602 {
603 env: {
604 ...process.env,
605 PATH: `${tools}:${process.env.PATH}`,
606 T3CODE_VERSION: version,
607 T3CODE_HOME: NodePath.join(root, "home"),
608 T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin", id),
609 T3CODE_RELEASE_BASE_URL: origin,
610 T3_TEST_ORIGIN: origin,
611 T3_TEST_INSTALLER: id,
612 },
613 stdio: ["ignore", "pipe", "pipe"],
614 },
615 );
616 let output = "";
617 child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString()));
618 child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString()));
619 child.on("error", reject);
620 child.on("close", (code) => resolve({ code, output }));
621 });
622 const results = await Promise.all([install("first"), install("second")]);
623 for (const result of results) expect(result.code, result.output).toBe(0);
624 expect(
625 (await NodeFSP.readdir(target)).filter((name) => name.startsWith(".staging-")),
626 "concurrent installs must not leave a nested runtime",
627 ).toEqual([]);
628 } finally {
629 server.closeAllConnections();
630 await new Promise<void>((resolve) => server.close(() => resolve()));
631 await NodeFSP.rm(root, { recursive: true, force: true });
632 }
633 });
634 });