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

DesktopCliShim.test.ts

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