@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 204 lines 9.08 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off processEnvInEffect:off - fixtures need real paths, the process resource list and the live environment.
2 import * as NodeOS from "node:os";
3 import * as NodePath from "node:path";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { describe, expect, it } from "@effect/vitest";
6 import { vi } from "vite-plus/test";
7 import * as Deferred from "effect/Deferred";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 import * as Layer from "effect/Layer";
11 import * as Result from "effect/Result";
12 import * as Stream from "effect/Stream";
13 import * as ChildProcess from "effect/process/ChildProcess";
14 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15 import * as HostProcess from "@t3tools/shared/HostProcess";
16
17 import * as SpawnWorker from "./SpawnWorker.ts";
18
19 const envChdir = vi.hoisted(() => ({ supported: true }));
20 vi.mock("@t3tools/shared/envTrampoline", async (importOriginal) => ({
21 ...(await importOriginal<typeof import("@t3tools/shared/envTrampoline")>()),
22 supportsEnvChdir: () => Promise.resolve(envChdir.supported),
23 }));
24
25 const layer = SpawnWorker.layer.pipe(Layer.provide(NodeServices.layer));
26 const text = <E>(stream: Stream.Stream<Uint8Array, E>) =>
27 stream.pipe(Stream.decodeText(), Stream.mkString);
28 const node = (script: string, args: ReadonlyArray<string> = [], options = {}) =>
29 ChildProcess.make(process.execPath, ["-e", script, ...args], options);
30
31 describe("SpawnWorker", () => {
32 it.live("runs children on a launcher thread where the server thread would wait on them", () =>
33 Effect.gen(function* () {
34 for (const [platform, hasEnvChdir, onServerThread] of [
35 ["win32", true, false],
36 ["linux", true, true],
37 ["linux", false, false],
38 ] as const) {
39 envChdir.supported = hasEnvChdir;
40 const launched = Effect.gen(function* () {
41 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
42 const child = yield* spawner.spawn(
43 node("process.stdout.write('ready');process.stdin.resume()"),
44 );
45 expect(yield* child.stdout.pipe(Stream.take(1), text)).toBe("ready");
46 // The thread that called spawn owns the native process handle.
47 expect(process.getActiveResourcesInfo().includes("ProcessWrap")).toBe(onServerThread);
48 expect(yield* child.isRunning).toBe(true);
49 });
50 yield* launched.pipe(
51 Effect.scoped,
52 Effect.provide(SpawnWorker.layerServer.pipe(Layer.provide(NodeServices.layer))),
53 Effect.provideService(HostProcess.Platform, platform),
54 );
55 }
56 }),
57 );
58
59 it.live("preserves stdin, large output, env, cwd, literal args and additional descriptors", () =>
60 Effect.gen(function* () {
61 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
62 const literal = "quote' \" $HOME; * & %PATH%";
63 const cwd = NodeOS.tmpdir();
64 const script = `
65 const fs = require('node:fs');
66 const input = fs.readFileSync(0, 'utf8');
67 fs.writeSync(1, JSON.stringify([input, process.cwd(), process.env.SPAWN_WORKER_TEST, process.argv[1]]) + '\\n');
68 fs.writeSync(1, 'a'.repeat(1024 * 1024));
69 fs.writeSync(2, 'b'.repeat(1024 * 1024));
70 `;
71 for (let i = 0; i < 3; i++) {
72 const child = yield* spawner.spawn(
73 node(script, [literal], {
74 cwd,
75 env: { SPAWN_WORKER_TEST: "inherited value" },
76 extendEnv: true,
77 stdin: Stream.encodeText(Stream.make("stdin value")),
78 }),
79 );
80 const [stdout, stderr, code] = yield* Effect.all(
81 [text(child.stdout), text(child.stderr), child.exitCode],
82 { concurrency: "unbounded" },
83 );
84 expect(stdout).toBe(
85 JSON.stringify(["stdin value", NodePath.resolve(cwd), "inherited value", literal]) +
86 "\n" +
87 "a".repeat(1024 * 1024),
88 );
89 expect(stderr).toBe("b".repeat(1024 * 1024));
90 expect(code).toBe(0);
91 }
92 // The launcher threads already exist, so this needs the server's environment at launch time.
93 process.env.SPAWN_WORKER_LATE = "set after start";
94 const late = yield* spawner.spawn(
95 node("process.stdout.write(process.env.SPAWN_WORKER_LATE)"),
96 );
97 expect(yield* text(late.stdout)).toBe("set after start");
98 delete process.env.SPAWN_WORKER_LATE;
99 const extra = yield* spawner.spawn(
100 node("require('node:fs').writeSync(3, 'fd3 value')", [], {
101 additionalFds: { fd3: { type: "output" } },
102 }),
103 );
104 const [fd3, extraCode] = yield* Effect.all([text(extra.getOutputFd(3)), extra.exitCode], {
105 concurrency: "unbounded",
106 });
107 expect(fd3).toBe("fd3 value");
108 expect(extraCode).toBe(0);
109 const reader = yield* spawner.spawn(
110 node("process.stdin.on('end', () => process.stdout.write('eof')).resume()"),
111 );
112 yield* Stream.fail("abandoned input").pipe(Stream.run(reader.stdin), Effect.ignore);
113 expect(yield* text(reader.stdout)).toBe("eof");
114 const pipeline = node("process.stdout.write('piped')").pipe(
115 ChildProcess.pipeTo(
116 node("process.stdin.on('data', (d) => process.stdout.write(String(d).toUpperCase()))"),
117 ),
118 );
119 const piped = yield* spawner.spawn(pipeline);
120 expect(yield* text(piped.stdout)).toBe("PIPED");
121 expect(yield* piped.exitCode).toBe(0);
122 }).pipe(Effect.scoped, Effect.provide(layer)),
123 );
124
125 it.live("reports launch errors and exit codes, and keeps launching after either", () =>
126 Effect.gen(function* () {
127 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
128 const missing = yield* spawner
129 .spawn(ChildProcess.make("t3-missing-command-25245"))
130 .pipe(Effect.result);
131 expect(Result.isFailure(missing)).toBe(true);
132 if (Result.isFailure(missing)) expect(missing.failure.reason._tag).toBe("NotFound");
133 const failed = yield* spawner.spawn(node("process.exit(23)"));
134 expect(yield* failed.exitCode).toBe(23);
135 const healthy = yield* spawner.spawn(node("process.stdout.write('ok')"));
136 expect(yield* text(healthy.stdout)).toBe("ok");
137 expect(yield* healthy.exitCode).toBe(0);
138 }).pipe(Effect.scoped, Effect.provide(layer)),
139 );
140
141 it.live("a short child's output ends while a sibling launched beside it still runs", () =>
142 Effect.gen(function* () {
143 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
144 const untilStdin =
145 "process.stdout.write('ready');process.stdin.once('data',()=>process.exit(0))";
146 // Workers that own a child stay alive, as beside a running agent, so each round's two
147 // launches land on two warm workers at once.
148 yield* Effect.all(
149 Array.from({ length: 4 }, () =>
150 Effect.gen(function* () {
151 const holder = yield* spawner.spawn(node(untilStdin));
152 expect(yield* holder.stdout.pipe(Stream.take(1), text)).toBe("ready");
153 }),
154 ),
155 { concurrency: "unbounded" },
156 );
157 for (let round = 0; round < 20; round++) {
158 const [sibling, output] = yield* Effect.all(
159 [
160 spawner.spawn(node(untilStdin, [], { stdin: { stream: Stream.never } })),
161 spawner
162 .spawn(node("process.stdout.write('ok')"))
163 .pipe(Effect.flatMap((child) => text(child.stdout))),
164 ],
165 { concurrency: "unbounded" },
166 );
167 expect(output).toBe("ok");
168 expect(yield* sibling.isRunning).toBe(true);
169 }
170 }).pipe(Effect.scoped, Effect.provide(layer)),
171 );
172
173 it.live("kills running commands, detached or not, and on scope interruption", () =>
174 Effect.gen(function* () {
175 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
176 for (const detached of [true, false]) {
177 const child = yield* spawner.spawn(
178 node("process.stdout.write(String(process.pid));process.stdin.resume()", [], {
179 detached,
180 }),
181 );
182 const pid = yield* child.stdout.pipe(Stream.take(1), text);
183 expect(Number(pid)).toBe(child.pid);
184 yield* child.kill();
185 expect(yield* child.isRunning).toBe(false);
186 }
187 const started = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
188 const running = yield* Effect.gen(function* () {
189 const scoped = yield* spawner.spawn(node("process.stdin.resume()"));
190 yield* Deferred.succeed(started, scoped);
191 return yield* Effect.never;
192 }).pipe(Effect.scoped, Effect.forkChild);
193 const scoped = yield* Deferred.await(started);
194 yield* Fiber.interrupt(running);
195 expect(yield* scoped.isRunning).toBe(false);
196 // Direct callers such as the Claude adapter pass an AbortSignal, which cannot cross to a worker.
197 const direct = SpawnWorker.spawnPiped(process.execPath, ["-e", "process.stdin.resume()"], {
198 signal: AbortSignal.abort(),
199 });
200 const exited = new Promise((resolve) => direct.once("exit", () => resolve(direct.killed)));
201 expect(yield* Effect.promise(() => exited)).toBe(true);
202 }).pipe(Effect.scoped, Effect.provide(layer)),
203 );
204 });