@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 426 lines 19 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import { assert, describe, expect, it } from "@alchemy.run/test";
3 import { newWebSocketRpcSession, type RpcStub } from "capnweb";
4 import * as Clock from "effect/Clock";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as ChildProcess from "effect/process/ChildProcess";
8 import * as Schedule from "effect/Schedule";
9 import * as Sink from "effect/Sink";
10 import * as Stream from "effect/Stream";
11 import { unwrapRpcHandlers, type RpcWrapped } from "@/Local/RpcSerialization.ts";
12 import type { RpcProxyApi } from "@/Local/RpcServer.ts";
13 import { PlatformServices } from "@/Util/PlatformServices.ts";
14 import { openWebSocket, waitForExit } from "./fixtures/process-effect.ts";
15 import type { EchoClient } from "./fixtures/rpc-echo.ts";
16 import { runtimes } from "./fixtures/runtimes.ts";
17
18 const FIXTURE_TS = fileURLToPath(new URL("./fixtures/rpc-server-entry.ts", import.meta.url));
19
20 const ADDRESS_RE = /<ALCHEMY_RPC_ADDRESS>(.+?)<\/ALCHEMY_RPC_ADDRESS>/;
21
22 const sampleEnv = () =>
23 JSON.stringify({
24 profile: null,
25 envFile: null,
26 alchemyContext: {
27 dotAlchemy: "/tmp/.alchemy",
28 updateStateStore: false,
29 dev: true,
30 adopt: false,
31 },
32 stack: { name: "test", stage: "dev" },
33 });
34
35 // Concurrent at both levels: every test spawns its own isolated child
36 // process, and two of them deliberately wait out the sidecar's ~10s
37 // parent-connect self-termination. Run serially (the file default) those
38 // two waits alone would stack to ~20s of wall clock.
39 describe.concurrent("Local.RpcServer", { tags: ["local"] }, () => {
40 for (const runtime of runtimes()) {
41 describe.concurrent.skipIf(!runtime.available)(runtime.name, () => {
42 const [bin, ...args] = runtime.argv(FIXTURE_TS);
43 const launch = ChildProcess.make(bin, args, {
44 env: {
45 ALCHEMY_RPC_SERVER_ENVIRONMENT: sampleEnv(),
46 },
47 extendEnv: true,
48 // We never write to the child's stdin, so close it. stdout/stderr
49 // default to "pipe" which is what we want for the buffering forks
50 // below.
51 stdin: "ignore",
52 // SIGTERM first, escalate to SIGKILL after 1s if the child hasn't
53 // exited. Matches the behavior of the old hand-rolled finalizer.
54 killSignal: "SIGTERM",
55 forceKillAfter: "1 second",
56 });
57
58 it.live(
59 "prints the RPC address marker on stdout and accepts /parent + session connections",
60 () =>
61 Effect.gen(function* () {
62 const proc = yield* launch;
63 const url = yield* proc.stdout.pipe(
64 Stream.decodeText,
65 Stream.run(
66 Sink.fold(
67 () => "",
68 (acc) => !acc.includes("</ALCHEMY_RPC_ADDRESS>"),
69 (acc, chunk) => Effect.succeed(acc + chunk),
70 ),
71 ),
72 Effect.timeout("5 seconds"),
73 Effect.map((output) => output.match(ADDRESS_RE)?.[1]),
74 );
75 assert(url, `url not found in output: "${url}"`);
76 expect(url).toMatch(/^ws:\/\//);
77 // The sidecar listens on loopback only, under every runtime.
78 expect(new URL(url).hostname).toBe("127.0.0.1");
79
80 // Open the parent websocket inside the scope so it stays alive
81 // for the duration of the RPC exchange below; closing it later
82 // is exactly what triggers the child to exit.
83 const parent = yield* openWebSocket(new URL("/parent", url));
84
85 // Drive a real RPC call through a session websocket. capnweb's
86 // surface is Promise-based, so we wrap exactly at the boundary
87 // and let everything above and below stay in Effect.
88
89 // TODO(sam): tsc (typescript 7) vomits here, so we cast to any.
90 const stub = (newWebSocketRpcSession as any)(url) as RpcStub<RpcProxyApi>;
91 const result = yield* Effect.promise(async () => {
92 const provider = await stub.getProvider(
93 "Test.Echo",
94 new URL("./fixtures/rpc-server-entry.ts", import.meta.url).href,
95 );
96 const handlers = unwrapRpcHandlers(provider as any) as {
97 echo: (msg: string) => Effect.Effect<string>;
98 };
99 return await Effect.runPromise(handlers.echo("hello"));
100 });
101 expect(result).toBe("echo:hello");
102
103 // Closing the parent ws should cause the child to exit promptly.
104 yield* Effect.sync(() => parent.close());
105 // waitForExit fails if the child is still running after the
106 // timeout, so reaching this point means the child exited.
107 yield* waitForExit(proc, "5 seconds");
108 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
109 { timeout: 30_000 },
110 );
111
112 it.live(
113 "test release closes contexts, artifacts, and late builds without closing dev contexts",
114 () =>
115 Effect.gen(function* () {
116 const proc = yield* launch;
117 const url = yield* proc.stdout.pipe(
118 Stream.decodeText,
119 Stream.run(
120 Sink.fold(
121 () => "",
122 (text) => !text.includes("</ALCHEMY_RPC_ADDRESS>"),
123 (text, chunk) => Effect.succeed(text + chunk),
124 ),
125 ),
126 Effect.timeout("5 seconds"),
127 Effect.map((text) => text.match(ADDRESS_RE)?.[1]),
128 );
129 assert(url);
130 yield* openWebSocket(new URL("/parent", url));
131 const connect = () =>
132 Effect.acquireRelease(
133 Effect.sync(() => {
134 const socket = new WebSocket(url);
135 const rpc = newWebSocketRpcSession(socket) as unknown as RpcStub<RpcProxyApi>;
136 return { socket, rpc };
137 }),
138 ({ socket, rpc }) =>
139 Effect.sync(() => {
140 rpc[Symbol.dispose]();
141 socket.close();
142 }),
143 );
144 const group = new URL("./fixtures/rpc-server-entry.ts", import.meta.url).href;
145 const observer = yield* connect();
146 const getEcho = (rpc: RpcStub<RpcProxyApi>, owned = false) =>
147 Effect.promise(() => rpc.getProvider("Test.Echo", group, owned)).pipe(
148 Effect.map(
149 (provider) =>
150 unwrapRpcHandlers(provider as any) as {
151 echo: (msg: string) => Effect.Effect<string>;
152 stats: () => Effect.Effect<{
153 active: number;
154 built: number;
155 finalized: number;
156 }>;
157 retainArtifact: () => Effect.Effect<void>;
158 artifactCount: () => Effect.Effect<number>;
159 },
160 ),
161 );
162 const dev = yield* getEcho(observer.rpc);
163 const baseline = yield* Effect.promise(() => observer.rpc.getDiagnostics()).pipe(
164 Effect.map((counts) => ({ ...counts })),
165 );
166 expect(baseline.sessions).toBe(1);
167 expect(baseline.testSessions).toBe(0);
168 const initial = yield* dev.stats();
169
170 const owned = yield* connect();
171 const provider = yield* getEcho(owned.rpc, true);
172 yield* provider.retainArtifact();
173 const retained = yield* Effect.promise(() => observer.rpc.getDiagnostics());
174 expect(retained.testSessions).toBe(1);
175 expect(retained.contexts).toBe(baseline.contexts + 1);
176 expect(retained.artifacts).toBe(baseline.artifacts + 1);
177 yield* Effect.promise(() => owned.rpc.releaseSession());
178 yield* Effect.promise(() => owned.rpc.releaseSession());
179 expect((yield* provider.artifactCount().pipe(Effect.exit))._tag).toBe("Failure");
180 expect(yield* Effect.promise(() => observer.rpc.getDiagnostics())).toMatchObject(
181 baseline,
182 );
183 expect((yield* dev.stats()).finalized).toBe(initial.finalized + 1);
184 const late = yield* Effect.tryPromise(() =>
185 owned.rpc.getProvider("Test.Echo", group, true),
186 ).pipe(Effect.exit);
187 expect(late._tag).toBe("Failure");
188 expect(yield* Effect.promise(() => observer.rpc.getDiagnostics())).toMatchObject(
189 baseline,
190 );
191
192 const blocked = yield* connect();
193 const pending = yield* Effect.tryPromise(() =>
194 blocked.rpc.getProvider("Test.Echo", `${group}#blocked`, true),
195 ).pipe(Effect.forkChild);
196 const building = yield* Effect.promise(() => observer.rpc.getDiagnostics()).pipe(
197 Effect.repeat({
198 schedule: Schedule.spaced("50 millis"),
199 times: 10,
200 until: (counts) => counts.building === 1,
201 }),
202 );
203 expect(building.building).toBe(1);
204 const acquired = yield* dev.stats().pipe(
205 Effect.repeat({
206 schedule: Schedule.spaced("50 millis"),
207 times: 10,
208 until: (stats) => stats.active === initial.active + 1,
209 }),
210 );
211 expect(acquired.active).toBe(initial.active + 1);
212 yield* Effect.promise(() => blocked.rpc.releaseSession());
213 expect((yield* Fiber.await(pending))._tag).toBe("Failure");
214 expect(yield* Effect.promise(() => observer.rpc.getDiagnostics())).toMatchObject(
215 baseline,
216 );
217 expect((yield* dev.stats()).active).toBe(initial.active);
218
219 // Old disconnects retire only their own test generation.
220 const lost = yield* connect();
221 yield* getEcho(lost.rpc, true);
222 const successor = yield* connect();
223 const next = yield* getEcho(successor.rpc, true);
224 yield* Effect.sync(() => {
225 blocked.socket.close();
226 lost.socket.close();
227 });
228 const disconnected = yield* Effect.promise(() => observer.rpc.getDiagnostics()).pipe(
229 Effect.repeat({
230 schedule: Schedule.spaced("50 millis"),
231 times: 10,
232 until: (counts) => counts.testSessions === 1,
233 }),
234 );
235 expect(disconnected.testSessions).toBe(1);
236 expect(yield* next.echo("successor")).toBe("echo:successor");
237 yield* Effect.promise(() => successor.rpc.releaseSession());
238 expect(yield* Effect.promise(() => observer.rpc.getDiagnostics())).toMatchObject(
239 baseline,
240 );
241
242 // Explicit release and transport loss do not retire ordinary dev state.
243 yield* Effect.promise(() => observer.rpc.releaseSession());
244 yield* Effect.sync(() => observer.socket.close());
245 const reconnected = yield* connect();
246 const resumed = yield* getEcho(reconnected.rpc);
247 expect(yield* resumed.echo("reconnected")).toBe("echo:reconnected");
248 expect(yield* Effect.promise(() => reconnected.rpc.getDiagnostics())).toMatchObject(
249 baseline,
250 );
251 expect((yield* resumed.stats()).active).toBe(initial.active);
252 expect((yield* resumed.stats()).built).toBe(initial.built + 4);
253 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
254 { timeout: 30_000 },
255 );
256
257 it.live(
258 "test release and disconnect drain calls and streams before provider resources",
259 () =>
260 Effect.gen(function* () {
261 const proc = yield* launch;
262 const url = yield* proc.stdout.pipe(
263 Stream.decodeText,
264 Stream.run(
265 Sink.fold(
266 () => "",
267 (text) => !text.includes("</ALCHEMY_RPC_ADDRESS>"),
268 (text, chunk) => Effect.succeed(text + chunk),
269 ),
270 ),
271 Effect.timeout("5 seconds"),
272 Effect.map((text) => text.match(ADDRESS_RE)?.[1]),
273 );
274 assert(url);
275 yield* openWebSocket(new URL("/parent", url));
276 const connect = () =>
277 Effect.acquireRelease(
278 Effect.sync(() => {
279 const socket = new WebSocket(url);
280 return {
281 socket,
282 rpc: newWebSocketRpcSession(socket) as unknown as RpcStub<RpcProxyApi>,
283 };
284 }),
285 ({ socket, rpc }) =>
286 Effect.sync(() => {
287 rpc[Symbol.dispose]();
288 socket.close();
289 }),
290 );
291 const group = new URL("./fixtures/rpc-server-entry.ts", import.meta.url).href;
292 const getEcho = (rpc: RpcStub<RpcProxyApi>, owned = false) =>
293 Effect.promise(() => rpc.getProvider("Test.Echo", group, owned)).pipe(
294 Effect.map((provider) => {
295 const wire = provider as unknown as RpcWrapped<EchoClient>;
296 return {
297 wire,
298 client: unwrapRpcHandlers(wire, ["tail"]) as unknown as EchoClient,
299 };
300 }),
301 );
302 const drainTail = (wire: RpcWrapped<EchoClient>, label: string) =>
303 Effect.promise(async () => wire.tail([label])).pipe(
304 Effect.flatMap((readable) =>
305 Stream.fromReadableStream({
306 evaluate: () => readable,
307 onError: (error) => error,
308 }).pipe(Stream.runDrain),
309 ),
310 );
311 const observer = yield* connect();
312 const { client: monitor } = yield* getEcho(observer.rpc);
313 const baseline = yield* Effect.promise(() => observer.rpc.getDiagnostics()).pipe(
314 Effect.map((counts) => ({ ...counts })),
315 );
316
317 for (const mode of ["release", "disconnect"] as const) {
318 const owned = yield* connect();
319 const { wire, client } = yield* getEcho(owned.rpc, true);
320 const labels = [`${mode}-effect`, `${mode}-stream`];
321 const call = yield* client.blockedCall(labels[0]!).pipe(Effect.forkChild);
322 const stream = yield* drainTail(wire, labels[1]!).pipe(Effect.forkChild);
323 for (const label of labels) {
324 const started = yield* monitor.callSnapshot(label).pipe(
325 Effect.repeat({
326 schedule: Schedule.spaced("50 millis"),
327 times: 10,
328 until: (snapshot) => snapshot?.events.includes("started") === true,
329 }),
330 );
331 expect(started?.events).toEqual(["started"]);
332 }
333 if (mode === "release") {
334 yield* Effect.promise(() => owned.rpc.releaseSession());
335 } else {
336 yield* Effect.sync(() => owned.socket.close());
337 }
338 for (const label of labels) {
339 const snapshot = monitor.callSnapshot(label);
340 const settled = yield* mode === "release"
341 ? snapshot
342 : snapshot.pipe(
343 Effect.repeat({
344 schedule: Schedule.spaced("50 millis"),
345 times: 10,
346 until: (value) => value?.events.includes("provider-finalized") === true,
347 }),
348 );
349 expect(settled).toEqual({
350 events: ["started", "call-finalized:live", "provider-finalized"],
351 mutations: 0,
352 artifacts: 0,
353 });
354 yield* monitor.unblockCall(label);
355 expect(yield* monitor.callSnapshot(label)).toEqual(settled);
356 }
357 expect((yield* Fiber.await(call).pipe(Effect.timeout("5 seconds")))._tag).toBe(
358 "Failure",
359 );
360 expect((yield* Fiber.await(stream).pipe(Effect.timeout("5 seconds")))._tag).toBe(
361 "Failure",
362 );
363
364 if (mode === "release") {
365 expect((yield* client.blockedCall("stale-effect").pipe(Effect.exit))._tag).toBe(
366 "Failure",
367 );
368 expect((yield* drainTail(wire, "stale-stream").pipe(Effect.exit))._tag).toBe(
369 "Failure",
370 );
371 expect((yield* client.retainArtifact().pipe(Effect.exit))._tag).toBe("Failure");
372 expect(yield* monitor.callSnapshot("stale-effect")).toBeUndefined();
373 expect(yield* monitor.callSnapshot("stale-stream")).toBeUndefined();
374 yield* Effect.promise(() => owned.rpc.releaseSession());
375 }
376 expect(yield* Effect.promise(() => observer.rpc.getDiagnostics())).toMatchObject(
377 baseline,
378 );
379 }
380
381 const transient = yield* connect();
382 const { client: dev } = yield* getEcho(transient.rpc);
383 const devCall = yield* dev.blockedCall("dev-call").pipe(Effect.forkChild);
384 const started = yield* monitor.callSnapshot("dev-call").pipe(
385 Effect.repeat({
386 schedule: Schedule.spaced("50 millis"),
387 times: 10,
388 until: (snapshot) => snapshot?.events.includes("started") === true,
389 }),
390 );
391 expect(started?.events).toEqual(["started"]);
392 yield* Effect.promise(() => transient.rpc.releaseSession());
393 yield* Effect.sync(() => transient.socket.close());
394 yield* Fiber.await(devCall).pipe(Effect.timeout("5 seconds"));
395 expect((yield* monitor.callSnapshot("dev-call"))?.events).toEqual(["started"]);
396 yield* monitor.unblockCall("dev-call");
397 const finished = yield* monitor.callSnapshot("dev-call").pipe(
398 Effect.repeat({
399 schedule: Schedule.spaced("50 millis"),
400 times: 10,
401 until: (snapshot) => snapshot?.events.includes("call-finalized:live") === true,
402 }),
403 );
404 expect(finished?.events).toEqual(["started", "call-finalized:live"]);
405 expect(finished?.mutations).toBe(1);
406 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
407 { timeout: 30_000 },
408 );
409
410 it.live(
411 "exits if the parent never connects within ~10s",
412 () =>
413 Effect.gen(function* () {
414 const start = yield* Clock.currentTimeMillis;
415 const proc = yield* launch;
416 // Never open /parent — the server should self-terminate via the
417 // connect timeout.
418 yield* waitForExit(proc, "20 seconds");
419 const elapsed = (yield* Clock.currentTimeMillis) - start;
420 expect(elapsed).toBeLessThan(18_000);
421 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
422 { timeout: 30_000 },
423 );
424 });
425 }
426 });