@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, 04:45 UTC

main
ts 161 lines 5.57 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import { assert, describe, expect, it } from "@alchemy.run/test";
3 import { PlatformServices } from "alchemy/Util/PlatformServices";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as ChildProcess from "effect/process/ChildProcess";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import {
10 assertPidExited,
11 killPid,
12 pidListeningOn,
13 waitForExit,
14 } from "./fixtures/process-effect.ts";
15
16 const FIXTURE_DIR = fileURLToPath(new URL("./fixtures/dev-cli/", import.meta.url));
17 const ALCHEMY_BIN = fileURLToPath(new URL("../../../alchemy/bin/alchemy.js", import.meta.url));
18
19 /** Every live pid on the system with its parent and command (POSIX). */
20 const processTable = ChildProcess.make("ps", ["-Ao", "pid=,ppid=,comm="], {
21 stdout: "pipe",
22 }).pipe(
23 Effect.flatMap((handle) => handle.stdout.pipe(Stream.decodeText, Stream.mkString)),
24 Effect.map((stdout) =>
25 stdout.split("\n").flatMap((line) => {
26 const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
27 return match
28 ? [
29 {
30 pid: Number(match[1]),
31 ppid: Number(match[2]),
32 command: match[3]!,
33 },
34 ]
35 : [];
36 }),
37 ),
38 );
39
40 /** Transitive children of `root`, resolved to a fixpoint over the table. */
41 const descendantsOf = (root: number) =>
42 processTable.pipe(
43 Effect.map((table) => {
44 const pids = new Set([root]);
45 let grew = true;
46 while (grew) {
47 grew = false;
48 for (const entry of table) {
49 if (pids.has(entry.ppid) && !pids.has(entry.pid)) {
50 pids.add(entry.pid);
51 grew = true;
52 }
53 }
54 }
55 return table.filter((entry) => entry.pid !== root && pids.has(entry.pid));
56 }),
57 );
58
59 describe.skipIf(process.platform === "win32" || process.env.FAST)(
60 "alchemy dev CLI process cleanup",
61 { tags: ["local"] },
62 () => {
63 // Expected failure: SIGKILL cannot be trapped, so nothing kills the
64 // exec child, the provider sidecar, or workerd on the CLI's behalf.
65 // When the orphan story lands this starts passing — flip it to a
66 // regular test then.
67 it.live.fails(
68 "every spawned process exits after the CLI is SIGKILLed",
69 () =>
70 Effect.gen(function* () {
71 let output = "";
72 const child = yield* ChildProcess.make(
73 "bun",
74 [ALCHEMY_BIN, "dev", "alchemy.run.ts", "--stage", "kill-test"],
75 {
76 cwd: FIXTURE_DIR,
77 stdout: "pipe",
78 stderr: "pipe",
79 forceKillAfter: "1 second",
80 // The stack is fully local (localState + local worker), so
81 // placeholder credentials satisfy the provider's env lookup
82 // without any cloud call being possible.
83 env: {
84 CI: "1",
85 CLOUDFLARE_ACCOUNT_ID: "0123456789abcdef0123456789abcdef",
86 CLOUDFLARE_API_TOKEN: "dev-cli-kill-test-placeholder",
87 },
88 extendEnv: true,
89 },
90 );
91 const collect = (stream: typeof child.stdout) =>
92 stream.pipe(
93 Stream.decodeText,
94 Stream.runForEach((chunk) =>
95 Effect.sync(() => {
96 output += chunk;
97 }),
98 ),
99 Effect.ignore,
100 Effect.forkScoped,
101 );
102 yield* collect(child.stdout);
103 yield* collect(child.stderr);
104
105 // The stack outputs print once the dev deploy has converged and
106 // workerd is serving the local worker.
107 const match = yield* Effect.sync(
108 () => output.match(/workerUrl[^h]*(http[^\s'",]+)/)?.[1],
109 ).pipe(
110 Effect.repeat({
111 schedule: Schedule.spaced("500 millis"),
112 until: (value) => value !== undefined,
113 times: 240,
114 }),
115 );
116 if (typeof match !== "string") {
117 return yield* Effect.die(
118 new Error(
119 `alchemy dev never printed the worker url.\n--- output tail ---\n${output.slice(-4_000)}`,
120 ),
121 );
122 }
123 const url = match;
124 yield* Effect.tryPromise(() => fetch(url)).pipe(
125 Effect.retry({
126 schedule: Schedule.spaced("500 millis"),
127 times: 40,
128 }),
129 );
130
131 const workerdPid = yield* pidListeningOn(url);
132 const tracked = yield* descendantsOf(child.pid);
133 assert(
134 tracked.some((entry) => entry.pid === workerdPid),
135 `workerd (pid ${workerdPid}) is not a descendant of the CLI:\n${JSON.stringify(tracked, null, 2)}`,
136 );
137 // Reap survivors unconditionally so the expected failure never
138 // leaks processes into the rest of the suite.
139 yield* Effect.addFinalizer(() =>
140 Effect.forEach(tracked, (entry) => killPid(entry.pid, "SIGKILL")).pipe(Effect.asVoid),
141 );
142
143 yield* killPid(child.pid, "SIGKILL");
144 yield* waitForExit(child, Duration.seconds(10));
145
146 const survivors: string[] = [];
147 yield* Effect.forEach(tracked, (entry) =>
148 assertPidExited(entry.pid).pipe(
149 Effect.catch(() =>
150 Effect.sync(() => {
151 survivors.push(`${entry.pid} ${entry.command}`);
152 }),
153 ),
154 ),
155 );
156 expect(survivors).toEqual([]);
157 }).pipe(Effect.provide(PlatformServices)),
158 { timeout: 180_000 },
159 );
160 },
161 );