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

main
ts 180 lines 6.67 KB
Raw
1 /**
2 * True `alchemy dev` end-to-end for the microvm shell (mirroring
3 * examples/aws-ecs/test/dev.test.ts): spawns the REAL CLI and drives the
4 * whole cross-cloud stack locally — no cloud credentials, no cloud
5 * resources:
6 *
7 * - Worker + ShellSession Durable Object → local workerd
8 * - IAM User/AccessKey/Role + STS chain → floci
9 * - ShellMicrovm image build + MicroVMs → floci (real Docker containers)
10 *
11 * The test opens ONE session WebSocket and runs several commands over it,
12 * asserting the streamed output renders like a real shell (no exit-status
13 * chatter, no blank-line padding) and that all commands hit the SAME
14 * MicroVM (state persists across commands — no re-boot per command).
15 */
16 import { afterAll, expect, test } from "bun:test";
17 import { spawn, spawnSync } from "node:child_process";
18 import * as path from "node:path";
19
20 const root = path.resolve(import.meta.dirname, "..");
21 // Spawn the CLI entry directly (not through `bun run` / the cli.js
22 // launcher) so signals hit the actual CLI process, whose scope teardown
23 // kills the exec child and the provider sidecars.
24 const alchemyBin = path.join(root, "node_modules", "alchemy", "bin", "alchemy.js");
25 // Isolated stage so this suite never fights a developer's own `alchemy dev`
26 // session (default stage) over state rows.
27 const STAGE = "dev-cli-test";
28
29 let proc: ReturnType<typeof spawn> | undefined;
30 let ws: WebSocket | undefined;
31 let output = "";
32
33 const pump = (stream: NodeJS.ReadableStream) => {
34 stream.on("data", (chunk: Buffer) => {
35 const text = chunk.toString();
36 output += text;
37 if (process.env.DEBUG) process.stderr.write(text);
38 });
39 };
40
41 /** Bounded poll for a (possibly async) producer to yield a value. */
42 const pollUntil = async <T>(
43 what: string,
44 f: () => T | undefined | Promise<T | undefined>,
45 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
46 ): Promise<T> => {
47 for (let i = 0; i < tries; i++) {
48 const value = await f();
49 if (value !== undefined) return value;
50 await Bun.sleep(delayMs);
51 }
52 throw new Error(
53 `Timed out waiting for ${what}.\n--- alchemy dev output (tail) ---\n${output.slice(-4000)}`,
54 );
55 };
56
57 /** Extract a stack-output URL the CLI prints on stdout. */
58 const outputUrl = (key: string) =>
59 output.match(new RegExp(`\\b${key}:\\s*['"]?(http[^\\s'",]+)`))?.[1];
60
61 /**
62 * Send a command over the session socket and collect streamed output until
63 * `expected` shows up — the shell renders like a real terminal (no exit
64 * trailer to key on).
65 */
66 const run = (socket: WebSocket, command: string, expected: string) =>
67 new Promise<string>((resolve, reject) => {
68 let out = "";
69 const onMessage = (e: MessageEvent) => {
70 out += typeof e.data === "string" ? e.data : "";
71 if (out.includes(expected)) {
72 socket.removeEventListener("message", onMessage);
73 clearTimeout(timer);
74 resolve(out);
75 }
76 };
77 // The first command waits through the session's MicroVM boot.
78 const timer = setTimeout(() => {
79 socket.removeEventListener("message", onMessage);
80 reject(new Error(`timeout for '${command}' (got: ${JSON.stringify(out)})`));
81 }, 120_000);
82 socket.addEventListener("message", onMessage);
83 socket.send(command);
84 });
85
86 afterAll(async () => {
87 ws?.close();
88 if (proc?.pid) {
89 // Ctrl-C semantics: signal the whole PROCESS GROUP (the CLI, its
90 // `--watch` exec child, and the provider sidecars).
91 const killGroup = (signal: NodeJS.Signals) => {
92 try {
93 process.kill(-proc!.pid!, signal);
94 } catch {
95 // group already gone
96 }
97 };
98 const exited = new Promise((resolve) => proc!.once("exit", resolve));
99 killGroup("SIGINT");
100 await Promise.race([exited, Bun.sleep(15_000)]);
101 if (proc.exitCode === null && proc.signalCode === null) {
102 killGroup("SIGKILL");
103 await Promise.race([exited, Bun.sleep(5_000)]);
104 }
105 }
106 if (!process.env.NO_DESTROY) {
107 spawnSync("bun", [alchemyBin, "destroy", "--stage", STAGE, "--yes"], {
108 cwd: root,
109 stdio: "inherit",
110 timeout: 300_000,
111 });
112 // Session MicroVMs are provisioned at RUNTIME (per WebSocket), not as
113 // stack resources, so `destroy` does not reap them — remove the
114 // emulator's VM containers this run booted.
115 const ids = spawnSync("docker", ["ps", "-q", "--filter", "name=floci-microvm-"], {
116 encoding: "utf8",
117 })
118 .stdout.trim()
119 .split("\n")
120 .filter(Boolean);
121 if (ids.length > 0) {
122 spawnSync("docker", ["rm", "-f", ...ids], { stdio: "ignore" });
123 }
124 }
125 }, 400_000);
126
127 test("alchemy dev serves a browser shell backed by a local MicroVM", async () => {
128 proc = spawn("bun", [alchemyBin, "dev", "--stage", STAGE], {
129 cwd: root,
130 // Own process group, so teardown can deliver Ctrl-C to the whole
131 // tree the way a terminal would.
132 detached: true,
133 stdio: ["ignore", "pipe", "pipe"],
134 });
135 pump(proc.stdout!);
136 pump(proc.stderr!);
137
138 // First dev deploy builds the ShellMicrovm image before printing
139 // stack outputs.
140 const url = await pollUntil("url in stack outputs", () => outputUrl("url"), {
141 tries: 600,
142 delayMs: 1000,
143 });
144
145 // Dev identity: the Worker is local workerd; no real cloud.
146 expect(url).toContain("localhost");
147 expect(output).not.toContain("apply failed");
148
149 // The Worker serves the terminal SPA.
150 const html = await fetch(url).then((r) => r.text());
151 expect(html).toContain("microvm@shell");
152
153 // One session socket: the Worker provisions the session's MicroVM
154 // (assume-role control plane against floci) and hands it to the DO.
155 const wsUrl = new URL(url);
156 wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
157 wsUrl.pathname = `/session/dev-test-${Math.random().toString(36).slice(2, 8)}/ws`;
158 const socket = new WebSocket(wsUrl);
159 ws = socket;
160 await new Promise<void>((resolve, reject) => {
161 socket.addEventListener("open", () => resolve());
162 socket.addEventListener("error", () => reject(new Error("socket error")));
163 });
164
165 // Command round-trip, streamed back through DO → Worker → browser.
166 const marker = "hello-from-microvm";
167 const first = await run(socket, `echo ${marker}`, marker);
168 expect(first).toContain(`${marker}\n`);
169
170 // Real-shell rendering: no exit-status chatter, no blank-line padding.
171 expect(first).not.toContain("[exit");
172 expect(first).not.toMatch(/\n\n/);
173
174 // Two more commands on the SAME socket → same cached VM: a file written
175 // by one command is read back by the next (state persists, no re-boot).
176 await run(socket, "echo persisted-$$ > /tmp/marker.txt && echo written", "written");
177 const readBack = await run(socket, "cat /tmp/marker.txt", "persisted-");
178 expect(readBack).toMatch(/persisted-\d+\n/);
179 expect(readBack).not.toMatch(/\n\n/);
180 }, 600_000);