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

main
ts 465 lines 15.2 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as GitHub from "@alchemy.run/github";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Git from "@distilled.cloud/github/git";
6 import * as Issues from "@distilled.cloud/github/issues";
7 import * as Pulls from "@distilled.cloud/github/pulls";
8 import * as Repos from "@distilled.cloud/github/repos";
9 import * as Alchemy from "alchemy";
10 import { Action } from "alchemy/Action";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as HttpClientRequest from "effect/http/HttpClientRequest";
14 import * as Layer from "effect/Layer";
15 import * as Predicate from "effect/Predicate";
16 import * as Schedule from "effect/Schedule";
17 import GitHubBindingsWorker, {
18 bindAll,
19 callBinding,
20 owner,
21 Repo,
22 repository,
23 } from "./fixtures/bindings-worker.ts";
24 import { gh } from "./scope.ts";
25
26 const providers = Layer.mergeAll(Cloudflare.providers(), GitHub.providers());
27
28 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ providers });
29
30 const stage = Test.defaultStage();
31 const scope = { owner, repo: repository };
32 const tags = [
33 "provider:cloudflare",
34 "provider:cloudflare:worker",
35 "provider:github",
36 "provider:github:bindings",
37 "live",
38 ];
39
40 type Answer<A> = { data: A; error?: undefined } | { data?: undefined; error: { _tag: string } };
41 type Call = <A = any>(binding: string, request: unknown) => Effect.Effect<Answer<A>, any, any>;
42
43 // The `*Http` layers, driven over HTTP through a deployed Worker.
44 const WorkerStack = Alchemy.Stack(
45 "GitHubBindingsStack",
46 { providers, state: Alchemy.localState() },
47 Effect.gen(function* () {
48 yield* Repo;
49 const worker = yield* GitHubBindingsWorker;
50 return { url: worker.url.as<string>() };
51 }),
52 );
53
54 const worker = beforeAll(deploy(WorkerStack), { timeout: 300_000 });
55 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(WorkerStack), { timeout: 300_000 });
56
57 const callHttp: Call = <A>(binding: string, request: unknown) =>
58 Effect.gen(function* () {
59 const { url } = yield* worker;
60 const response = yield* Test.executeWhenReady(
61 HttpClientRequest.post(`${url.replace(/\/+$/, "")}/${binding}`).pipe(
62 HttpClientRequest.bodyJsonUnsafe(request ?? {}),
63 ),
64 );
65 expect(response.status).toBe(200);
66 return (yield* response.json) as unknown as Answer<A>;
67 });
68
69 // The `*Local` layers, driven through an Action: each call deploys the stack
70 // with a fresh input, so the Action body runs once per call.
71 const LocalBindings = Layer.mergeAll(
72 GitHub.CreateIssueLocal,
73 GitHub.GetIssueLocal,
74 GitHub.UpdateIssueLocal,
75 GitHub.ListIssuesLocal,
76 GitHub.SearchIssuesLocal,
77 GitHub.CreateIssueCommentLocal,
78 GitHub.ListIssueCommentsLocal,
79 GitHub.GetPullRequestLocal,
80 GitHub.ListPullRequestsLocal,
81 GitHub.CreatePullRequestLocal,
82 GitHub.MergePullRequestLocal,
83 GitHub.CreatePullRequestReviewLocal,
84 GitHub.ListPullRequestReviewsLocal,
85 GitHub.ListPullRequestReviewCommentsLocal,
86 GitHub.ListPullRequestFilesLocal,
87 );
88
89 const localStack = (input: { binding: string; request: unknown; call: string }) =>
90 Alchemy.Stack(
91 "GitHubBindingsLocalStack",
92 { providers, state: Alchemy.localState() },
93 Effect.gen(function* () {
94 const repo = yield* Repo;
95 const Call = Action(
96 "Call",
97 Effect.gen(function* () {
98 const bindings = yield* bindAll(repo);
99 return Effect.fn(function* (input: { binding: string; request: unknown }) {
100 return yield* callBinding(bindings, input.binding, input.request);
101 });
102 }).pipe(Effect.provide(LocalBindings)),
103 );
104 return yield* Call(input);
105 }),
106 );
107
108 // Suspended so every attempt (including retries) gets a fresh input.
109 const callLocal: Call = <A>(binding: string, request: unknown) =>
110 Effect.suspend(() => deploy(localStack({ binding, request, call: crypto.randomUUID() }))).pipe(
111 Effect.map((answer) => answer as unknown as Answer<A>),
112 );
113
114 afterAll.skipIf(!!process.env.NO_DESTROY)(
115 destroy(localStack({ binding: "", request: {}, call: "" })),
116 { timeout: 120_000 },
117 );
118
119 class NotYet extends Data.TaggedError("NotYet")<{}> {}
120
121 // Issue lists and search lag writes; bounded so a real failure surfaces.
122 const indexed = { schedule: Schedule.spaced("5 seconds"), times: 18 };
123
124 const until = <A, E, R>(effect: Effect.Effect<A, E, R>, ready: (a: A) => boolean) =>
125 effect.pipe(
126 Effect.filterOrFail(ready, () => new NotYet()),
127 Effect.retry({ while: (error) => Predicate.isTagged(error, "NotYet"), ...indexed }),
128 );
129
130 const deleteBranch = (branch: string) =>
131 Effect.gen(function* () {
132 yield* gh(Git.deleteRef({ ...scope, ref: `heads/${branch}` })).pipe(
133 Effect.catchTag(["NotFound", "UnprocessableEntity"], () => Effect.void),
134 );
135 });
136
137 /**
138 * Every binding, in dependency order, through one implementation. The pull
139 * request merges into a throwaway base branch so `main` never changes.
140 */
141 const scenario = (impl: "Http" | "Local", call: Call) => {
142 const ok = <A = any>(binding: string, request?: unknown) =>
143 call<A>(binding, request).pipe(
144 Effect.map((answer) => {
145 expect(answer.error).toBeUndefined();
146 return answer.data as A;
147 }),
148 );
149
150 const title = `alchemy bindings ${impl} ${stage} ${crypto.randomUUID()}`;
151 const base = `alchemy-bindings-${impl.toLowerCase()}-${stage}-base`;
152 const head = `alchemy-bindings-${impl.toLowerCase()}-${stage}-head`;
153 const path = `alchemy-bindings/${impl.toLowerCase()}-${stage}.txt`;
154 let issueNumber: number | undefined;
155 let pullNumber: number | undefined;
156 let reviewId: number | undefined;
157
158 const resetBranches = Effect.gen(function* () {
159 const repo = yield* gh(Repos.get(scope));
160 const main = yield* gh(Git.getRef({ ...scope, ref: `heads/${repo.default_branch}` }));
161 for (const branch of [base, head]) {
162 yield* deleteBranch(branch);
163 yield* gh(Git.createRef({ ...scope, ref: `refs/heads/${branch}`, sha: main.object.sha }));
164 }
165 yield* gh(
166 Repos.createOrUpdateFileContents({
167 ...scope,
168 branch: head,
169 path,
170 message: `test: GitHub runtime bindings (${impl})`,
171 content: Buffer.from(`line one\n${crypto.randomUUID()}\n`).toString("base64"),
172 }),
173 );
174 });
175
176 // Close the run's issue and drop its branches even when a test failed.
177 afterAll(
178 Effect.gen(function* () {
179 if (issueNumber !== undefined) {
180 yield* gh(Issues.update({ ...scope, issue_number: issueNumber!, state: "closed" }));
181 }
182 yield* deleteBranch(head);
183 yield* deleteBranch(base);
184 }),
185 );
186
187 describe.sequential(impl, () => {
188 describe("CreateIssue", () => {
189 test(
190 "opens an issue in the bound repository",
191 Effect.gen(function* () {
192 const issue = yield* ok("CreateIssue", { title, body: "created by CreateIssue" });
193 issueNumber = issue.number;
194 expect(issue.title).toBe(title);
195 const data = yield* gh(Issues.get({ ...scope, issue_number: issueNumber! }));
196 expect(data.title).toBe(title);
197 expect(data.body).toBe("created by CreateIssue");
198 }),
199 { tags, timeout: 180_000 },
200 );
201 });
202
203 describe("GetIssue", () => {
204 test(
205 "gets an issue by number",
206 Effect.gen(function* () {
207 const issue = yield* ok("GetIssue", { issue_number: issueNumber });
208 expect(issue.number).toBe(issueNumber);
209 expect(issue.title).toBe(title);
210 }),
211 { tags },
212 );
213
214 test(
215 "fails with IssueNotFound for a missing issue",
216 Effect.gen(function* () {
217 const answer = yield* call("GetIssue", { issue_number: 999_999_999 });
218 expect(answer.error?._tag).toBe("IssueNotFound");
219 }),
220 { tags },
221 );
222 });
223
224 describe("ListIssues", () => {
225 test(
226 "lists the repository's issues",
227 Effect.gen(function* () {
228 const issues = yield* until(
229 ok<{ number: number }[]>("ListIssues", {
230 state: "open",
231 sort: "created",
232 direction: "desc",
233 per_page: 100,
234 }),
235 (issues) => issues.some((issue) => issue.number === issueNumber),
236 );
237 expect(issues.map((issue) => issue.number)).toContain(issueNumber);
238 }),
239 { tags, timeout: 150_000 },
240 );
241 });
242
243 describe("SearchIssues", () => {
244 test(
245 "searches issues scoped to the bound repository",
246 Effect.gen(function* () {
247 const result = yield* until(
248 ok<{ items: { number: number }[] }>("SearchIssues", { q: `"${title}" in:title` }),
249 (result) => result.items.some((item) => item.number === issueNumber),
250 );
251 expect(result.items.map((item) => item.number)).toEqual([issueNumber]);
252 }),
253 { tags, timeout: 150_000 },
254 );
255 });
256
257 describe("CreateIssueComment", () => {
258 test(
259 "comments on an issue",
260 Effect.gen(function* () {
261 const comment = yield* ok("CreateIssueComment", {
262 issue_number: issueNumber,
263 body: "comment from CreateIssueComment",
264 });
265 const data = yield* gh(Issues.getComment({ ...scope, comment_id: comment.id }));
266 expect(data.body).toBe("comment from CreateIssueComment");
267 }),
268 { tags },
269 );
270 });
271
272 describe("ListIssueComments", () => {
273 test(
274 "lists an issue's comments",
275 Effect.gen(function* () {
276 const comments = yield* ok<{ body: string }[]>("ListIssueComments", {
277 issue_number: issueNumber,
278 });
279 expect(comments.map((comment) => comment.body)).toEqual([
280 "comment from CreateIssueComment",
281 ]);
282 }),
283 { tags },
284 );
285 });
286
287 describe("UpdateIssue", () => {
288 test(
289 "closes an issue",
290 Effect.gen(function* () {
291 const issue = yield* ok("UpdateIssue", {
292 issue_number: issueNumber,
293 body: "updated by UpdateIssue",
294 state: "closed",
295 state_reason: "completed",
296 });
297 expect(issue.state).toBe("closed");
298 const data = yield* gh(Issues.get({ ...scope, issue_number: issueNumber! }));
299 expect(data.state).toBe("closed");
300 expect(data.state_reason).toBe("completed");
301 expect(data.body).toBe("updated by UpdateIssue");
302 }),
303 { tags },
304 );
305
306 test(
307 "fails with IssueNotFound for a missing issue",
308 Effect.gen(function* () {
309 const answer = yield* call("UpdateIssue", { issue_number: 999_999_999, title: "x" });
310 expect(answer.error?._tag).toBe("IssueNotFound");
311 }),
312 { tags },
313 );
314 });
315
316 describe("CreatePullRequest", () => {
317 test(
318 "opens a pull request",
319 Effect.gen(function* () {
320 yield* resetBranches;
321 const pull = yield* ok("CreatePullRequest", {
322 title: `alchemy bindings ${impl} ${stage}`,
323 head,
324 base,
325 body: "opened by CreatePullRequest",
326 });
327 pullNumber = pull.number;
328 const data = yield* gh(Pulls.get({ ...scope, pull_number: pullNumber! }));
329 expect(data.state).toBe("open");
330 expect(data.head.ref).toBe(head);
331 expect(data.base.ref).toBe(base);
332 }),
333 { tags, timeout: 120_000 },
334 );
335 });
336
337 describe("GetPullRequest", () => {
338 test(
339 "gets a pull request as JSON",
340 Effect.gen(function* () {
341 const pull = yield* ok("GetPullRequest", { pull_number: pullNumber });
342 expect(pull.number).toBe(pullNumber);
343 expect(pull.head.ref).toBe(head);
344 }),
345 { tags },
346 );
347
348 test(
349 "gets a pull request's diff as text",
350 Effect.gen(function* () {
351 const diff = yield* ok<string>("GetPullRequest", {
352 pull_number: pullNumber,
353 accept: "application/vnd.github.diff",
354 });
355 expect(diff).toContain(`diff --git a/${path} b/${path}`);
356 }),
357 { tags },
358 );
359 });
360
361 describe("ListPullRequests", () => {
362 test(
363 "lists the repository's pull requests",
364 Effect.gen(function* () {
365 const pulls = yield* ok<{ number: number }[]>("ListPullRequests", {
366 state: "open",
367 base,
368 });
369 expect(pulls.map((pull) => pull.number)).toEqual([pullNumber]);
370 }),
371 { tags },
372 );
373 });
374
375 describe("ListPullRequestFiles", () => {
376 test(
377 "lists the files a pull request changes",
378 Effect.gen(function* () {
379 const files = yield* ok<{ filename: string }[]>("ListPullRequestFiles", {
380 pull_number: pullNumber,
381 });
382 expect(files.map((file) => file.filename)).toEqual([path]);
383 }),
384 { tags },
385 );
386 });
387
388 describe("CreatePullRequestReview", () => {
389 test(
390 "submits a review with an inline comment",
391 Effect.gen(function* () {
392 const review = yield* ok("CreatePullRequestReview", {
393 pull_number: pullNumber,
394 event: "COMMENT",
395 body: "review from CreatePullRequestReview",
396 comments: [{ path, line: 1, body: "inline comment" }],
397 });
398 reviewId = review.id;
399 const data = yield* gh(
400 Pulls.getReview({
401 ...scope,
402 pull_number: pullNumber!,
403 review_id: reviewId!,
404 }),
405 );
406 expect(data.body).toBe("review from CreatePullRequestReview");
407 expect(data.state).toBe("COMMENTED");
408 }),
409 { tags },
410 );
411 });
412
413 describe("ListPullRequestReviews", () => {
414 test(
415 "lists a pull request's reviews",
416 Effect.gen(function* () {
417 const reviews = yield* ok<{ id: number }[]>("ListPullRequestReviews", {
418 pull_number: pullNumber,
419 });
420 expect(reviews.map((review) => review.id)).toEqual([reviewId]);
421 }),
422 { tags },
423 );
424 });
425
426 describe("ListPullRequestReviewComments", () => {
427 test(
428 "lists a pull request's inline review comments",
429 Effect.gen(function* () {
430 const comments = yield* ok<
431 { body: string; path: string; pull_request_review_id: number }[]
432 >("ListPullRequestReviewComments", { pull_number: pullNumber });
433 expect(
434 comments.map(({ body, path, pull_request_review_id }) => ({
435 body,
436 path,
437 pull_request_review_id,
438 })),
439 ).toEqual([{ body: "inline comment", path, pull_request_review_id: reviewId }]);
440 }),
441 { tags },
442 );
443 });
444
445 describe("MergePullRequest", () => {
446 test(
447 "merges a pull request",
448 Effect.gen(function* () {
449 const merged = yield* ok("MergePullRequest", {
450 pull_number: pullNumber,
451 merge_method: "squash",
452 });
453 expect(merged.merged).toBe(true);
454 const data = yield* gh(Pulls.get({ ...scope, pull_number: pullNumber! }));
455 expect(data.merged).toBe(true);
456 expect(data.base.ref).toBe(base);
457 }),
458 { tags },
459 );
460 });
461 });
462 };
463
464 scenario("Http", callHttp);
465 scenario("Local", callLocal);