Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Runs the rendered launcher in a real shell.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import { afterEach, describe, expect, it } from "vite-plus/test";
8
9import { type CliShimTarget, renderCliShim } from "./DesktopCliShim.ts";
10
11const directories: Array<string> = [];
12afterEach(() => {
13 for (const directory of directories.splice(0)) {
14 NodeFS.rmSync(directory, { recursive: true, force: true });
15 }
16});
17
18const tempRoot = () => {
19 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-shim-"));
20 directories.push(root);
21 return root;
22};
23
24const writeExecutable = (path: string, content: string) => {
25 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
26 NodeFS.writeFileSync(path, content, { mode: 0o755 });
27};
28
29const writeShim = (root: string, target: CliShimTarget) => {
30 const shim = NodePath.join(root, "bin", "t3");
31 writeExecutable(shim, renderCliShim({ target, shimPath: shim, t3Home: `${root}/home` }));
32 return shim;
33};
34
35const run = (shim: string, args: ReadonlyArray<string>, env: NodeJS.ProcessEnv = {}) =>
36 NodeChildProcess.spawnSync(shim, args, {
37 encoding: "utf8",
38 env: { PATH: process.env.PATH, ...env },
39 });
40
41const REPORTER =
42 '#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME appimage=$APPIMAGE"\nprintf "%s\\n" "$@"\nexit 3\n';
43
44const fakeAppImage = (canMount = true, app = REPORTER) => {
45 const root = tempRoot();
46 const image = NodePath.join(root, "image");
47 writeExecutable(NodePath.join(image, "t3code"), app);
48 const appImage = NodePath.join(root, "T3 Code.AppImage");
49 writeExecutable(
50 appImage,
51 [
52 "#!/bin/sh",
53 `if [ "$1" = --appimage-extract ]; then cp -R '${image}' squashfs-root; exit 0; fi`,
54 '[ "$1" = --appimage-mount ] || exit 9',
55 '[ -n "$APPIMAGE_EXTRACT_AND_RUN" ] && exit 8',
56 `echo $$ >'${root}/mounter.pid'`,
57 canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1',
58 // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open.
59 "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT",
60 "trap 'echo mounted >&3 2>/dev/null' WINCH",
61 "while :; do sleep 0.05; done",
62 "",
63 ].join("\n"),
64 );
65 const shim = writeShim(root, { kind: "appimage", appImage, executableName: "t3code" });
66 return { root, image, appImage, shim };
67};
68
69// Stays up after a signal until the test lets it finish, like a server shutting down.
70const SLOW_SERVER = [
71 "#!/bin/sh",
72 "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP",
73 "echo ready",
74 "while :; do sleep 0.05; done",
75 "",
76].join("\n");
77
78// The launcher mounts only under setsid, which stock macOS and Windows lack; there it extracts instead.
79const hasSetsid = NodeChildProcess.spawnSync("setsid", ["true"]).status === 0;
80
81const lines = (stream: NodeJS.ReadableStream) => {
82 const seen: Array<string> = [];
83 const waiters: Array<() => void> = [];
84 let buffer = "";
85 stream.setEncoding("utf8");
86 stream.on("data", (chunk: string) => {
87 buffer += chunk;
88 const parts = buffer.split("\n");
89 buffer = parts.pop()!;
90 seen.push(...parts);
91 for (const wake of waiters.splice(0)) wake();
92 });
93 const until = async (match: (line: string) => boolean) => {
94 for (;;) {
95 const line = seen.find(match);
96 if (line !== undefined) return line;
97 await new Promise<void>((resolve) => waiters.push(resolve));
98 }
99 };
100 return { seen, until };
101};
102
103describe("renderCliShim", () => {
104 // Ctrl-C, an SSH hangup, or a supervisor signals the process group. systemd's default KillMode
105 // also signals the mounter, and KillMode=mixed signals only the launcher.
106 it.skipIf(!hasSetsid).each([
107 ["SIGTERM", "the process group"],
108 ["SIGHUP", "the process group"],
109 ["SIGTERM", "every process"],
110 ["SIGTERM", "the launcher"],
111 ] as const)(
112 "keeps the AppImage mounted until the server exits after %s to %s",
113 async (signal, target) => {
114 const { root, shim } = fakeAppImage(true, SLOW_SERVER);
115 const child = NodeChildProcess.spawn(shim, [], {
116 detached: true,
117 env: { PATH: process.env.PATH },
118 stdio: ["pipe", "pipe", "ignore", "pipe"],
119 });
120 let mounter: number | undefined;
121 try {
122 const stdout = lines(child.stdout!);
123 const events = lines(child.stdio[3] as NodeJS.ReadableStream);
124 const exited = new Promise<number | null>((resolve) => child.on("close", resolve));
125 await stdout.until((line) => line === "ready");
126 mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8"));
127
128 process.kill(target === "the launcher" ? child.pid! : -child.pid!, signal);
129 if (target === "every process") process.kill(mounter, signal);
130 // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and
131 // HUP, so a mounter that also got the group signal unmounts before it answers this probe.
132 process.kill(mounter, "SIGWINCH");
133 const mount = await events.until((line) => line === "mounted" || line === "unmounted");
134 expect(mount).toBe("mounted");
135
136 await events.until((line) => line === "stopping");
137 child.stdin!.end("go\n");
138 expect(await exited).toBe(7);
139 expect(events.seen.slice(-2)).toEqual(["stopped go", "unmounted"]);
140 } finally {
141 for (const pid of [-child.pid!, mounter]) {
142 if (pid === undefined) continue;
143 try {
144 process.kill(pid, "SIGKILL");
145 } catch {}
146 }
147 }
148 },
149 );
150
151 it("extracts the AppImage where it cannot be mounted", () => {
152 const { shim } = fakeAppImage(false);
153 const result = run(shim, ["--version"], { APPIMAGE_EXTRACT_AND_RUN: "1" });
154 expect(result.status).toBe(3);
155 expect(result.stdout).toMatch(
156 /squashfs-root\/resources\/app\.asar\/apps\/server\/dist\/bin\.mjs/,
157 );
158 });
159
160 // The server skips its compile cache only under APPIMAGE; each mount path is new.
161 it("tells the CLI it runs from the mounted AppImage", () => {
162 const { appImage, shim } = fakeAppImage();
163 const result = run(shim, ["--version"]);
164 expect(result.status).toBe(3);
165 expect(result.stdout).toContain(`appimage=${appImage}`);
166 const closedStdin = NodeChildProcess.spawnSync("sh", ["-c", '"$0" --version <&-', shim]);
167 expect(closedStdin.status).toBe(3);
168 });
169
170 it("keeps the install's T3 home under sudo, unless one is set", () => {
171 const root = tempRoot();
172 writeExecutable(NodePath.join(root, "app"), REPORTER);
173 const shim = writeShim(root, {
174 kind: "direct",
175 executable: NodePath.join(root, "app"),
176 entry: "/bin.mjs",
177 });
178 expect(run(shim, []).stdout).toContain(`home=${root}/home`);
179 expect(run(shim, [], { T3CODE_HOME: "/elsewhere" }).stdout).toContain("home=/elsewhere");
180 const relative = NodeChildProcess.spawnSync("./bin/t3", [], { cwd: root, encoding: "utf8" });
181 expect(relative.stdout).toContain(`cli=${shim}`);
182 });
183
184 it("runs an installed app's server directly", () => {
185 const root = tempRoot();
186 const executable = NodePath.join(root, "opt", "T3 Code", "t3code");
187 writeExecutable(executable, REPORTER);
188 const shim = writeShim(root, {
189 kind: "direct",
190 executable,
191 entry: "/opt/T3's/app.asar/bin.mjs",
192 });
193 expect(run(shim, ["browser", "setup"]).stdout.split("\n").slice(1)).toEqual([
194 "/opt/T3's/app.asar/bin.mjs",
195 "browser",
196 "setup",
197 "",
198 ]);
199 });
200
201 it("writes a Windows launcher that keeps cmd from reinterpreting paths", () => {
202 const executable = "C:\\Apps\\R&whoami&X 100%\\!CHANNEL!\\T3 Code.exe";
203 const script = renderCliShim({
204 target: { kind: "windows", executable, entry: "C:\\Apps\\server.asar\\bin.mjs" },
205 shimPath: "C:\\Users\\José\\.t3\\bin\\t3.cmd",
206 t3Home: "C:\\Users\\José\\.t3",
207 });
208 const lines = script.split("\r\n");
209 expect(lines).toContain("setlocal EnableExtensions DisableDelayedExpansion");
210 expect(lines).toContain("chcp 65001 >nul");
211 expect(lines).toContain(
212 'if exist "C:\\Apps\\R&whoami&X 100%%\\!CHANNEL!\\T3 Code.exe" goto run',
213 );
214 const bare = lines.filter(
215 (line) => line.includes("whoami") && !/"[^"]*whoami[^"]*"/.test(line),
216 );
217 expect(bare).toEqual([]);
218 expect(lines).toContain('set "T3CODE_CLI_PATH=C:\\Users\\José\\.t3\\bin\\t3.cmd"');
219 });
220});