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

main
ts 212 lines 8.02 KB
Raw
1 import { expect, test } from "bun:test";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6 import nativeAI from "../src/ai/native.ts";
7 import bare from "../src/forms/bare.ts";
8 import hono from "../src/forms/hono.ts";
9
10 const source = Effect.fn(function* (file: string) {
11 const fs = yield* FileSystem.FileSystem;
12 const path = yield* Path.Path;
13 const filename = yield* path.fromFileUrl(new URL(`../${file}`, import.meta.url));
14 return yield* fs.readFileString(filename);
15 });
16
17 test("all three stack configurations import without running deployment effects", () =>
18 Effect.runPromise(
19 Effect.gen(function* () {
20 const effect = yield* Effect.tryPromise(() => import("../alchemy.run.ts"));
21 const native = yield* Effect.tryPromise(() => import("../alchemy.native.ts"));
22 const preview = yield* Effect.tryPromise(() => import("../alchemy.preview.ts"));
23 expect(effect.default).toBeDefined();
24 expect(native.default).toBeDefined();
25 expect(preview.default).toBeDefined();
26 }),
27 ));
28
29 const files = [
30 "src/resources.ts",
31 "src/Api.ts",
32 "src/Events.ts",
33 "src/website.ts",
34 "src/features.ts",
35 "src/ai/resources.ts",
36 "src/ai/index.ts",
37 "src/ai/EffectApi.ts",
38 "src/forms/index.ts",
39 "src/forms/LayerApi.ts",
40 ];
41
42 test("composition declares one Project and one Backend for every feature module", () =>
43 Effect.runPromise(
44 Effect.gen(function* () {
45 const modules = yield* Effect.forEach(files, source);
46 const combined = modules.join("\n");
47 expect(combined.match(/Neon\.Project\(/g)).toHaveLength(1);
48 expect(combined.match(/Neon\.Branch\(/g)).toHaveLength(1);
49 expect(combined).not.toContain("Alchemy.Stack(");
50 expect(modules[0]).toContain('Neon.Project("Project"');
51 expect(modules[0]).toContain('Neon.Branch("Backend"');
52 expect(modules[0]).toContain('access: "private"');
53 expect(modules[0]).toContain('access: "public_read"');
54 expect(modules[0]).toContain('key: "config/settings.json"');
55 expect(modules[0]).toContain("schema: Schema.Struct(");
56 expect(modules[1]).toContain("Neon.ConnectAuth(auth)");
57 expect(modules[1]).toContain("Neon.ReadObject(settings)");
58 for (const file of ["alchemy.run.ts", "alchemy.native.ts"]) {
59 const stack = yield* source(file);
60 expect(stack).toContain("yield* features");
61 expect(stack).not.toContain("Neon.Project(");
62 }
63 const features = yield* source("src/features.ts");
64 expect(features).toContain('enableAI === "true" ? yield* ai : undefined');
65 expect(features).toContain('enableForms === "true" ? yield* forms : undefined');
66 expect(features.match(/Config\.withDefault\("false"\)/g)).toHaveLength(2);
67 for (const file of ["src/ai/index.ts", "src/ai/EffectApi.ts"]) {
68 const ai = yield* source(file);
69 expect(ai).toContain('Config.String("NEON_AI_ALLOW_PAID")');
70 expect(ai).toContain('Config.withDefault("false")');
71 }
72 }).pipe(Effect.provide(NodeServices.layer)),
73 ));
74
75 test("cron writes are idempotent and the preview only enables its own upload trigger", () =>
76 Effect.runPromise(
77 Effect.gen(function* () {
78 const events = yield* source("src/Events.ts");
79 const migration = yield* source("migrations/0002_scheduled_runs.sql");
80 expect(events).toContain('Neon.CronEventSource("Nightly", { cron: "0 2 * * *" }');
81 expect(events).toContain("ON CONFLICT DO NOTHING");
82 expect(migration).toContain("invocation_id text PRIMARY KEY");
83 const preview = yield* source("alchemy.preview.ts");
84 expect(preview).toContain('"NeonUploadPreview"');
85 expect(preview).toContain('name: "PreviewUploads"');
86 expect(preview).not.toContain("yield* features");
87 expect(preview).not.toContain("CronEventSource");
88 expect(preview).not.toContain("Neon.CustomDomain(");
89 }).pipe(Effect.provide(NodeServices.layer)),
90 ));
91
92 const invokeNativeAI = Effect.fn(function* (options: {
93 path?: string;
94 method?: string;
95 authorization?: string;
96 body?: string;
97 paid?: string;
98 }) {
99 const names = ["EXAMPLE_API_KEY", "AI_MODEL", "AI_ALLOW_PAID"] as const;
100 return yield* Effect.acquireUseRelease(
101 Effect.sync(() => {
102 const previous = names.map((name) => [name, process.env[name]] as const);
103 process.env.EXAMPLE_API_KEY = "offline-example-secret";
104 process.env.AI_MODEL = "never-call-this-model";
105 if (options.paid === undefined) delete process.env.AI_ALLOW_PAID;
106 else process.env.AI_ALLOW_PAID = options.paid;
107 return previous;
108 }),
109 () =>
110 Effect.gen(function* () {
111 const method = options.method ?? "POST";
112 const request = yield* Effect.sync(
113 () =>
114 new Request(`https://example.invalid${options.path ?? "/chat"}`, {
115 method,
116 body: method === "POST" ? (options.body ?? '{"prompt":"Hello"}') : undefined,
117 headers: {
118 "content-type": "application/json",
119 ...(options.authorization === undefined
120 ? {}
121 : { authorization: options.authorization }),
122 },
123 }),
124 );
125 return yield* Effect.tryPromise(() => nativeAI.fetch(request));
126 }),
127 (previous) =>
128 Effect.sync(() => {
129 for (const [name, value] of previous) {
130 if (value === undefined) delete process.env[name];
131 else process.env[name] = value;
132 }
133 }),
134 );
135 });
136
137 for (const authorization of [undefined, "Bearer wrong"]) {
138 test.serial(`native AI authenticates before parsing: ${authorization ?? "missing"}`, () =>
139 Effect.runPromise(
140 Effect.gen(function* () {
141 const response = yield* invokeNativeAI({
142 authorization,
143 body: "not-json",
144 });
145 expect(response.status).toBe(401);
146 }),
147 ),
148 );
149 }
150
151 for (const body of [
152 "{",
153 "{}",
154 "null",
155 '{"prompt":4}',
156 '{"prompt":" "}',
157 JSON.stringify({ prompt: "x".repeat(4001) }),
158 ]) {
159 test.serial(`native AI rejects invalid prompts before the paid gate: ${body.slice(0, 30)}`, () =>
160 Effect.runPromise(
161 Effect.gen(function* () {
162 const response = yield* invokeNativeAI({
163 authorization: "Bearer offline-example-secret",
164 body,
165 });
166 expect(response.status).toBe(400);
167 }),
168 ),
169 );
170 }
171
172 for (const paid of [undefined, "false", "1"]) {
173 test.serial(`native AI refuses inference without exact opt-in: ${paid ?? "unset"}`, () =>
174 Effect.runPromise(
175 Effect.gen(function* () {
176 const response = yield* invokeNativeAI({
177 authorization: "Bearer offline-example-secret",
178 paid,
179 });
180 expect(response.status).toBe(503);
181 const body = yield* Effect.tryPromise(() => response.text());
182 expect(body).not.toContain("offline-example-secret");
183 }),
184 ),
185 );
186 }
187
188 test.serial("native streaming UI and public handler forms remain usable offline", () =>
189 Effect.runPromise(
190 Effect.gen(function* () {
191 const page = yield* invokeNativeAI({ path: "/", method: "GET" });
192 expect(page.status).toBe(200);
193 const html = yield* Effect.tryPromise(() => page.text());
194 expect(html).toContain('id="cancel"');
195 expect(html).toContain("AbortController");
196 expect(html).toContain("text-delta");
197 expect(html).not.toContain("offline-example-secret");
198 expect((yield* invokeNativeAI({ path: "/missing", method: "GET" })).status).toBe(404);
199 const request = yield* Effect.sync(() => new Request("https://example.invalid/health"));
200 const bareResponse = yield* Effect.sync(() => bare(request));
201 expect(yield* Effect.tryPromise(() => bareResponse.json())).toEqual({
202 path: "/health",
203 });
204 const result = yield* Effect.sync(() => hono.fetch(request));
205 const honoResponse =
206 result instanceof Response ? result : yield* Effect.tryPromise(() => result);
207 expect(yield* Effect.tryPromise(() => honoResponse.json())).toEqual({
208 ok: true,
209 });
210 }),
211 ),
212 );