@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 276 lines 11.1 KB
Raw
1 import { spawn } from "node:child_process";
2 import { describe, expect, it } from "@alchemy.run/test";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6 import * as ChildProcess from "effect/process/ChildProcess";
7 import * as Stream from "effect/Stream";
8 import { PlatformServices } from "@/Util/PlatformServices.ts";
9 import { nodePath, nodeSupportsDevMode } from "../nodeProbe.ts";
10
11 // Use the published bin layout but replace the entry with a real progress
12 // render, so startup is exercised without credentials or cloud resources.
13 const runPublishedLauncher = (nodeEnv: string | undefined, jsx?: string, runtime = "bun") =>
14 Effect.gen(function* () {
15 const fs = yield* FileSystem.FileSystem;
16 const path = yield* Path.Path;
17 const packageDir = yield* path.fromFileUrl(new URL("../../", import.meta.url));
18 const project = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-launcher-" });
19 const installed = path.join(project, "node_modules", "alchemy");
20 const bin = path.join(installed, "bin");
21 yield* fs.makeDirectory(bin, { recursive: true });
22 yield* fs.copyFile(path.join(packageDir, "bin", "cli.js"), path.join(bin, "cli.js"));
23 yield* fs.writeFileString(
24 path.join(installed, "package.json"),
25 JSON.stringify({ type: "module", bin: { alchemy: "./bin/cli.js" } }),
26 );
27 yield* fs.symlink(path.join(packageDir, "node_modules"), path.join(installed, "node_modules"));
28 yield* fs.makeDirectory(path.join(project, "node_modules", ".bin"));
29 yield* fs.symlink(
30 path.join(bin, "cli.js"),
31 path.join(project, "node_modules", ".bin", "alchemy"),
32 );
33 yield* fs.chmod(path.join(bin, "cli.js"), 0o755);
34 const fixture = new URL("./fixtures/launcher-production.tsx", import.meta.url).href;
35 yield* fs.writeFileString(
36 path.join(bin, "alchemy.js"),
37 `await import(${JSON.stringify(fixture)});\n`,
38 );
39 if (jsx !== undefined) {
40 yield* fs.writeFileString(
41 path.join(project, "tsconfig.json"),
42 JSON.stringify({
43 compilerOptions: { jsx, ...(jsx === "preserve" ? { jsxImportSource: "solid-js" } : {}) },
44 }),
45 );
46 }
47 const args = ["deploy", "stack.run.ts", "--stage", "test", "--yes"];
48 const handle = yield* ChildProcess.make(
49 runtime,
50 [...(runtime === "bun" ? ["--bun", "alchemy"] : [path.join(bin, "cli.js")]), ...args],
51 {
52 cwd: project,
53 env: {
54 NODE_ENV: nodeEnv,
55 CI: "true",
56 // Mirror `bun run`, which starts node-shebang bins under Node but
57 // points npm_execpath at bun.
58 npm_execpath: process.execPath,
59 npm_config_user_agent: `bun/${process.versions.bun}`,
60 BUN_OPTIONS: "",
61 BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0",
62 },
63 extendEnv: true,
64 stdin: "ignore",
65 stdout: "pipe",
66 stderr: "pipe",
67 forceKillAfter: "1 second",
68 },
69 );
70 const [stdout, stderr, exitCode] = yield* Effect.all(
71 [
72 handle.stdout.pipe(Stream.decodeText, Stream.mkString),
73 handle.stderr.pipe(Stream.decodeText, Stream.mkString),
74 handle.exitCode,
75 ],
76 { concurrency: 3 },
77 );
78 expect({ exitCode, stderr, failure: exitCode === 0 ? "" : stdout }).toEqual({
79 exitCode: 0,
80 stderr: "",
81 failure: "",
82 });
83 expect(stdout).toContain("Starting deployment");
84 expect(stdout).toContain("Deployment complete");
85 expect(stdout).toContain(JSON.stringify({ cwd: yield* fs.realPath(project), args }));
86 }).pipe(Effect.scoped, Effect.provide(PlatformServices));
87
88 // Run the published launcher under Node with a launcher's environment and
89 // report which runtime it picked. The entry and loader are stubs, and a fake
90 // `bun` first on PATH reports the handoff instead of running the CLI.
91 const launcherRuntime = (
92 env: { npm_execpath: string; npm_config_user_agent: string },
93 nodeArgs: ReadonlyArray<string> = [],
94 ) =>
95 Effect.gen(function* () {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const packageDir = yield* path.fromFileUrl(new URL("../../", import.meta.url));
99 const project = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-launcher-runtime-" });
100 const bin = path.join(project, "node_modules", "alchemy", "bin");
101 yield* fs.makeDirectory(bin, { recursive: true });
102 yield* fs.copyFile(path.join(packageDir, "bin", "cli.js"), path.join(bin, "cli.js"));
103 yield* fs.symlink(
104 path.join(packageDir, "node_modules"),
105 path.join(project, "node_modules", "alchemy", "node_modules"),
106 );
107 yield* fs.writeFileString(
108 path.join(project, "node_modules", "alchemy", "package.json"),
109 JSON.stringify({ type: "module" }),
110 );
111 yield* fs.writeFileString(path.join(bin, "register-oxc.js"), "");
112 yield* fs.writeFileString(path.join(bin, "alchemy.js"), `console.log("node");\n`);
113 const fakeBin = path.join(project, "fake-bin");
114 yield* fs.makeDirectory(fakeBin);
115 const fakeBun = path.join(fakeBin, "bun");
116 yield* fs.writeFileString(fakeBun, `#!/bin/sh\necho bun\n`);
117 yield* fs.chmod(fakeBun, 0o755);
118 const handle = yield* ChildProcess.make(nodePath!, [...nodeArgs, path.join(bin, "cli.js")], {
119 cwd: project,
120 env: {
121 ...env,
122 npm_execpath: env.npm_execpath.replace("<fake-bun>", fakeBun),
123 PATH: `${fakeBin}:${process.env.PATH ?? ""}`,
124 },
125 extendEnv: true,
126 stdin: "ignore",
127 stdout: "pipe",
128 stderr: "pipe",
129 forceKillAfter: "1 second",
130 });
131 const [stdout, stderr, exitCode] = yield* Effect.all(
132 [
133 handle.stdout.pipe(Stream.decodeText, Stream.mkString),
134 handle.stderr.pipe(Stream.decodeText, Stream.mkString),
135 handle.exitCode,
136 ],
137 { concurrency: 3 },
138 );
139 expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: "" });
140 return stdout.trim();
141 }).pipe(Effect.scoped, Effect.provide(PlatformServices));
142
143 // Environments captured from each launcher in #2000. The user agent names the
144 // package manager, so only npm_execpath may select bun.
145 const launchers = [
146 {
147 name: "nub exec in a bun project",
148 npm_execpath: "",
149 npm_config_user_agent: "bun/1.4.2 nub/0.9.6 node/v25.6.1 darwin arm64",
150 runtime: "node",
151 },
152 {
153 name: "nub run in a bun project",
154 npm_execpath: "/opt/homebrew/bin/nub",
155 npm_config_user_agent: "bun/1.4.2 nub/0.9.6 node/v25.6.1 darwin arm64",
156 runtime: "node",
157 },
158 {
159 name: "npx",
160 npm_execpath: "/usr/lib/node_modules/npm/bin/npm-cli.js",
161 npm_config_user_agent: "npm/11.9.0 node/v25.6.1 darwin arm64 workspaces/false",
162 runtime: "node",
163 },
164 {
165 // A directory named like bun (`/home/ubuntu/`) must not select bun.
166 name: "pnpm under /home/ubuntu",
167 npm_execpath: "/home/ubuntu/.local/share/pnpm/pnpm.cjs",
168 npm_config_user_agent: "pnpm/11.25.0 npm/? node/v24.0.0 linux x64",
169 runtime: "node",
170 },
171 {
172 name: "bun run / bunx",
173 npm_execpath: "<fake-bun>",
174 npm_config_user_agent: "bun/1.4.2 npm/? node/v26.3.0 darwin arm64",
175 runtime: "bun",
176 },
177 ] as const;
178
179 describe.sequential("launcher runtime selection", { tags: ["unit", "local"] }, () => {
180 for (const { name, runtime, ...env } of launchers) {
181 it.live.skipIf(!nodeSupportsDevMode)(`${name} runs the CLI under ${runtime}`, () =>
182 Effect.gen(function* () {
183 expect(yield* launcherRuntime(env)).toBe(runtime);
184 }),
185 );
186 }
187
188 it.live.skipIf(!nodeSupportsDevMode)(
189 "bun run hands off through a child when this Node has no execve",
190 () =>
191 Effect.gen(function* () {
192 const { runtime: _runtime, name: _name, ...env } = launchers[4];
193 const withoutExecve = "data:text/javascript,delete process.execve;";
194 expect(yield* launcherRuntime(env, ["--import", withoutExecve])).toBe("bun");
195 }),
196 );
197
198 it.live.skipIf(!nodeSupportsDevMode)(
199 "bun run keeps a parent's IPC channel across the handoff",
200 () => launcherRelaysIpc(),
201 );
202 });
203
204 // The launcher, forked with an IPC channel the way a supervisor would, must
205 // still deliver the CLI's messages both ways: `execve` would sever the channel,
206 // so this path keeps a child and relays. Node's IPC has no Effect surface, so
207 // the process is driven with `node:child_process` directly.
208 const launcherRelaysIpc = () =>
209 Effect.gen(function* () {
210 const fs = yield* FileSystem.FileSystem;
211 const path = yield* Path.Path;
212 const packageDir = yield* path.fromFileUrl(new URL("../../", import.meta.url));
213 const project = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-launcher-ipc-" });
214 const bin = path.join(project, "node_modules", "alchemy", "bin");
215 yield* fs.makeDirectory(bin, { recursive: true });
216 yield* fs.copyFile(path.join(packageDir, "bin", "cli.js"), path.join(bin, "cli.js"));
217 yield* fs.symlink(
218 path.join(packageDir, "node_modules"),
219 path.join(project, "node_modules", "alchemy", "node_modules"),
220 );
221 yield* fs.writeFileString(
222 path.join(project, "node_modules", "alchemy", "package.json"),
223 JSON.stringify({ type: "module" }),
224 );
225 // The CLI entry, as bun would run it: announce readiness over IPC, then
226 // echo the one message the parent sends and exit.
227 yield* fs.writeFileString(
228 path.join(bin, "alchemy.js"),
229 [
230 "process.send({ ready: true, args: process.argv.slice(2) });",
231 'process.once("message", (message) => {',
232 " process.send({ echo: message });",
233 " process.exit(7);",
234 "});",
235 ].join("\n"),
236 );
237 const fakeBun = path.join(project, "bun");
238 yield* fs.writeFileString(fakeBun, `#!/bin/sh\nexec ${JSON.stringify(nodePath!)} "$@"\n`);
239 yield* fs.chmod(fakeBun, 0o755);
240
241 const result = yield* Effect.promise(
242 () =>
243 new Promise<{ messages: Array<unknown>; exitCode: number | null }>((resolve, reject) => {
244 const child = spawn(nodePath!, [path.join(bin, "cli.js"), "deploy", "--yes"], {
245 cwd: project,
246 env: { ...process.env, npm_execpath: fakeBun, npm_config_user_agent: "bun/1.4.2" },
247 stdio: ["ignore", "ignore", "inherit", "ipc"],
248 });
249 const messages: Array<unknown> = [];
250 child.on("message", (message) => {
251 messages.push(message);
252 if (messages.length === 1) child.send({ hello: "cli" });
253 });
254 child.on("error", reject);
255 child.on("close", (exitCode) => resolve({ messages, exitCode }));
256 }),
257 );
258 expect(result).toEqual({
259 messages: [{ ready: true, args: ["deploy", "--yes"] }, { echo: { hello: "cli" } }],
260 exitCode: 7,
261 });
262 }).pipe(Effect.scoped, Effect.provide(PlatformServices));
263
264 describe.sequential("published Bun launcher", { tags: ["unit", "local"] }, () => {
265 it.live.skipIf(!nodeSupportsDevMode)(
266 "renders production progress through the Node shebang handoff",
267 () => runPublishedLauncher("development", "preserve", nodePath!),
268 );
269 for (const nodeEnv of [undefined, "development", "production"]) {
270 for (const jsx of [undefined, "react-jsx", "react-jsxdev", "preserve"]) {
271 it.live(`renders production progress with NODE_ENV=${nodeEnv} and jsx=${jsx}`, () =>
272 runPublishedLauncher(nodeEnv, jsx),
273 );
274 }
275 }
276 });