Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopCliShim.test.ts

222 lines8.6 KB

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 // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open.
57 // Trapped before the mount is announced, or the test's probe can arrive first and be lost.
58 "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT",
59 "trap 'echo mounted >&3 2>/dev/null' WINCH",
60 `echo $$ >'${root}/mounter.pid'`,
61 canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1',
62 "while :; do sleep 0.05; done",
63 "",
64 ].join("\n"),
65 );
66 const shim = writeShim(root, { kind: "appimage", appImage, executableName: "t3code" });
67 return { root, image, appImage, shim };
68};
69​
70// Stays up after a signal until the test lets it finish, like a server shutting down. A group
71// signal and the launcher's forwarded one can both arrive; a re-run trap would read stdin's EOF.
72const SLOW_SERVER = [
73 "#!/bin/sh",
74 'trap \'trap "" TERM HUP; echo stopping >&3; read go; echo "stopped $go" >&3; exit 7\' TERM HUP',
75 "echo ready",
76 "while :; do sleep 0.05; done",
77 "",
78].join("\n");
79​
80// The launcher mounts only under setsid, which stock macOS and Windows lack; there it extracts instead.
81const hasSetsid = NodeChildProcess.spawnSync("setsid", ["true"]).status === 0;
82​
83const lines = (stream: NodeJS.ReadableStream) => {
84 const seen: Array<string> = [];
85 const waiters: Array<() => void> = [];
86 let buffer = "";
87 stream.setEncoding("utf8");
88 stream.on("data", (chunk: string) => {
89 buffer += chunk;
90 const parts = buffer.split("\n");
91 buffer = parts.pop()!;
92 seen.push(...parts);
93 for (const wake of waiters.splice(0)) wake();
94 });
95 const until = async (match: (line: string) => boolean) => {
96 for (;;) {
97 const line = seen.find(match);
98 if (line !== undefined) return line;
99 await new Promise<void>((resolve) => waiters.push(resolve));
100 }
101 };
102 return { seen, until };
103};
104​
105describe("renderCliShim", () => {
106 // Ctrl-C, an SSH hangup, or a supervisor signals the process group. systemd's default KillMode
107 // also signals the mounter, and KillMode=mixed signals only the launcher.
108 it.skipIf(!hasSetsid).each([
109 ["SIGTERM", "the process group"],
110 ["SIGHUP", "the process group"],
111 ["SIGTERM", "every process"],
112 ["SIGTERM", "the launcher"],
113 ] as const)(
114 "keeps the AppImage mounted until the server exits after %s to %s",
115 async (signal, target) => {
116 const { root, shim } = fakeAppImage(true, SLOW_SERVER);
117 const child = NodeChildProcess.spawn(shim, [], {
118 detached: true,
119 env: { PATH: process.env.PATH },
120 stdio: ["pipe", "pipe", "ignore", "pipe"],
121 });
122 let mounter: number | undefined;
123 try {
124 const stdout = lines(child.stdout!);
125 const events = lines(child.stdio[3] as NodeJS.ReadableStream);
126 const exited = new Promise<number | null>((resolve) => child.on("close", resolve));
127 await stdout.until((line) => line === "ready");
128 mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8"));
129​
130 process.kill(target === "the launcher" ? child.pid! : -child.pid!, signal);
131 if (target === "every process") process.kill(mounter, signal);
132 // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and
133 // HUP, so a mounter that also got the group signal unmounts before it answers this probe.
134 process.kill(mounter, "SIGWINCH");
135 const mount = await events.until((line) => line === "mounted" || line === "unmounted");
136 expect(mount).toBe("mounted");
137​
138 await events.until((line) => line === "stopping");
139 child.stdin!.end("go\n");
140 expect(await exited).toBe(7);
141 expect(events.seen.slice(-2)).toEqual(["stopped go", "unmounted"]);
142 } finally {
143 for (const pid of [-child.pid!, mounter]) {
144 if (pid === undefined) continue;
145 try {
146 process.kill(pid, "SIGKILL");
147 } catch {}
148 }
149 }
150 },
151 );
152​
153 it("extracts the AppImage where it cannot be mounted", () => {
154 const { shim } = fakeAppImage(false);
155 const result = run(shim, ["--version"], { APPIMAGE_EXTRACT_AND_RUN: "1" });
156 expect(result.status).toBe(3);
157 expect(result.stdout).toMatch(
158 /squashfs-root\/resources\/app\.asar\/apps\/server\/dist\/bin\.mjs/,
159 );
160 });
161​
162 // The server skips its compile cache only under APPIMAGE; each mount path is new.
163 it("tells the CLI it runs from the mounted AppImage", () => {
164 const { appImage, shim } = fakeAppImage();
165 const result = run(shim, ["--version"]);
166 expect(result.status).toBe(3);
167 expect(result.stdout).toContain(`appimage=${appImage}`);
168 const closedStdin = NodeChildProcess.spawnSync("sh", ["-c", '"$0" --version <&-', shim]);
169 expect(closedStdin.status).toBe(3);
170 });
171​
172 it("keeps the install's T3 home under sudo, unless one is set", () => {
173 const root = tempRoot();
174 writeExecutable(NodePath.join(root, "app"), REPORTER);
175 const shim = writeShim(root, {
176 kind: "direct",
177 executable: NodePath.join(root, "app"),
178 entry: "/bin.mjs",
179 });
180 expect(run(shim, []).stdout).toContain(`home=${root}/home`);
181 expect(run(shim, [], { T3CODE_HOME: "/elsewhere" }).stdout).toContain("home=/elsewhere");
182 const relative = NodeChildProcess.spawnSync("./bin/t3", [], { cwd: root, encoding: "utf8" });
183 expect(relative.stdout).toContain(`cli=${shim}`);
184 });
185​
186 it("runs an installed app's server directly", () => {
187 const root = tempRoot();
188 const executable = NodePath.join(root, "opt", "T3 Code", "t3code");
189 writeExecutable(executable, REPORTER);
190 const shim = writeShim(root, {
191 kind: "direct",
192 executable,
193 entry: "/opt/T3's/app.asar/bin.mjs",
194 });
195 expect(run(shim, ["browser", "setup"]).stdout.split("\n").slice(1)).toEqual([
196 "/opt/T3's/app.asar/bin.mjs",
197 "browser",
198 "setup",
199 "",
200 ]);
201 });
202​
203 it("writes a Windows launcher that keeps cmd from reinterpreting paths", () => {
204 const executable = "C:\\Apps\\R&whoami&X 100%\\!CHANNEL!\\T3 Code.exe";
205 const script = renderCliShim({
206 target: { kind: "windows", executable, entry: "C:\\Apps\\server.asar\\bin.mjs" },
207 shimPath: "C:\\Users\\José\\.t3\\bin\\t3.cmd",
208 t3Home: "C:\\Users\\José\\.t3",
209 });
210 const lines = script.split("\r\n");
211 expect(lines).toContain("setlocal EnableExtensions DisableDelayedExpansion");
212 expect(lines).toContain("chcp 65001 >nul");
213 expect(lines).toContain(
214 'if exist "C:\\Apps\\R&whoami&X 100%%\\!CHANNEL!\\T3 Code.exe" goto run',
215 );
216 const bare = lines.filter(
217 (line) => line.includes("whoami") && !/"[^"]*whoami[^"]*"/.test(line),
218 );
219 expect(bare).toEqual([]);
220 expect(lines).toContain('set "T3CODE_CLI_PATH=C:\\Users\\José\\.t3\\bin\\t3.cmd"');
221 });
222});