@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 363 lines 14.5 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import { newWebSocketRpcSession, type RpcStub } from "capnweb";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Fiber from "effect/Fiber";
6 import * as FetchHttpClient from "effect/http/FetchHttpClient";
7 import * as HttpBody from "effect/http/HttpBody";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Layer from "effect/Layer";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { unwrapRpcHandlers } from "@/Local/RpcSerialization.ts";
14 import type { RpcProxyApi } from "@/Local/RpcServer.ts";
15 import { encodeSessionEnvironment, SESSION_ENV_PARAM } from "@/Local/RpcServerEnvironment.ts";
16 import {
17 layerServer,
18 RpcSpawner,
19 LOGS_PATH,
20 parseSidecarLogLine,
21 type RpcSpawnPayload,
22 } from "@/Local/RpcSpawner.ts";
23 import { PlatformServices } from "@/Util/PlatformServices.ts";
24 import {
25 assertPidExited,
26 canOpenWebSocket,
27 isAlive,
28 openWebSocket,
29 pgidOf,
30 pidListeningOn,
31 } from "./fixtures/process-effect.ts";
32 import type { EchoClient } from "./fixtures/rpc-echo.ts";
33
34 const FIXTURE_TS_URL = new URL("./fixtures/rpc-server-entry.ts", import.meta.url).toString();
35 const FIXTURE_B_TS_URL = new URL("./fixtures/rpc-server-entry-b.ts", import.meta.url).toString();
36 const CRASH_FIXTURE_TS_URL = new URL("./fixtures/rpc-server-crash.ts", import.meta.url).toString();
37 const LOGS_FIXTURE_TS_URL = new URL("./fixtures/rpc-server-logs.ts", import.meta.url).toString();
38
39 const samplePayload = (serverEntryUrl: string): RpcSpawnPayload => ({ serverEntryUrl });
40
41 // The spawner inherits the runtime that vitest itself is running under
42 // (it shells out to `bun` or `node` based on `typeof Bun`). These tests
43 // only verify behavior for the active runtime; run vitest under both to
44 // get full coverage.
45 describe(
46 `Local.RpcSpawner (runtime=${typeof globalThis.Bun !== "undefined" ? "bun" : "node"})`,
47 { tags: ["local"] },
48 () => {
49 /**
50 * The Spawner layer (and any child processes it spawns) is torn down
51 * when the surrounding test scope closes, so we provide it at the test
52 * boundary rather than wrapping a sub-effect — that would tear the
53 * server down the moment the sub-effect returned.
54 */
55 const services = Layer.provideMerge(
56 layerServer({ profile: undefined, envFile: undefined }),
57 Layer.merge(PlatformServices, FetchHttpClient.layer),
58 );
59
60 it.live(
61 "POST returns a ws url whose RPC end-to-end call hits the fixture",
62 () =>
63 Effect.gen(function* () {
64 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
65 const wsUrl = yield* post(url, samplePayload(FIXTURE_TS_URL));
66 expect(wsUrl).toMatch(/^ws:\/\//);
67 const result = yield* echoWebSocket(wsUrl, "hello");
68 expect(result).toBe("echo:hello");
69 }).pipe(Effect.provide(services)),
70 { timeout: 60_000 },
71 );
72
73 it.live(
74 "omitEnv withholds matching env vars from the sidecar",
75 () =>
76 Effect.acquireUseRelease(
77 Effect.sync(() => {
78 process.env.ALCHEMY_TEST_OMITTED_SECRET = "omitted";
79 process.env.ALCHEMY_TEST_KEPT_VALUE = "kept";
80 }),
81 () =>
82 Effect.gen(function* () {
83 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
84 const wsUrl = yield* post(url, samplePayload(FIXTURE_TS_URL));
85 const env = yield* sidecarEnv(wsUrl, [
86 "ALCHEMY_TEST_OMITTED_SECRET",
87 "ALCHEMY_TEST_KEPT_VALUE",
88 ]);
89 expect(env).toEqual([undefined, "kept"]);
90 }).pipe(
91 Effect.provide(
92 Layer.provideMerge(
93 layerServer({
94 profile: undefined,
95 envFile: undefined,
96 omitEnv: ["ALCHEMY_TEST_OMITTED_"],
97 }),
98 Layer.merge(PlatformServices, FetchHttpClient.layer),
99 ),
100 ),
101 ),
102 () =>
103 Effect.sync(() => {
104 delete process.env.ALCHEMY_TEST_OMITTED_SECRET;
105 delete process.env.ALCHEMY_TEST_KEPT_VALUE;
106 }),
107 ),
108 // sets process-global env vars the sidecar inherits at spawn
109 { timeout: 60_000, exclusive: true },
110 );
111
112 it.live(
113 "rejects malformed spawn payloads and non-file URLs",
114 () =>
115 Effect.gen(function* () {
116 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
117 for (const payload of [
118 {},
119 { serverEntryUrl: 42 },
120 { serverEntryUrl: "not a url" },
121 { serverEntryUrl: "https://example.com/server.ts" },
122 ]) {
123 const response = yield* postRaw(url, payload);
124 expect(response.status).toBe(400);
125 }
126 }).pipe(Effect.provide(services)),
127 { timeout: 60_000 },
128 );
129
130 it(
131 "client parser ignores heartbeat frames",
132 () => {
133 expect(parseSidecarLogLine('{"channel":"heartbeat"}')).toBeUndefined();
134 },
135 { tags: ["unit"] },
136 );
137
138 it.live(
139 "emits a heartbeat immediately and periodically",
140 () =>
141 Effect.gen(function* () {
142 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
143 const client = yield* HttpClient.HttpClient;
144 const response = yield* client.get(new URL(LOGS_PATH, url).toString());
145 const frames = yield* response.stream.pipe(
146 Stream.decodeText,
147 Stream.splitLines,
148 Stream.map((line) => JSON.parse(line) as { channel: string }),
149 Stream.filter(({ channel }) => channel === "heartbeat"),
150 Stream.take(2),
151 Stream.runCollect,
152 Effect.timeout(Duration.seconds(7)),
153 );
154 expect(Array.from(frames)).toEqual([{ channel: "heartbeat" }, { channel: "heartbeat" }]);
155 }).pipe(Effect.provide(services)),
156 { timeout: 10_000 },
157 );
158
159 it.live(
160 "caches the child by entry url: a second POST returns the same url",
161 () =>
162 Effect.gen(function* () {
163 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
164 const payload = samplePayload(FIXTURE_TS_URL);
165 const first = yield* post(url, payload);
166 const second = yield* post(url, payload);
167 expect(second).toBe(first);
168 const pid = yield* pidListeningOn(first);
169 if (pid !== undefined) {
170 expect(yield* isAlive(pid)).toBe(true);
171 }
172 }).pipe(Effect.provide(services)),
173 { timeout: 60_000 },
174 );
175
176 it.live(
177 "distinct entry urls spawn distinct children with distinct urls",
178 () =>
179 Effect.gen(function* () {
180 // Children are keyed by serverEntryUrl ONLY — stacks share one child
181 // (each RPC session carries its own stack environment), so the second
182 // fixture must be a genuinely different entry module.
183 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
184 const a = yield* post(url, samplePayload(FIXTURE_TS_URL));
185 const b = yield* post(url, samplePayload(FIXTURE_B_TS_URL));
186 expect(a).not.toBe(b);
187 }).pipe(Effect.provide(services)),
188 { timeout: 60_000 },
189 );
190
191 it.live(
192 "sidecars lead their own process group (a terminal Ctrl+C cannot reach them)",
193 () =>
194 Effect.gen(function* () {
195 // POSIX-only: Windows has no process groups; the spawner leaves
196 // sidecars attached there (detached console children have their own
197 // quirks) and Ctrl+C delivery works differently anyway.
198 if (process.platform === "win32") return;
199 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
200 const wsUrl = yield* post(url, samplePayload(FIXTURE_TS_URL));
201 const pid = yield* pidListeningOn(wsUrl);
202 if (pid === undefined || Number.isNaN(pid)) return;
203 // Group leader (pgid === pid) proves the sidecar was spawned
204 // detached: the tty's foreground-group signals stop at this process.
205 expect(yield* pgidOf(pid)).toBe(pid);
206 }).pipe(Effect.provide(services)),
207 { timeout: 60_000 },
208 );
209
210 it.live(
211 "closing the spawner's scope kills all spawned children",
212 () =>
213 Effect.gen(function* () {
214 // Boot the spawner in an inner scope so we can close it while
215 // the outer test scope is still alive, then assert against the
216 // pid we recorded.
217 const pid = yield* Effect.gen(function* () {
218 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
219 const wsUrl = yield* post(url, samplePayload(FIXTURE_TS_URL));
220 return yield* pidListeningOn(wsUrl);
221 }).pipe(Effect.provide(services), Effect.scoped);
222
223 if (pid === undefined) return;
224 yield* assertPidExited(pid);
225 }),
226 { timeout: 60_000 },
227 );
228
229 it.live(
230 "url returned for a crash-on-boot fixture is not a usable RPC endpoint",
231 () =>
232 Effect.gen(function* () {
233 // The crash fixture prints the address marker then exits. The
234 // spawner's health check is best-effort: depending on race
235 // timing the POST may return a bogus url, or surface a 500
236 // once the retry budget drains. The invariant we *can*
237 // assert is that callers cannot open a parent websocket to
238 // the returned url.
239 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
240 yield* Effect.gen(function* () {
241 const r = yield* postRaw(url, samplePayload(CRASH_FIXTURE_TS_URL));
242 if (r.status !== 200) {
243 return { unusable: true } as const;
244 }
245 const usable = yield* canOpenWebSocket(new URL("/parent", r.body));
246 return { unusable: !usable } as const;
247 }).pipe(
248 Effect.flatMap((r) =>
249 r.unusable ? Effect.void : Effect.fail(new Error("endpoint was still usable")),
250 ),
251 // Mirrors the original `for (let i = 0; i < 4 && !failed; i++)`
252 // loop: up to 4 retries spaced 250ms apart.
253 Effect.retry({ schedule: Schedule.spaced(Duration.millis(250)), times: 4 }),
254 );
255 }).pipe(Effect.provide(services)),
256 { timeout: 60_000 },
257 );
258
259 it.live(
260 "a /logs subscriber receives sidecar stdout and stderr as ndjson",
261 () =>
262 Effect.gen(function* () {
263 const url = yield* RpcSpawner.useSync((spawner) => spawner.url);
264 const client = yield* HttpClient.HttpClient;
265
266 // Subscribe BEFORE spawning (headers received = subscription
267 // registered server-side) — with a subscriber connected, the
268 // spawner must route sidecar output here instead of its console.
269 const response = yield* client.get(new URL(LOGS_PATH, url).toString());
270 const collector = yield* response.stream.pipe(
271 Stream.decodeText,
272 Stream.splitLines,
273 Stream.map((line) => JSON.parse(line) as { channel: string; line?: string }),
274 // drop heartbeats (no `line`) and any non-fixture noise
275 Stream.filter(
276 (entry): entry is { channel: string; line: string } =>
277 entry.line?.startsWith("fixture-") ?? false,
278 ),
279 Stream.take(6),
280 Stream.runCollect,
281 Effect.forkScoped,
282 );
283
284 const wsUrl = yield* post(url, samplePayload(LOGS_FIXTURE_TS_URL));
285 expect(wsUrl).toMatch(/^ws:\/\//);
286
287 const received = Array.from(
288 yield* Fiber.join(collector).pipe(Effect.timeout(Duration.seconds(20))),
289 );
290 const channels = new Set(received.map((entry) => entry.channel));
291 expect(received.every((entry) => entry.line.startsWith("fixture-"))).toBe(true);
292 expect(channels.has("stdout")).toBe(true);
293 expect(channels.has("stderr")).toBe(true);
294 }).pipe(Effect.provide(services)),
295 { timeout: 60_000 },
296 );
297 },
298 );
299
300 interface PostResult {
301 readonly status: number;
302 readonly body: string;
303 }
304
305 const postRaw = (
306 url: string,
307 body: unknown,
308 ): Effect.Effect<PostResult, never, HttpClient.HttpClient> =>
309 Effect.gen(function* () {
310 const client = yield* HttpClient.HttpClient;
311 const req = HttpClientRequest.post(url).pipe(
312 HttpClientRequest.setBody(HttpBody.text(JSON.stringify(body), "application/json")),
313 );
314 const res = yield* client.execute(req);
315 const text = yield* res.text;
316 return { status: res.status, body: text };
317 }).pipe(Effect.orDie);
318
319 const post = (url: string, body: unknown): Effect.Effect<string, Error, HttpClient.HttpClient> =>
320 postRaw(url, body).pipe(
321 Effect.flatMap((r) =>
322 r.status === 200
323 ? Effect.succeed(r.body)
324 : Effect.fail(new Error(`spawn POST failed: ${r.status} ${r.body}`)),
325 ),
326 );
327
328 const echoWebSocket = (rpcUrl: string, msg: string): Effect.Effect<string, Error> =>
329 withEchoHandlers(rpcUrl, (handlers) => handlers.echo(msg));
330
331 /** Read env vars as the sidecar process sees them. */
332 const sidecarEnv = (
333 rpcUrl: string,
334 keys: ReadonlyArray<string>,
335 ): Effect.Effect<Array<string | undefined>, Error> =>
336 withEchoHandlers(rpcUrl, (handlers) => Effect.forEach(keys, handlers.env));
337
338 const withEchoHandlers = <A>(
339 rpcUrl: string,
340 use: (handlers: Pick<EchoClient, "echo" | "env">) => Effect.Effect<A>,
341 ): Effect.Effect<A, Error> =>
342 Effect.gen(function* () {
343 yield* openWebSocket(new URL("/parent", rpcUrl));
344 // Sessions carry their stack environment (real clients — the
345 // RpcProviderProxy — always send one; a session without it is an error).
346 const sessionUrl = new URL(rpcUrl);
347 sessionUrl.searchParams.set(
348 SESSION_ENV_PARAM,
349 encodeSessionEnvironment({
350 alchemyContext: { dotAlchemy: "/tmp/.alchemy", dev: true, adopt: false },
351 stack: { name: "test", stage: "dev" },
352 }),
353 );
354 return yield* Effect.promise(async () => {
355 // Cast through `unknown`: comparing capnweb's deeply-recursive Stub
356 // type against RpcStub<RpcProxyApi> exceeds the compiler's
357 // instantiation depth (TS2589/TS2321).
358 const stub = newWebSocketRpcSession(sessionUrl.toString()) as unknown as RpcStub<RpcProxyApi>;
359 const provider = await stub.getProvider("Test.Echo", FIXTURE_TS_URL);
360 const handlers = unwrapRpcHandlers(provider as any) as Pick<EchoClient, "echo" | "env">;
361 return await Effect.runPromise(use(handlers));
362 });
363 }).pipe(Effect.scoped);