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

main
ts 75 lines 2.91 KB
Raw
1 import { expect, test } from "bun:test";
2 import { spawn } from "node:child_process";
3 import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join, resolve } from "node:path";
6 import { pollUntil } from "../src/DevCli.ts";
7
8 for (const signal of ["SIGINT", "SIGTERM"] as const) {
9 test(`forwards ${signal} to DevCli and waits for cleanup`, async () => {
10 const root = mkdtempSync(join(tmpdir(), "alchemy-forward-signals-"));
11 const devCli = resolve(import.meta.dirname, "../src/DevCli.ts");
12 writeFileSync(
13 join(root, "cli.ts"),
14 `
15 import { writeFileSync } from "node:fs";
16 process.on(${JSON.stringify(signal)}, () => {
17 setTimeout(() => { writeFileSync("cleaned", "yes"); process.exit(0); }, 200);
18 });
19 writeFileSync("child.pid", String(process.pid));
20 setInterval(() => {}, 1000);
21 `,
22 );
23 writeFileSync(
24 join(root, "owner.test.ts"),
25 `
26 import { afterAll, test } from "bun:test";
27 import { writeFileSync } from "node:fs";
28 import { DevCli } from ${JSON.stringify(devCli)};
29 const cli = new DevCli({ root: process.cwd(), alchemyBin: process.cwd() + "/cli.ts" });
30 afterAll(async () => { writeFileSync("afterAll", "yes"); await cli.stop(); });
31 test("running", async () => { cli.start(); await Bun.sleep(60000); }, 65000);
32 `,
33 );
34 const runner = spawn(process.execPath, ["test", "owner.test.ts"], {
35 cwd: root,
36 detached: true,
37 stdio: "ignore",
38 env: { ...process.env, ALCHEMY_PROFILE: "alchemy" },
39 });
40 const exited = new Promise<number | null>((resolve, reject) => {
41 runner.once("exit", resolve);
42 runner.once("error", reject);
43 });
44 const timeout = setTimeout(() => runner.kill("SIGKILL"), 6000);
45 let childPid: number | undefined;
46 try {
47 await pollUntil(
48 "CLI started",
49 () => (existsSync(join(root, "child.pid")) ? true : undefined),
50 { tries: 80, delayMs: 50 },
51 );
52 childPid = Number(readFileSync(join(root, "child.pid"), "utf8"));
53 process.kill(-runner.pid!, signal);
54 // A launcher can forward the same terminal signal more than once.
55 await Bun.sleep(50);
56 process.kill(-runner.pid!, signal);
57 expect(await exited).toBe(signal === "SIGINT" ? 130 : 143);
58 expect(existsSync(join(root, "cleaned"))).toBe(true);
59 expect(existsSync(join(root, "afterAll"))).toBe(false);
60 expect(() => process.kill(childPid!, 0)).toThrow();
61 } finally {
62 clearTimeout(timeout);
63 runner.kill("SIGKILL");
64 if (childPid !== undefined) {
65 try {
66 process.kill(childPid, "SIGKILL");
67 } catch (error) {
68 // oxlint-disable-next-line no-unsafe-finally, TODO: fix
69 if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
70 }
71 }
72 rmSync(root, { recursive: true, force: true });
73 }
74 }, 10000);
75 }