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

main
ts 4,722 lines 158 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import { afterEach, assert, expect, it, vi } from "@effect/vitest";
4 import * as Effect from "effect/Effect";
5 import * as Deferred from "effect/Deferred";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 import * as Option from "effect/Option";
9 import * as Result from "effect/Result";
10 import * as Schema from "effect/Schema";
11 import * as TestClock from "effect/testing/TestClock";
12 import * as Redacted from "effect/Redacted";
13
14 import { HttpClient, HttpClientResponse } from "effect/http";
15
16 import * as GitHubRest from "./GitHubRest.ts";
17 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
18 import * as GitHubCredentials from "./GitHubCredentials.ts";
19 import * as GitHubQuota from "./GitHubQuota.ts";
20 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
21 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
22 import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
23 import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
24 import { KnownWorkflowRuns } from "./gitHubConditionalChecks.ts";
25 import * as GitHubAppAccess from "./GitHubAppAccess.ts";
26 import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
27
28 const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
29 enabled: false,
30 token: () => Effect.succeedNone,
31 invalidate: () => Effect.void,
32 });
33 const mockedAppToken = vi.fn<(host: string) => Effect.Effect<Option.Option<string>>>(
34 () => Effect.succeedNone,
35 );
36
37 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
38
39 // GitHub's field-level reviewer refusal; the surrounding response data is synthetic.
40 const refusedReviewer = {
41 type: "FORBIDDEN",
42 message: "Resource not accessible by integration",
43 path: ["repository", "pullRequest", "reviewRequests", "nodes", 0, "requestedReviewer"],
44 };
45 // What GitHub answers for a pull request that has no `refs/pull/<number>/head`.
46 const unresolvedPullRef = {
47 type: "NOT_FOUND",
48 message: "Could not resolve head ref 'refs/pull/7/head'.",
49 path: ["repository", "pullRequest", "baseRef", "compare"],
50 };
51 const pullRequestInput = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
52 type PullRequestRead = (
53 input: typeof pullRequestInput,
54 ) => Effect.Effect<unknown, GitHubPullRequestApi.GitHubPullRequestApiError>;
55 const refusedReviewerResponse = () =>
56 Effect.succeed(output(encodeJson({ ...coreResponse(), errors: [refusedReviewer] })));
57
58 const coreResponse = (pullRequest: Readonly<Record<string, unknown>> = {}) => ({
59 data: {
60 repository: {
61 mergeCommitAllowed: true,
62 squashMergeAllowed: false,
63 rebaseMergeAllowed: true,
64 autoMergeAllowed: true,
65 viewerPermission: "WRITE",
66 pullRequest: {
67 number: 7,
68 title: "Pull request 7",
69 url: "https://github.com/acme/web/pull/7",
70 body: "",
71 isDraft: false,
72 mergeable: "MERGEABLE",
73 mergeStateStatus: "BLOCKED",
74 reviewDecision: null,
75 additions: 0,
76 deletions: 0,
77 changedFiles: 0,
78 mergedAt: null,
79 mergeCommit: null,
80 mergedBy: null,
81 closedAt: null,
82 isCrossRepository: false,
83 maintainerCanModify: true,
84 headRepositoryOwner: null,
85 headRepository: null,
86 headRef: null,
87 author: null,
88 autoMergeRequest: null,
89 headRefName: "feature",
90 baseRefName: "main",
91 headRefOid: "abc123",
92 state: "OPEN",
93 createdAt: "2026-07-01T00:00:00Z",
94 updatedAt: "2026-07-02T00:00:00Z",
95 viewerCanUpdate: true,
96 viewerDidAuthor: false,
97 viewerCanUpdateBranch: true,
98 baseRef: { compare: { behindBy: 2 } },
99 reviewRequests: { nodes: [] },
100 labels: { nodes: [] },
101 commits: { nodes: [] },
102 ...pullRequest,
103 },
104 },
105 },
106 });
107
108 type ApiCall =
109 | {
110 readonly kind: "graphql";
111 readonly authorization: string | undefined;
112 readonly partial?: boolean;
113 readonly operationName?: string;
114 readonly host: string;
115 readonly operation: string;
116 readonly query: string;
117 readonly variables?: Readonly<Record<string, unknown>>;
118 }
119 | ({ readonly kind: "rest" } & GitHubRest.GitHubRestInput);
120
121 type ApiAnswer = Effect.Effect<GitHubRest.GitHubRestResponse, GitHubRequestPolicy.GitHubApiError>;
122
123 const mockedExecute = vi.fn<(call: ApiCall) => ApiAnswer>();
124 const defaultCredential = (host: string) =>
125 Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:token` });
126 const mockedCredential =
127 vi.fn<
128 (
129 host: string,
130 ) => Effect.Effect<GitHubRequestPolicy.GitHubHeldCredential, GitHubRequestPolicy.GitHubApiError>
131 >(defaultCredential);
132 const mockedStackMemberships = vi.fn<(call: ApiCall) => ApiAnswer>(() =>
133 Effect.succeed(output('{"data":{}}')),
134 );
135
136 const mockApi = Layer.succeed(
137 GitHubRest.GitHubRest,
138 GitHubRest.GitHubRest.of({
139 rest: (input) => mockedExecute({ kind: "rest", ...input }),
140 credential: (host) => mockedCredential(host),
141 appCredential: () => Effect.succeedNone,
142 }),
143 );
144
145 const mockHttp = Layer.succeed(
146 HttpClient.HttpClient,
147 HttpClient.make((request) =>
148 Effect.gen(function* () {
149 const host = new URL(request.url).hostname.replace(/^api\./, "");
150 const sent =
151 request.body._tag === "Uint8Array"
152 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
153 readonly query: string;
154 readonly operationName: string;
155 readonly variables: Readonly<Record<string, unknown>>;
156 })
157 : { query: "", operationName: "", variables: {} };
158 const call: ApiCall = {
159 kind: "graphql",
160 authorization: request.headers["authorization"],
161 host,
162 operation: "batch",
163 operationName: sent.operationName,
164 query: sent.query,
165 variables: sent.variables,
166 partial: true,
167 };
168 const answer = yield* (
169 sent.query.startsWith("query PullRequestStackMembership(")
170 ? mockedStackMemberships
171 : mockedExecute
172 )(call).pipe(
173 Effect.catchTags({
174 GitHubApiResponseError: (error) =>
175 Effect.succeed(output('{"message":"Bad gateway"}', false, false, {}, error.status)),
176 }),
177 Effect.orDie,
178 );
179 // Empty mutation mocks still need the selected GraphQL root field.
180 const body =
181 answer.body === "{}" && sent.query.startsWith("mutation ")
182 ? encodeJson(mutationAnswer(sent.query))
183 : answer.body;
184 return HttpClientResponse.fromWeb(
185 request,
186 new Response(body, {
187 status: answer.status,
188 headers: { "content-type": "application/json", ...answer.headers },
189 }),
190 );
191 }),
192 ),
193 );
194
195 const layer = it.layer(
196 GitHubPullRequestApi.layer.pipe(
197 Layer.provideMerge(GitHubAppAccess.layer),
198 Layer.provideMerge(mockApi),
199 Layer.provideMerge(GitHubRequestPolicy.layer),
200 Layer.provideMerge(
201 Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
202 enabled: false,
203 token: (host) => mockedAppToken(host),
204 invalidate: () => Effect.void,
205 }),
206 ),
207 Layer.provideMerge(GitHubQuota.layer),
208 Layer.provideMerge(SourceControlRateLimit.layer),
209 Layer.provideMerge(mockHttp),
210 Layer.provideMerge(
211 Layer.succeed(GitHubCredentials.GitHubCredentials, {
212 get: (host) =>
213 mockedCredential(host).pipe(
214 Effect.map((held) => ({ source: "gh" as const, ...held, host })),
215 Effect.mapError(() => new GitHubCredentials.GitHubCliMissingError({ host })),
216 ),
217 saved: () => Effect.succeedNone,
218 fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
219 invalidate: () => Effect.void,
220 }),
221 ),
222 Layer.provide(NodeCrypto.layer),
223 Layer.provide(TestSourceControlHost.layer()),
224 Layer.provide(NodeServices.layer),
225 ),
226 );
227
228 function output(
229 body: string,
230 truncated = false,
231 invalidUtf8 = false,
232 headers: Readonly<Record<string, string>> = {},
233 status = 200,
234 ): GitHubRest.GitHubRestResponse {
235 return { status, headers, body, truncated, invalidUtf8 };
236 }
237
238 function graphqlQuota(remaining: number, resetAt = "2099-08-13T14:00:00Z") {
239 return {
240 "x-ratelimit-resource": "graphql",
241 "x-ratelimit-limit": "5000",
242 "x-ratelimit-remaining": String(remaining),
243 "x-ratelimit-reset": String(Date.parse(resetAt) / 1000),
244 };
245 }
246
247 const rowDefaults = {
248 author: null,
249 state: "OPEN",
250 isDraft: false,
251 mergeable: "UNKNOWN",
252 reviewDecision: null,
253 latestReviews: { nodes: [] },
254 mergedAt: null,
255 reviewRequests: { nodes: [] },
256 labels: { nodes: [] },
257 commits: { nodes: [] },
258 };
259
260 const lastPage = { hasNextPage: false, endCursor: null };
261
262 function rows(
263 count: number,
264 firstNumber: number,
265 overrides: (number: number) => Readonly<Record<string, unknown>> = () => ({}),
266 ): ReadonlyArray<Record<string, unknown>> {
267 return Array.from({ length: count }, (_, index) => {
268 const number = firstNumber + index;
269 const { reviewRequests, checks, ...rest } = overrides(number) as {
270 reviewRequests?: ReadonlyArray<Record<string, string>>;
271 checks?: string;
272 } & Record<string, unknown>;
273 return {
274 ...rowDefaults,
275 number,
276 title: `Pull request ${number}`,
277 url: `https://github.com/acme/web/pull/${number}`,
278 headRefName: "feat/page",
279 baseRefName: "main",
280 createdAt: "2026-07-01T00:00:00Z",
281 updatedAt: "2026-07-02T00:00:00Z",
282 repository: { nameWithOwner: "acme/web" },
283 ...(reviewRequests === undefined
284 ? {}
285 : {
286 reviewRequests: {
287 nodes: reviewRequests.map((requestedReviewer) => ({
288 requestedReviewer: {
289 __typename: "slug" in requestedReviewer ? "Team" : "User",
290 ...requestedReviewer,
291 },
292 })),
293 },
294 }),
295 ...(checks === undefined
296 ? {}
297 : { commits: { nodes: [{ commit: { statusCheckRollup: { state: checks } } }] } }),
298 ...rest,
299 };
300 });
301 }
302
303 function pullRequests(
304 count: number,
305 firstNumber: number,
306 overrides?: (number: number) => Readonly<Record<string, unknown>>,
307 ): string {
308 return encodeJson({
309 data: {
310 search: { pageInfo: lastPage, nodes: rows(count, firstNumber, overrides) },
311 },
312 });
313 }
314
315 function listedPullRequests(
316 count: number,
317 firstNumber: number,
318 overrides?: (number: number) => Readonly<Record<string, unknown>>,
319 ): string {
320 return encodeJson({
321 data: {
322 repository: {
323 pullRequests: {
324 pageInfo: lastPage,
325 nodes: rows(count, firstNumber, overrides),
326 },
327 },
328 },
329 });
330 }
331
332 const emptySearch = () => output(pullRequests(0, 1));
333 const emptyList = () => output(listedPullRequests(0, 1));
334
335 function pullRequestFiles(count: number, firstIndex: number): string {
336 return encodeJson(
337 Array.from({ length: count }, (_, index) => ({
338 filename: `src/file${firstIndex + index}.ts`,
339 status: "modified",
340 patch: "@@ -1 +1 @@\n-old\n+new",
341 })),
342 );
343 }
344
345 function threadComments(
346 ids: ReadonlyArray<string>,
347 endCursor: string | null,
348 totalCount = ids.length,
349 author: Readonly<Record<string, unknown>> | null = null,
350 ) {
351 return {
352 totalCount,
353 pageInfo: { hasNextPage: endCursor !== null, endCursor },
354 nodes: ids.map((id) => ({
355 id,
356 author,
357 body: id,
358 createdAt: "2026-07-01T00:00:00Z",
359 lastEditedAt: null,
360 url: `https://github.com/acme/web/pull/7#discussion_${id}`,
361 isMinimized: false,
362 pullRequestReview: null,
363 reactionGroups: [],
364 })),
365 };
366 }
367
368 function thread(id: string, ...commentIds: ReadonlyArray<string>) {
369 return {
370 id,
371 path: "src/a.ts",
372 line: 1,
373 diffSide: "RIGHT",
374 isResolved: false,
375 isOutdated: false,
376 comments: threadComments(commentIds, null),
377 };
378 }
379
380 function reviewThreadsPage(
381 nodes: ReadonlyArray<Record<string, unknown>>,
382 endCursor: string | null,
383 requestedReviewers: ReadonlyArray<Record<string, unknown>> = [],
384 ): string {
385 return encodeJson({
386 data: {
387 viewer: { login: "viewer" },
388 repository: {
389 pullRequest: {
390 reviewThreads: {
391 totalCount: nodes.length,
392 pageInfo: { hasNextPage: endCursor !== null, endCursor },
393 nodes,
394 },
395 viewerCanUpdate: true,
396 viewerDidAuthor: false,
397 author: null,
398 reactionGroups: [],
399 comments: { nodes: [] },
400 reviews: { nodes: [] },
401 reviewRequests: {
402 nodes: requestedReviewers.map((requestedReviewer) => ({ requestedReviewer })),
403 },
404 latestReviews: { nodes: [] },
405 reviewDismissals: { pageInfo: lastPage, nodes: [] },
406 commits: { nodes: [] },
407 },
408 },
409 },
410 });
411 }
412
413 function threadCommentsPage(
414 ids: ReadonlyArray<string>,
415 endCursor: string | null,
416 totalCount: number,
417 pullRequestId = "PR_7",
418 ): string {
419 return encodeJson({
420 data: {
421 viewer: { login: "viewer" },
422 repository: { pullRequest: { id: "PR_7" } },
423 node: {
424 __typename: "PullRequestReviewThread",
425 pullRequest: { id: pullRequestId },
426 comments: threadComments(ids, endCursor, totalCount),
427 },
428 },
429 });
430 }
431
432 const diffRefused = new GitHubRequestPolicy.GitHubApiResponseError({
433 host: "github.com",
434 operation: "getPullRequestDiff",
435 status: 406,
436 });
437
438 function callAt(index: number): ApiCall {
439 const call = mockedExecute.mock.calls[index];
440 assert.isDefined(call);
441 return call[0];
442 }
443
444 function varsAt(index: number): Readonly<Record<string, unknown>> {
445 const call = callAt(index);
446 assert.strictEqual(call.kind, "graphql");
447 return call.kind === "graphql" ? (call.variables ?? {}) : {};
448 }
449
450 function queryAt(index: number): string {
451 const call = callAt(index);
452 return call.kind === "graphql" ? call.query : "";
453 }
454
455 function pathAt(index: number): string {
456 const call = callAt(index);
457 return call.kind === "rest" ? call.path : "";
458 }
459
460 function searchOfCall(index: number): string | undefined {
461 const q = callAt(index).kind === "graphql" ? varsAt(index)["q"] : undefined;
462 return typeof q === "string" ? q : undefined;
463 }
464
465 function searchItem(number: number, repository: string, updatedAt: string) {
466 return {
467 ...rowDefaults,
468 number,
469 title: `Pull request ${number}`,
470 url: `https://github.com/${repository}/pull/${number}`,
471 author: {
472 __typename: "User",
473 login: "octocat",
474 avatarUrl: "https://avatars/octocat",
475 name: null,
476 },
477 headRefName: "feat/page",
478 baseRefName: "main",
479 state: "OPEN",
480 isDraft: false,
481 mergeable: "MERGEABLE",
482 createdAt: "2026-07-01T00:00:00Z",
483 updatedAt,
484 repository: { nameWithOwner: repository },
485 reviewRequests: { nodes: [{ requestedReviewer: { __typename: "User", login: "hubot" } }] },
486 labels: { nodes: [{ name: "bug", color: "ff0000", description: "Something is broken" }] },
487 };
488 }
489
490 function searchPage(nodes: ReadonlyArray<unknown>, hasNextPage = false) {
491 return output(
492 encodeJson({
493 data: {
494 search: { pageInfo: { hasNextPage, endCursor: hasNextPage ? "next" : null }, nodes },
495 },
496 }),
497 );
498 }
499
500 const searchQueryOfCall = searchOfCall;
501
502 function matches(call: ApiCall, needle: string): boolean {
503 return call.kind === "graphql"
504 ? call.operationName === needle || call.query.includes(needle)
505 : call.path.includes(needle);
506 }
507
508 function route(...routes: ReadonlyArray<readonly [needle: string, body: unknown]>): void {
509 mockedExecute.mockImplementation((call) => {
510 const match = routes.find(([needle]) => matches(call, needle));
511 return Effect.succeed(
512 output(
513 match !== undefined
514 ? encodeJson(match[1])
515 : call.kind === "graphql" && call.query.startsWith("mutation ")
516 ? encodeJson(mutationAnswer(call.query))
517 : "{}",
518 ),
519 );
520 });
521 }
522
523 function mutationAnswer(query: string) {
524 const root = /\)\{(\w+)(?:\(|\{|@)/.exec(query)?.[1];
525 return { data: root === undefined ? {} : { [root]: null } };
526 }
527
528 function variablesOf(needle: string): ReadonlyArray<Readonly<Record<string, unknown>>> {
529 return mockedExecute.mock.calls.flatMap(([call]) =>
530 call.kind === "graphql" && matches(call, needle) ? [call.variables ?? {}] : [],
531 );
532 }
533
534 function restCallsTo(needle: string): ReadonlyArray<GitHubRest.GitHubRestInput> {
535 return mockedExecute.mock.calls.flatMap(([call]) =>
536 call.kind === "rest" && call.path.includes(needle) ? [call] : [],
537 );
538 }
539
540 /** Route before the node-ID lookup, whose document is contained in this scope query. */
541 const SUBJECT_SCOPE_QUERY = "PullRequestSubject";
542 const subjectScope = (subjectId: string, pullRequestId: string) => ({
543 data: {
544 repository: { pullRequest: { id: pullRequestId } },
545 node: { __typename: "IssueComment", id: subjectId, pullRequest: { id: pullRequestId } },
546 },
547 });
548
549 const checkRun = (fields: Record<string, unknown>) => ({
550 __typename: "CheckRun",
551 name: "",
552 status: "COMPLETED",
553 conclusion: null,
554 startedAt: null,
555 completedAt: null,
556 detailsUrl: null,
557 checkSuite: { workflowRun: null },
558 ...fields,
559 });
560
561 const checkContextsPage = (
562 nodes: ReadonlyArray<Record<string, unknown>>,
563 endCursor: string | null,
564 headRefOid = "abc123",
565 ) =>
566 encodeJson({
567 data: {
568 repository: {
569 pullRequest: {
570 headRefOid,
571 commits: {
572 nodes: [
573 {
574 commit: {
575 statusCheckRollup: {
576 contexts: { nodes, pageInfo: { hasNextPage: endCursor !== null, endCursor } },
577 },
578 },
579 },
580 ],
581 },
582 },
583 },
584 },
585 });
586
587 const pullRequestRefs = encodeJson({ base: { sha: "a1b2c3d" }, head: { sha: "b1c2d3e" } });
588 const pullRequestMergeBase = encodeJson({ merge_base_commit: { sha: "c1d2e3f" } });
589
590 const crossRepositoryDetail = (headRefOid = "abc123") =>
591 coreResponse({
592 headRefName: "feat/page",
593 headRefOid,
594 isCrossRepository: true,
595 headRepositoryOwner: { __typename: "User", login: "octocat" },
596 });
597
598 const heads = (numbers: ReadonlyArray<number>) => ({
599 data: {
600 repository: {
601 pullRequests: {
602 pageInfo: { hasNextPage: false, endCursor: null },
603 nodes: numbers.map((number) => ({
604 number,
605 headRefOid: "abc123",
606 isCrossRepository: true,
607 headRepositoryOwner: { __typename: "User", login: "octocat" },
608 })),
609 },
610 },
611 },
612 });
613
614 const workflowRuns = (ids: ReadonlyArray<number>) => ({
615 workflow_runs: ids.map((id) => ({
616 id,
617 name: id === 10 ? "build" : `run ${id}`,
618 html_url: `https://example.com/${id}`,
619 })),
620 });
621
622 function workflowApprovalRoutes(
623 detail: () => unknown,
624 headsAnswer: unknown,
625 runsAnswer: unknown,
626 ): void {
627 mockedExecute.mockImplementation((call) =>
628 Effect.sync(() =>
629 output(
630 call.kind === "rest"
631 ? call.path.endsWith("/approve")
632 ? ""
633 : encodeJson(runsAnswer)
634 : call.operationName === "PullRequestHeads"
635 ? encodeJson(headsAnswer)
636 : encodeJson(detail()),
637 ),
638 ),
639 );
640 }
641
642 /** Node IDs stay cached after the first test. */
643 const NODE_ID_QUERY = "PullRequestNodeId";
644 const nodeIdAnswer = (id: string) => ({ data: { repository: { pullRequest: { id } } } });
645
646 afterEach(() => {
647 mockedExecute.mockReset();
648 mockedStackMemberships.mockReset();
649 mockedCredential.mockReset();
650 mockedAppToken.mockReset();
651 mockedCredential.mockImplementation(defaultCredential);
652 });
653
654 it.effect(
655 "keeps a verified credential through an auth switch and separates token fingerprints",
656 () =>
657 Effect.gen(function* () {
658 let activeToken = "broad-credential";
659 const requests: Array<{ readonly url: string; readonly authorization: string | undefined }> =
660 [];
661 const credentials = Layer.succeed(
662 GitHubCredentials.GitHubCredentials,
663 GitHubCredentials.GitHubCredentials.of({
664 get: (host) =>
665 Effect.sync(() => ({
666 host,
667 token: Redacted.make(activeToken),
668 source: "gh" as const,
669 fingerprint: `${host}:${activeToken.length}${activeToken.at(-1)}`,
670 })),
671 saved: () => Effect.succeedNone,
672 fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
673 invalidate: () => Effect.void,
674 }),
675 );
676 const http = Layer.succeed(
677 HttpClient.HttpClient,
678 HttpClient.make((request) =>
679 Effect.sync(() => {
680 requests.push({ url: request.url, authorization: request.headers["authorization"] });
681 const body = request.url.endsWith("/user")
682 ? { id: 123, login: "same-account" }
683 : {
684 data: {
685 repository: { pullRequest: { id: "PR_1" } },
686 addComment: { clientMutationId: null },
687 },
688 };
689 return HttpClientResponse.fromWeb(
690 request,
691 new Response(encodeJson(body), { headers: { "content-type": "application/json" } }),
692 );
693 }),
694 ),
695 );
696 const cli = yield* GitHubPullRequestApi.make.pipe(
697 Effect.provide(
698 GitHubAppAccess.layer.pipe(
699 Layer.provideMerge(GitHubRest.layer),
700 Layer.provideMerge(Layer.mergeAll(credentials, http, appSignedOut)),
701 Layer.provideMerge(GitHubQuota.layer),
702 Layer.provideMerge(SourceControlRateLimit.layer),
703 Layer.merge(TestSourceControlHost.layer()),
704 Layer.provideMerge(NodeServices.layer),
705 ),
706 ),
707 );
708 const input = { cwd: "/repo", host: "github.com" };
709 const first = yield* cli.withVerifiedCredential(input, (identity) =>
710 Effect.gen(function* () {
711 activeToken = "restricted-credential";
712 expect(yield* cli.getViewerLogin(input)).toBe("same-account");
713 yield* cli.commentOnPullRequest({
714 ...input,
715 repository: "owner/repo",
716 number: 1,
717 body: "comment",
718 });
719 return identity;
720 }),
721 );
722 const second = yield* cli.withVerifiedCredential(input, Effect.succeed);
723 expect(first.accountId).toBe(second.accountId);
724 expect(first.credentialFingerprint).not.toBe(second.credentialFingerprint);
725 expect(encodeJson([first, second])).not.toContain("broad-credential");
726 expect(encodeJson([first, second])).not.toContain("restricted-credential");
727 expect(
728 requests
729 .filter((request) => request.url.endsWith("/graphql"))
730 .map((request) => request.authorization),
731 ).toEqual(["Bearer broad-credential", "Bearer broad-credential"]);
732 expect(
733 requests
734 .filter((request) => request.url.endsWith("/user"))
735 .map((request) => request.authorization),
736 ).toEqual(["Bearer broad-credential", "Bearer restricted-credential"]);
737 expect(yield* cli.getRoutingIdentity(input)).toEqual({
738 accountId: "123",
739 viewer: "same-account",
740 });
741 }),
742 );
743
744 layer("GitHubPullRequestApi.layer", (it) => {
745 it.effect("keeps recent references when the typed number does not exist", () =>
746 Effect.gen(function* () {
747 const search = {
748 pageInfo: { hasNextPage: false },
749 nodes: [{ __typename: "Issue", number: 7, title: "Seven", issueState: "OPEN" }],
750 };
751 mockedExecute.mockImplementation((call) =>
752 Effect.succeed(
753 output(
754 encodeJson(
755 call.kind === "graphql" && call.variables?.["exact"] === true
756 ? {
757 data: { search, repository: { issueOrPullRequest: null } },
758 errors: [
759 {
760 type: "NOT_FOUND",
761 path: ["repository", "issueOrPullRequest"],
762 message: "Could not resolve to an issue or pull request.",
763 },
764 ],
765 }
766 : { data: { search } },
767 ),
768 ),
769 ),
770 );
771 const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;
772 const result = yield* api.searchRepositoryReferences({
773 cwd: "/w",
774 repository: "acme/web",
775 host: "github.com",
776 query: "99",
777 });
778 expect(result.items.map((item) => item.reference)).toEqual(["#7"]);
779 }),
780 );
781
782 it.effect("turns maintainer edits off without rewriting the pull request's text", () =>
783 Effect.gen(function* () {
784 mockedExecute.mockImplementation((call) =>
785 Effect.succeed(
786 output(
787 encodeJson(
788 call.kind === "graphql" && matches(call, NODE_ID_QUERY) ? nodeIdAnswer("PR_7") : {},
789 ),
790 ),
791 ),
792 );
793 const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;
794 yield* api.updatePullRequest({ ...pullRequestInput, maintainerCanModify: false });
795 expect(variablesOf("mutation UpdatePullRequest")).toEqual([
796 { pullRequestId: "PR_7", maintainerCanModify: false },
797 ]);
798 }),
799 );
800
801 it.effect("tails Actions job logs and re-runs a run's failed jobs together", () =>
802 Effect.gen(function* () {
803 const runOf: Record<string, number> = {
804 "11": 10,
805 "12": 10,
806 "21": 20,
807 "41": 40,
808 "42": 40,
809 "51": 50,
810 "52": 50,
811 };
812 const runJobs: Record<string, Array<{ id: number; conclusion: string }>> = {
813 "10": [
814 { id: 11, conclusion: "failure" },
815 { id: 12, conclusion: "cancelled" },
816 ],
817 // 41 passed and is asked for by name; 43 failed but was not selected.
818 "40": [
819 { id: 41, conclusion: "success" },
820 { id: 42, conclusion: "failure" },
821 { id: 43, conclusion: "failure" },
822 ],
823 "50": [
824 { id: 51, conclusion: "failure" },
825 { id: 52, conclusion: "failure" },
826 ],
827 };
828 mockedExecute.mockImplementation((call) => {
829 if (call.kind !== "rest") return Effect.succeed(output("{}"));
830 const log = /actions\/jobs\/(\d+)\/logs$/.exec(call.path);
831 if (log?.[1] === "13") return Effect.succeed(output("one long line", true));
832 if (log?.[1] === "15") return Effect.succeed(output("x".repeat(100_000)));
833 if (log?.[1] === "14") {
834 return Effect.fail(
835 new GitHubRequestPolicy.GitHubApiAuthenticationError({
836 host: "github.com",
837 operation: "readCheckLog",
838 }),
839 );
840 }
841 if (log) return Effect.succeed(output("setup\nbuild\nError: boom\n"));
842 const job = /actions\/jobs\/(\d+)$/.exec(call.path);
843 if (job) return Effect.succeed(output(encodeJson({ run_id: runOf[job[1]!] })));
844 const run = /actions\/runs\/(\d+)\/jobs\?/.exec(call.path);
845 if (run) {
846 const jobs = runJobs[run[1]!] ?? [];
847 // Run 50 has more jobs than one page shows.
848 const total = run[1] === "50" ? 150 : jobs.length;
849 return Effect.succeed(output(encodeJson({ total_count: total, jobs })));
850 }
851 return Effect.succeed(output("{}"));
852 });
853 const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;
854 const job = (id: number, run: number) => ({
855 name: `job ${id}`,
856 url: `https://github.com/octo/repo/actions/runs/${run}/job/${id}`,
857 });
858 const external = { name: "Vercel", url: "https://vercel.com/octo/repo/deployments/1" };
859 const logs = yield* api.readCheckLogs({
860 host: "github.com",
861 repository: "octo/repo",
862 checks: [job(11, 10), external],
863 tailLines: 2,
864 });
865 expect(logs).toMatchObject([
866 { name: "job 11", log: "build\nError: boom", truncated: true, detail: null },
867 { name: "Vercel", log: null },
868 ]);
869 const capped = { host: "github.com", repository: "octo/repo", tailLines: 5 };
870 expect(yield* api.readCheckLogs({ ...capped, checks: [job(13, 30)] })).toMatchObject([
871 { log: "one long line", truncated: true },
872 ]);
873 const refused = yield* Effect.flip(api.readCheckLogs({ ...capped, checks: [job(14, 30)] }));
874 const [huge] = yield* api.readCheckLogs({ ...capped, checks: [job(15, 30)] });
875 expect(huge?.log?.length).toBe(32_000);
876 expect(huge?.truncated).toBe(true);
877 expect(refused._tag).toBe("GitHubApiAuthenticationError");
878
879 const reruns = yield* api.rerunChecks({
880 host: "github.com",
881 repository: "octo/repo",
882 checks: [
883 job(11, 10),
884 job(12, 10),
885 { name: "solo", url: "https://github.com/octo/repo/runs/21" },
886 external,
887 job(41, 40),
888 { name: "job 42", url: "https://github.com/octo/repo/actions/runs/40/jobs/42" },
889 job(51, 50),
890 job(52, 50),
891 ],
892 });
893 expect(reruns.map(({ name, rerun }) => [name, rerun])).toEqual([
894 ["job 11", true],
895 ["job 12", true],
896 ["solo", true],
897 ["Vercel", false],
898 ["job 41", true],
899 ["job 42", false],
900 ["job 51", true],
901 ["job 52", false],
902 ]);
903 expect(
904 mockedExecute.mock.calls.flatMap(([call]) =>
905 call.kind === "rest" && call.method === "POST" ? [call.path] : [],
906 ),
907 ).toEqual([
908 "repos/octo/repo/actions/runs/10/rerun-failed-jobs",
909 "repos/octo/repo/actions/jobs/21/rerun",
910 "repos/octo/repo/actions/jobs/41/rerun",
911 "repos/octo/repo/actions/jobs/51/rerun",
912 ]);
913 }),
914 );
915
916 it.effect.each(["mixed", "merges", "unavailable"] as const)(
917 "reads stats only for displayed non-merge commits (%s)",
918 (kind) =>
919 Effect.gen(function* () {
920 const oids = kind === "merges" ? ["merge"] : ["regular", "merge"];
921 mockedExecute.mockReturnValueOnce(
922 Effect.succeed(
923 output(
924 encodeJson({
925 data: {
926 repository: {
927 pullRequest: {
928 author: null,
929 comments: { nodes: [], pageInfo: lastPage },
930 reviews: { nodes: [], pageInfo: lastPage },
931 commits: {
932 nodes: oids.map((oid) => ({
933 commit: {
934 id: "node-" + oid,
935 oid,
936 messageHeadline: oid,
937 committedDate: "2026-07-05T00:00:00Z",
938 parents: { totalCount: oid === "merge" ? 2 : 1 },
939 authors: { nodes: [] },
940 },
941 })),
942 },
943 },
944 },
945 },
946 }),
947 ),
948 ),
949 );
950 if (kind === "unavailable") {
951 mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}", false, false, {}, 503)));
952 } else if (kind !== "merges") {
953 mockedExecute.mockReturnValueOnce(
954 Effect.succeed(
955 output(
956 encodeJson({
957 data: {
958 nodes: [{ __typename: "Commit", oid: "regular", additions: 18, deletions: 7 }],
959 },
960 }),
961 ),
962 ),
963 );
964 }
965 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
966 const activity = yield* cli.getPullRequestActivity(pullRequestInput);
967 expect(activity.commits.map((commit) => commit.oid)).toEqual(oids);
968 expect(activity.commits.find((commit) => commit.oid === "merge")).not.toHaveProperty(
969 "additions",
970 );
971 expect(activity.commits.find((commit) => commit.oid === "merge")).not.toHaveProperty(
972 "deletions",
973 );
974 if (kind === "mixed") {
975 expect(activity.commits[0]).toMatchObject({ additions: 18, deletions: 7 });
976 } else if (kind === "unavailable") {
977 expect(activity.commits[0]).not.toHaveProperty("additions");
978 }
979 expect(variablesOf("PullRequestCommitStats")).toEqual(
980 kind === "merges" ? [] : [{ ids: ["node-regular"] }],
981 );
982 expect(mockedExecute).toHaveBeenCalledTimes(kind === "merges" ? 1 : 2);
983 }),
984 );
985
986 it.effect("reads commit stats alongside later activity pages", () =>
987 Effect.gen(function* () {
988 const laterPageStarted = yield* Deferred.make<void>();
989 const statsStarted = yield* Deferred.make<void>();
990 const activityPage = (head: boolean) => ({
991 data: {
992 repository: {
993 pullRequest: {
994 ...(head
995 ? {
996 author: null,
997 commits: {
998 nodes: [
999 {
1000 commit: {
1001 id: "node-regular",
1002 oid: "regular",
1003 messageHeadline: "regular",
1004 committedDate: "2026-07-05T00:00:00Z",
1005 parents: { totalCount: 1 },
1006 authors: { nodes: [] },
1007 },
1008 },
1009 ],
1010 },
1011 }
1012 : {}),
1013 comments: {
1014 nodes: [],
1015 pageInfo: head ? { hasNextPage: true, endCursor: "c1" } : lastPage,
1016 },
1017 reviews: { nodes: [], pageInfo: lastPage },
1018 },
1019 },
1020 },
1021 });
1022 mockedExecute.mockImplementation((call) => {
1023 if (matches(call, "PullRequestCommitStats")) {
1024 return Deferred.succeed(statsStarted, undefined).pipe(
1025 Effect.andThen(Deferred.await(laterPageStarted)),
1026 Effect.as(
1027 output(
1028 encodeJson({
1029 data: {
1030 nodes: [{ __typename: "Commit", oid: "regular", additions: 3, deletions: 1 }],
1031 },
1032 }),
1033 ),
1034 ),
1035 );
1036 }
1037 const head = call.kind === "graphql" && call.variables?.["head"] === true;
1038 return head
1039 ? Effect.succeed(output(encodeJson(activityPage(true))))
1040 : Deferred.succeed(laterPageStarted, undefined).pipe(
1041 Effect.andThen(Deferred.await(statsStarted)),
1042 Effect.as(output(encodeJson(activityPage(false)))),
1043 );
1044 });
1045 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1046
1047 const activity = yield* cli.getPullRequestActivity(pullRequestInput);
1048
1049 expect(activity.commits[0]).toMatchObject({ additions: 3, deletions: 1 });
1050 expect(activity.truncated).toBe(false);
1051 expect(mockedExecute).toHaveBeenCalledTimes(3);
1052 }),
1053 );
1054
1055 it.effect("reports activity as truncated when comment pages remain past the page cap", () =>
1056 Effect.gen(function* () {
1057 mockedExecute.mockImplementation((call) => {
1058 const head = call.kind === "graphql" && call.variables?.["head"] === true;
1059 return Effect.succeed(
1060 output(
1061 encodeJson({
1062 data: {
1063 repository: {
1064 pullRequest: {
1065 ...(head ? { author: null, commits: { nodes: [] } } : {}),
1066 comments: { nodes: [], pageInfo: { hasNextPage: true, endCursor: "c1" } },
1067 ...(head ? { reviews: { nodes: [], pageInfo: lastPage } } : {}),
1068 },
1069 },
1070 },
1071 }),
1072 ),
1073 );
1074 });
1075 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1076
1077 const activity = yield* cli.getPullRequestActivity(pullRequestInput);
1078
1079 expect(activity.truncated).toBe(true);
1080 }),
1081 );
1082
1083 it.effect("loads the complete hover card with one GraphQL request", () =>
1084 Effect.gen(function* () {
1085 mockedExecute.mockReturnValueOnce(
1086 Effect.succeed(
1087 output(
1088 encodeJson({
1089 data: {
1090 repository: {
1091 pullRequest: {
1092 number: 7,
1093 title: "Fast previews",
1094 url: "https://github.example/acme/web/pull/7",
1095 state: "MERGED",
1096 isDraft: false,
1097 createdAt: "2026-07-01T00:00:00Z",
1098 author: {
1099 __typename: "User",
1100 login: "octocat",
1101 name: "Octo Cat",
1102 avatarUrl: "https://github.example/avatar.png",
1103 },
1104 },
1105 },
1106 },
1107 }),
1108 ),
1109 ),
1110 );
1111 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1112 const preview = yield* cli.getPullRequestPreview({
1113 cwd: "/w",
1114 repository: "acme/web",
1115 host: "github.example",
1116 number: 7,
1117 });
1118 expect(preview).toEqual({
1119 number: 7,
1120 title: "Fast previews",
1121 url: "https://github.example/acme/web/pull/7",
1122 state: "merged",
1123 isDraft: false,
1124 createdAt: "2026-07-01T00:00:00Z",
1125 author: {
1126 login: "octocat",
1127 name: "Octo Cat",
1128 avatarUrl: "https://github.example/avatar.png",
1129 },
1130 });
1131 expect(mockedExecute).toHaveBeenCalledTimes(1);
1132 expect(callAt(0)).toMatchObject({ kind: "graphql", host: "github.example" });
1133 }),
1134 );
1135
1136 it.effect("coalesces concurrent identity verification for the same host and credential", () =>
1137 Effect.gen(function* () {
1138 mockedExecute.mockImplementation(() =>
1139 Effect.yieldNow.pipe(Effect.as(output('{"id":123,"login":"viewer"}'))),
1140 );
1141 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1142 const results = yield* Effect.all(
1143 Array.from({ length: 4 }, () =>
1144 cli.getRoutingIdentity({ cwd: "/w", host: "github.identity-flight.test" }),
1145 ),
1146 { concurrency: 4 },
1147 );
1148 expect(results).toEqual(
1149 Array.from({ length: 4 }, () => ({ accountId: "123", viewer: "viewer" })),
1150 );
1151 expect(mockedExecute).toHaveBeenCalledTimes(1);
1152 expect(pathAt(0)).toBe("user");
1153 }),
1154 );
1155
1156 it.effect(
1157 "lets another identity reader continue when the first verification is interrupted",
1158 () =>
1159 Effect.gen(function* () {
1160 const firstStarted = yield* Deferred.make<void>();
1161 let verifications = 0;
1162 mockedExecute.mockImplementation(() =>
1163 Effect.gen(function* () {
1164 if (++verifications === 1) {
1165 yield* Deferred.succeed(firstStarted, undefined);
1166 return yield* Effect.never;
1167 }
1168 return output('{"id":123,"login":"viewer"}');
1169 }),
1170 );
1171 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1172 const input = { cwd: "/w", host: "github.identity-cancel.test" };
1173 const first = yield* cli.getRoutingIdentity(input).pipe(Effect.forkChild);
1174 yield* Deferred.await(firstStarted);
1175 const second = yield* cli.getRoutingIdentity(input).pipe(Effect.forkChild);
1176 yield* Effect.yieldNow;
1177 yield* Fiber.interrupt(first);
1178 expect(yield* Fiber.join(second)).toEqual({ accountId: "123", viewer: "viewer" });
1179 expect(verifications).toBe(2);
1180 }),
1181 );
1182
1183 it.effect("reads linked pull requests on one host together, filed back by position", () =>
1184 Effect.gen(function* () {
1185 const node = (number: number) => ({
1186 number,
1187 title: `Pull request ${number}`,
1188 url: `https://github.com/acme/web/pull/${number}`,
1189 author: {
1190 __typename: "User",
1191 login: "octocat",
1192 name: "Octo Cat",
1193 avatarUrl: "https://avatars.githubusercontent.com/u/1",
1194 },
1195 baseRefName: "main",
1196 headRefName: `feat/${number}`,
1197 state: "OPEN",
1198 isDraft: false,
1199 mergeable: "MERGEABLE",
1200 reviewDecision: null,
1201 latestReviews: {
1202 nodes: [
1203 {
1204 state: "APPROVED",
1205 isMinimized: false,
1206 author: { __typename: "User", login: "reviewer" },
1207 },
1208 ],
1209 },
1210 additions: 12,
1211 deletions: 3,
1212 changedFiles: 2,
1213 updatedAt: "2026-08-24T12:34:56.000Z",
1214 mergedAt: null,
1215 closedAt: null,
1216 commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] },
1217 });
1218 mockedExecute.mockReturnValueOnce(
1219 Effect.succeed(
1220 output(
1221 encodeJson({
1222 data: {
1223 _0_repository: { pullRequest: node(7) },
1224 _1_repository: { pullRequest: node(8) },
1225 },
1226 }),
1227 ),
1228 ),
1229 );
1230 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1231
1232 const reads = yield* Effect.forEach(
1233 [7, 8],
1234 (number) =>
1235 cli.getPullRequestSummary({
1236 cwd: "/w",
1237 repository: "acme/web",
1238 host: "github.com",
1239 number,
1240 }),
1241 { concurrency: "unbounded" },
1242 ).pipe(Effect.forkChild);
1243 yield* TestClock.adjust("10 millis");
1244 const [seven, eight] = yield* Fiber.join(reads);
1245
1246 assert.deepStrictEqual(
1247 {
1248 number: seven?.number,
1249 state: seven?.state,
1250 headBranch: seven?.headBranch,
1251 author: seven?.author?.login,
1252 changedFiles: seven?.changedFiles,
1253 reviewDecision: seven?.reviewDecision,
1254 checksState: seven?.checksState,
1255 mergeability: seven?.mergeability,
1256 },
1257 {
1258 number: 7,
1259 state: "open",
1260 headBranch: "feat/7",
1261 author: "octocat",
1262 changedFiles: 2,
1263 reviewDecision: "approved",
1264 checksState: "passing",
1265 mergeability: "mergeable",
1266 },
1267 );
1268 assert.strictEqual(eight?.headBranch, "feat/8");
1269 expect(mockedExecute).toHaveBeenCalledOnce();
1270 expect(queryAt(0)).toContain(
1271 "_0_repository:repository(owner:$_0_owner name:$_0_name){pullRequest(number:$_0_number)",
1272 );
1273 expect(varsAt(0)).toMatchObject({
1274 _0_owner: "acme",
1275 _0_name: "web",
1276 _0_number: 7,
1277 _0_stacks: true,
1278 _1_number: 8,
1279 });
1280 }),
1281 );
1282
1283 it.effect(
1284 "fails only the pull request GitHub cannot find, and answers the rest of its batch",
1285 () =>
1286 Effect.gen(function* () {
1287 mockedExecute.mockReturnValueOnce(
1288 Effect.succeed(
1289 output(
1290 encodeJson({
1291 data: {
1292 _0_repository: { pullRequest: null },
1293 _1_repository: {
1294 pullRequest: {
1295 number: 8,
1296 title: "Still here",
1297 url: "https://github.com/acme/web/pull/8",
1298 author: null,
1299 baseRefName: "main",
1300 headRefName: "feat/eight",
1301 state: "OPEN",
1302 isDraft: false,
1303 mergeable: "MERGEABLE",
1304 reviewDecision: null,
1305 latestReviews: { nodes: [] },
1306 additions: 1,
1307 deletions: 1,
1308 changedFiles: 1,
1309 updatedAt: "2026-08-24T12:34:56.000Z",
1310 mergedAt: null,
1311 closedAt: null,
1312 commits: { nodes: [] },
1313 stack: null,
1314 stackEntry: null,
1315 },
1316 },
1317 },
1318 errors: [
1319 {
1320 type: "NOT_FOUND",
1321 path: ["_0_repository", "pullRequest"],
1322 message: "Could not resolve to a PullRequest with the number of 7.",
1323 },
1324 ],
1325 }),
1326 ),
1327 ),
1328 );
1329 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1330
1331 const reads = yield* Effect.forEach(
1332 [7, 8],
1333 (number) =>
1334 cli
1335 .getPullRequestSummary({
1336 cwd: "/w",
1337 repository: "acme/web",
1338 host: "github.com",
1339 number,
1340 })
1341 .pipe(Effect.result),
1342 { concurrency: "unbounded" },
1343 ).pipe(Effect.forkChild);
1344 yield* TestClock.adjust("10 millis");
1345 const [seven, eight] = yield* Fiber.join(reads);
1346
1347 expect(Result.isFailure(seven!) ? seven.failure._tag : null).toBe("GitHubApiNotFoundError");
1348 expect(Result.isSuccess(eight!) ? eight.success.headBranch : null).toBe("feat/eight");
1349 expect(mockedExecute).toHaveBeenCalledOnce();
1350 expect(callAt(0)).toMatchObject({ kind: "graphql", partial: true });
1351 }),
1352 );
1353
1354 it.effect("reads the stack a pull request is in through the stacks preview, on its host", () =>
1355 Effect.gen(function* () {
1356 mockedExecute.mockReturnValueOnce(
1357 Effect.succeed(
1358 output(
1359 encodeJson([
1360 {
1361 id: 42,
1362 number: 3,
1363 url: "https://api.github.com/repos/acme/web/stacks/3",
1364 base: { ref: "main" },
1365 pull_requests: [
1366 {
1367 number: 6,
1368 head: { ref: "feat/one" },
1369 state: "closed",
1370 merged_at: "2026-09-02",
1371 },
1372 { number: 7, head: { ref: "feat/two" }, state: "open", merged_at: null },
1373 ],
1374 },
1375 ]),
1376 ),
1377 ),
1378 );
1379 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1380
1381 const stack = yield* cli.getPullRequestStack({
1382 cwd: "/w",
1383 repository: "acme/web",
1384 host: "ghe.example.com",
1385 number: 7,
1386 });
1387
1388 assert.deepStrictEqual(stack, {
1389 id: "42",
1390 number: 3,
1391 url: "https://api.github.com/repos/acme/web/stacks/3",
1392 base: "main",
1393 layers: [
1394 { number: 6, headBranch: "feat/one", state: "merged" },
1395 { number: 7, headBranch: "feat/two", state: "open" },
1396 ],
1397 });
1398 expect(callAt(0)).toMatchObject({
1399 kind: "rest",
1400 host: "ghe.example.com",
1401 path: "repos/acme/web/stacks?pull_request=7",
1402 });
1403 }),
1404 );
1405
1406 it.effect("revalidates a polled stack, per credential, so an unchanged one costs no quota", () =>
1407 Effect.gen(function* () {
1408 const listing = encodeJson([
1409 {
1410 number: 4,
1411 url: "https://api.github.com/repos/acme/poll/stacks/4",
1412 base: { ref: "main" },
1413 pull_requests: [
1414 { number: 9, head: { ref: "feat/nine" }, state: "open", merged_at: null },
1415 ],
1416 },
1417 ]);
1418 const read = Effect.flatMap(GitHubPullRequestApi.GitHubPullRequestApi, (cli) =>
1419 cli.getPullRequestStack({
1420 cwd: "/w",
1421 repository: "acme/poll",
1422 host: "github.com",
1423 number: 9,
1424 }),
1425 );
1426 mockedExecute.mockReturnValueOnce(
1427 Effect.succeed(output(listing, false, false, { etag: 'W/"v1"' })),
1428 );
1429 const first = yield* read;
1430 mockedExecute.mockReturnValueOnce(Effect.succeed(output("", false, false, {}, 304)));
1431 const second = yield* read;
1432 mockedCredential.mockImplementationOnce(() =>
1433 Effect.succeed({ token: Redacted.make("other"), fingerprint: "github.com:other" }),
1434 );
1435 mockedExecute.mockReturnValueOnce(Effect.succeed(output(listing)));
1436 yield* read;
1437
1438 assert.deepStrictEqual(second, first);
1439 expect(callAt(0)).not.toHaveProperty("ifNoneMatch");
1440 expect(callAt(1)).toMatchObject({ ifNoneMatch: 'W/"v1"' });
1441 // Another account never revalidates the first account's answer.
1442 expect(callAt(2)).not.toHaveProperty("ifNoneMatch");
1443 }),
1444 );
1445
1446 it.effect("reads a host that refuses the stacks preview as not stacked", () =>
1447 Effect.gen(function* () {
1448 mockedExecute.mockReturnValueOnce(
1449 Effect.fail(
1450 new GitHubRequestPolicy.GitHubApiNotFoundError({
1451 host: "github.com",
1452 operation: "getPullRequestStack",
1453 }),
1454 ),
1455 );
1456 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1457
1458 const stack = yield* cli.getPullRequestStack({
1459 cwd: "/w",
1460 repository: "acme/web",
1461 host: "github.com",
1462 number: 7,
1463 });
1464
1465 assert.isNull(stack);
1466 }),
1467 );
1468
1469 it.effect("does not read a refused credential as an unstacked pull request", () =>
1470 Effect.gen(function* () {
1471 mockedExecute.mockReturnValueOnce(
1472 Effect.fail(
1473 new GitHubRequestPolicy.GitHubApiAuthenticationError({
1474 host: "github.com",
1475 operation: "getPullRequestStack",
1476 }),
1477 ),
1478 );
1479 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1480
1481 const error = yield* Effect.flip(
1482 cli.getPullRequestStack({
1483 cwd: "/w",
1484 repository: "acme/web",
1485 host: "github.com",
1486 number: 7,
1487 }),
1488 );
1489
1490 assert.strictEqual(error._tag, "GitHubApiAuthenticationError");
1491 }),
1492 );
1493
1494 it.effect("preserves transient stack failures instead of reporting no stack", () =>
1495 Effect.gen(function* () {
1496 const failure = new GitHubRequestPolicy.GitHubApiResponseError({
1497 host: "github.com",
1498 operation: "getPullRequestStack",
1499 status: 503,
1500 });
1501 mockedExecute.mockReturnValueOnce(Effect.fail(failure));
1502 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1503 const error = yield* Effect.flip(
1504 cli.getPullRequestStack({
1505 cwd: "/w",
1506 repository: "acme/web",
1507 host: "github.com",
1508 number: 7,
1509 }),
1510 );
1511 assert.strictEqual(error, failure);
1512 }),
1513 );
1514
1515 it.effect("reports truncation from the extra row, counted before decoding", () =>
1516 Effect.gen(function* () {
1517 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(11, 1))));
1518 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1519
1520 const batch = yield* cli.listPullRequests({
1521 cwd: "/w",
1522 repository: "acme/web",
1523 host: "github.com",
1524 state: "open",
1525 involvement: "all",
1526 viewer: "bilal",
1527 limit: 10,
1528 });
1529
1530 assert.strictEqual(batch.items.length, 10);
1531 assert.isTrue(batch.truncated);
1532 }),
1533 );
1534
1535 it.effect("reports truncation when GitHub repeats a cursor before the page is full", () =>
1536 Effect.gen(function* () {
1537 const repeating = output(
1538 encodeJson({
1539 data: {
1540 search: {
1541 pageInfo: { hasNextPage: true, endCursor: "same" },
1542 nodes: rows(100, 1),
1543 },
1544 },
1545 }),
1546 );
1547 mockedExecute.mockReturnValue(Effect.succeed(repeating));
1548 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1549
1550 const batch = yield* cli.listPullRequests({
1551 cwd: "/w",
1552 repository: "acme/web",
1553 host: "github.com",
1554 state: "open",
1555 involvement: "all",
1556 viewer: "bilal",
1557 limit: 250,
1558 });
1559
1560 assert.strictEqual(mockedExecute.mock.calls.length, 2);
1561 assert.isTrue(batch.truncated);
1562 }),
1563 );
1564
1565 /**
1566 * Lists a repository GitHub will not return, answering credential lookups in turn (the last
1567 * answer repeats; `undefined` is no credential), and returns the error with the tokens sent.
1568 */
1569 const listUnreadableRepository = (
1570 ...lookups: ReadonlyArray<
1571 | { readonly token: string; readonly source: GitHubCredentials.GitHubCredentialSource }
1572 | undefined
1573 >
1574 ) => {
1575 mockedExecute.mockClear();
1576 let lookup = 0;
1577 mockedCredential.mockImplementation((host) =>
1578 Effect.suspend(() => {
1579 const held = lookups[Math.min(lookup++, lookups.length - 1)];
1580 return held === undefined
1581 ? Effect.fail(
1582 new GitHubRequestPolicy.GitHubApiAuthenticationError({
1583 host,
1584 operation: "credential",
1585 }),
1586 )
1587 : Effect.succeed({
1588 token: Redacted.make(held.token),
1589 fingerprint: `${host}:${held.token}`,
1590 source: held.source,
1591 });
1592 }),
1593 );
1594 route(
1595 ["PullRequestSearch", { data: { search: { pageInfo: lastPage, nodes: [] } } }],
1596 [
1597 "PullRequestList",
1598 {
1599 data: { repository: null },
1600 errors: [
1601 {
1602 type: "NOT_FOUND",
1603 path: ["repository"],
1604 message: "Could not resolve to a Repository with the name 'acme/private'.",
1605 },
1606 ],
1607 },
1608 ],
1609 );
1610 return GitHubPullRequestProvider.make.pipe(
1611 Effect.flatMap((provider) =>
1612 Effect.flip(
1613 provider.listChangeRequests({
1614 cwd: "/w",
1615 repository: "acme/private",
1616 host: "github.com",
1617 state: "open",
1618 involvement: "all",
1619 viewer: "bilal",
1620 limit: 10,
1621 }),
1622 ),
1623 ),
1624 Effect.map((error) => ({
1625 error,
1626 sentWith: mockedExecute.mock.calls.map(([call]) =>
1627 call.kind === "graphql" ? call.authorization : undefined,
1628 ),
1629 })),
1630 );
1631 };
1632
1633 it.effect("names the credential GitHub would not return a repository to", () =>
1634 Effect.gen(function* () {
1635 // The saved token is replaced mid-read; every request still goes out with the one named.
1636 const saved = yield* listUnreadableRepository(
1637 { token: "first", source: "settings" },
1638 { token: "replaced", source: "settings" },
1639 );
1640 expect(saved.error.accessHint).toContain("saved GitHub token");
1641 assert.isAbove(saved.sentWith.length, 1);
1642 for (const authorization of saved.sentWith) expect(authorization).toContain("first");
1643
1644 // The policy hands what the app cannot see to the gh login, which GitHub refuses too.
1645 mockedAppToken.mockReturnValue(Effect.succeedSome("app"));
1646 const app = { token: "app", source: "app" } as const;
1647 const gh = { token: "personal", source: "gh" } as const;
1648 const retried = yield* listUnreadableRepository(app, gh);
1649 expect(retried.error.accessHint).toContain("gh login");
1650 expect(retried.sentWith).toEqual(["Bearer app", "Bearer app", "Bearer personal"]);
1651
1652 // With no gh login when the app is refused, the app made the last request; a login that
1653 // turns up afterwards is not named.
1654 const appOnly = yield* listUnreadableRepository(app, undefined, gh);
1655 assert.isUndefined(appOnly.error.accessHint);
1656 expect(appOnly.sentWith).toEqual(["Bearer app", "Bearer app"]);
1657 }),
1658 );
1659
1660 it.effect("carries every repository and every qualifier into one search", () =>
1661 Effect.gen(function* () {
1662 mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
1663 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1664
1665 yield* cli.searchPullRequests({
1666 cwd: "/w",
1667 host: "github.com",
1668 repositories: ["acme/web", "pingdotgg/t3code"],
1669 state: "closed",
1670 involvement: "reviewing",
1671 viewer: "bilal",
1672 limit: 10,
1673 query: "pull requests page",
1674 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 10 },
1675 });
1676
1677 assert.strictEqual(mockedExecute.mock.calls.length, 1);
1678 assert.strictEqual(
1679 searchQueryOfCall(0),
1680 'is:pr is:closed is:unmerged review-requested:bilal "pull requests page" ' +
1681 "updated:<=2026-07-02T00:00:00Z sort:updated-desc repo:acme/web repo:pingdotgg/t3code",
1682 );
1683 }),
1684 );
1685
1686 it.effect("keeps a searched-for qualifier inside the phrase", () =>
1687 Effect.gen(function* () {
1688 mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
1689 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1690
1691 yield* cli.searchPullRequests({
1692 cwd: "/w",
1693 host: "github.com",
1694 repositories: ["acme/web"],
1695 state: "open",
1696 involvement: "all",
1697 viewer: "bilal",
1698 limit: 10,
1699 query: 'x" is:merged repo:evil/repo',
1700 });
1701
1702 assert.strictEqual(
1703 searchQueryOfCall(0),
1704 'is:pr is:open "x\\" is:merged repo:evil/repo" sort:updated-desc repo:acme/web',
1705 );
1706 }),
1707 );
1708
1709 it.effect("refuses to search for a repository GitHub cannot address", () =>
1710 Effect.gen(function* () {
1711 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1712
1713 const failure = yield* Effect.flip(
1714 cli.searchPullRequests({
1715 cwd: "/w",
1716 host: "github.com",
1717 repositories: ["acme/web", "acme/web is:merged"],
1718 state: "open",
1719 involvement: "all",
1720 viewer: "bilal",
1721 limit: 10,
1722 }),
1723 );
1724
1725 assert.strictEqual(failure._tag, "GitHubRepositorySelectorError");
1726 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1727 }),
1728 );
1729
1730 it.effect("files each searched row under the repository it came from", () =>
1731 Effect.gen(function* () {
1732 mockedExecute.mockReturnValue(
1733 Effect.succeed(
1734 searchPage([
1735 searchItem(7, "acme/web", "2026-07-03T00:00:00Z"),
1736 searchItem(9, "pingdotgg/t3code", "2026-07-02T00:00:00Z"),
1737 {},
1738 ]),
1739 ),
1740 );
1741 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1742
1743 const batch = yield* cli.searchPullRequests({
1744 cwd: "/w",
1745 host: "github.com",
1746 repositories: ["acme/web", "pingdotgg/t3code"],
1747 state: "open",
1748 involvement: "all",
1749 viewer: "bilal",
1750 limit: 10,
1751 });
1752
1753 assert.deepStrictEqual(
1754 batch.items.map((item) => [item.repository, item.number, item.author?.avatarUrl]),
1755 [
1756 ["acme/web", 7, "https://avatars/octocat"],
1757 ["pingdotgg/t3code", 9, "https://avatars/octocat"],
1758 ],
1759 );
1760 assert.deepStrictEqual(
1761 batch.items.map((item) => [item.additions, item.deletions]),
1762 [
1763 [0, 0],
1764 [0, 0],
1765 ],
1766 );
1767 assert.deepStrictEqual(batch.items[0]?.labels, [
1768 { name: "bug", color: "ff0000", description: "Something is broken" },
1769 ]);
1770 assert.isFalse(batch.truncated);
1771 }),
1772 );
1773
1774 it.effect("reports truncation from the extra row, and from a page GitHub says has more", () =>
1775 Effect.gen(function* () {
1776 mockedExecute
1777 .mockReturnValueOnce(
1778 Effect.succeed(
1779 searchPage([
1780 searchItem(1, "acme/web", "2026-07-03T00:00:00Z"),
1781 searchItem(2, "acme/web", "2026-07-02T00:00:00Z"),
1782 searchItem(3, "acme/web", "2026-07-01T00:00:00Z"),
1783 ]),
1784 ),
1785 )
1786 .mockReturnValueOnce(
1787 Effect.succeed(searchPage([searchItem(1, "acme/web", "2026-07-03T00:00:00Z")], true)),
1788 );
1789 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1790 const read = () =>
1791 cli.searchPullRequests({
1792 cwd: "/w",
1793 host: "github.com",
1794 repositories: ["acme/web"],
1795 state: "open",
1796 involvement: "all",
1797 viewer: "bilal",
1798 limit: 2,
1799 });
1800
1801 const overflowing = yield* read();
1802 const capped = yield* read();
1803
1804 assert.strictEqual(overflowing.items.length, 2);
1805 assert.isTrue(overflowing.truncated);
1806 assert.isTrue(capped.truncated);
1807 }),
1808 );
1809
1810 it.effect("enriches only the visible fallback rows after filtering and widening", () =>
1811 Effect.gen(function* () {
1812 mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
1813 mockedExecute.mockReturnValueOnce(
1814 Effect.succeed(output(listedPullRequests(3, 1, () => ({ isDraft: true })))),
1815 );
1816 mockedExecute.mockReturnValueOnce(
1817 Effect.succeed(output(listedPullRequests(6, 1, (number) => ({ isDraft: number < 4 })))),
1818 );
1819 mockedStackMemberships.mockReturnValueOnce(
1820 Effect.succeed(
1821 output(
1822 encodeJson({
1823 data: {
1824 _0_repository: {
1825 pullRequest: {
1826 stack: { number: 3, size: 2, baseRefName: "main" },
1827 stackEntry: { position: 1 },
1828 },
1829 },
1830 _1_repository: { pullRequest: { stack: null, stackEntry: null } },
1831 },
1832 }),
1833 ),
1834 ),
1835 );
1836 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1837 const batch = yield* cli.listPullRequests({
1838 cwd: "/w",
1839 repository: "acme/web",
1840 host: "github.com",
1841 state: "open",
1842 involvement: "all",
1843 viewer: "bilal",
1844 limit: 2,
1845 filters: { draft: "hide" },
1846 });
1847 expect(batch.items.map((item) => item.number)).toEqual([4, 5]);
1848 expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, base: "main", position: 1 });
1849 expect(batch.items[1]?.stack).toBeUndefined();
1850 expect(batch.truncated).toBe(true);
1851 expect(batch.continues).toBe(false);
1852 expect(mockedStackMemberships).toHaveBeenCalledTimes(1);
1853 const membership = mockedStackMemberships.mock.calls[0]?.[0];
1854 const numbers = Object.entries(
1855 membership?.kind === "graphql" ? (membership.variables ?? {}) : {},
1856 )
1857 .filter(([name]) => name.endsWith("_number"))
1858 .map(([, number]) => number);
1859 expect(numbers).toEqual([4, 5]);
1860 }),
1861 );
1862
1863 it.effect("batches membership reads and keeps successful rows when one chunk fails", () =>
1864 Effect.gen(function* () {
1865 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(27, 1))));
1866 mockedStackMemberships.mockImplementation((input) =>
1867 input.kind === "graphql" && Object.values(input.variables ?? {}).includes(26)
1868 ? Effect.fail(
1869 new GitHubRequestPolicy.GitHubApiResponseError({
1870 host: "github.com",
1871 operation: "listPullRequestStackMemberships",
1872 status: 502,
1873 }),
1874 )
1875 : Effect.succeed(
1876 output(
1877 encodeJson({
1878 data: Object.fromEntries(
1879 Object.keys(input.kind === "graphql" ? (input.variables ?? {}) : {})
1880 .filter((name) => name.endsWith("_number"))
1881 .map((name, index) => [
1882 name.replace(/number$/, "repository"),
1883 {
1884 pullRequest:
1885 index === 0
1886 ? {
1887 stack: { number: 3, size: 2, baseRefName: "main" },
1888 stackEntry: { position: 1 },
1889 }
1890 : { stack: null, stackEntry: null },
1891 },
1892 ]),
1893 ),
1894 }),
1895 ),
1896 ),
1897 );
1898 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1899 const batch = yield* cli.listPullRequests({
1900 cwd: "/w",
1901 repository: "acme/web",
1902 host: "github.com",
1903 state: "open",
1904 involvement: "all",
1905 viewer: "bilal",
1906 limit: 26,
1907 });
1908 expect(batch.items.map((item) => item.number)).toEqual(
1909 Array.from({ length: 26 }, (_, i) => i + 1),
1910 );
1911 expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, base: "main", position: 1 });
1912 expect(batch.items[25]?.stack).toBeUndefined();
1913 expect(batch.truncated).toBe(true);
1914 expect(batch.continues).toBe(true);
1915 expect(mockedStackMemberships).toHaveBeenCalledTimes(2);
1916 }),
1917 );
1918
1919 it.effect("reads the line counts in chunks, and files them back by position", () =>
1920 Effect.gen(function* () {
1921 const changeRequests = Array.from({ length: 26 }, (_, index) => ({
1922 repository: "acme/web",
1923 number: index + 1,
1924 }));
1925 mockedExecute.mockImplementation((call) =>
1926 Effect.succeed(
1927 output(
1928 encodeJson({
1929 data: Object.fromEntries(
1930 Object.keys(call.kind === "graphql" ? (call.variables ?? {}) : {})
1931 .filter((name) => name.endsWith("_number"))
1932 .map((name, index) => [
1933 name.replace(/number$/, "repository"),
1934 { pullRequest: index === 0 ? { additions: 4, deletions: 1 } : null },
1935 ]),
1936 ),
1937 }),
1938 ),
1939 ),
1940 );
1941 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1942
1943 const stats = yield* cli.listPullRequestStats({
1944 cwd: "/w",
1945 host: "github.com",
1946 changeRequests,
1947 });
1948
1949 assert.strictEqual(mockedExecute.mock.calls.length, 2);
1950 assert.deepStrictEqual(stats, [
1951 { repository: "acme/web", number: 1, additions: 4, deletions: 1 },
1952 { repository: "acme/web", number: 26, additions: 4, deletions: 1 },
1953 ]);
1954 expect(queryAt(0)).toContain("_0_repository:repository(owner:$_0_owner name:$_0_name)");
1955 expect(varsAt(0)).toMatchObject({ _0_owner: "acme", _0_name: "web", _24_number: 25 });
1956 }),
1957 );
1958
1959 it.effect("carries the further narrowings into the search as qualifiers", () =>
1960 Effect.gen(function* () {
1961 mockedExecute.mockImplementation((call) =>
1962 Effect.succeed(
1963 call.kind === "graphql" && call.operationName === "PullRequestList"
1964 ? emptyList()
1965 : emptySearch(),
1966 ),
1967 );
1968 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
1969
1970 yield* cli.listPullRequests({
1971 cwd: "/w",
1972 repository: "acme/web",
1973 host: "github.com",
1974 state: "open",
1975 involvement: "all",
1976 viewer: "bilal",
1977 limit: 10,
1978 filters: {
1979 draft: "hide",
1980 review: "changes-requested",
1981 checks: "failing",
1982 labels: [["needs design"], ['quo"te']],
1983 excludedLabels: ["wip"],
1984 author: "octocat",
1985 },
1986 });
1987
1988 expect(searchOfCall(0)).toBe(
1989 'is:pr is:open label:"needs design" label:"quote" -label:"wip" author:"octocat" ' +
1990 "draft:false review:changes_requested status:failure sort:updated-desc repo:acme/web",
1991 );
1992 }),
1993 );
1994
1995 it.effect('resolves an author filter of "me" to the viewer, not the literal word', () =>
1996 Effect.gen(function* () {
1997 mockedExecute.mockImplementation((call) =>
1998 Effect.succeed(
1999 call.kind === "graphql" && call.operationName === "PullRequestList"
2000 ? emptyList()
2001 : emptySearch(),
2002 ),
2003 );
2004 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2005
2006 yield* cli.listPullRequests({
2007 cwd: "/w",
2008 repository: "acme/web",
2009 host: "github.com",
2010 state: "open",
2011 involvement: "all",
2012 viewer: "bilal",
2013 limit: 10,
2014 filters: { author: "me" },
2015 });
2016
2017 expect(searchOfCall(0)).toBe('is:pr is:open author:"bilal" sort:updated-desc repo:acme/web');
2018 }),
2019 );
2020
2021 it.effect("sends one label qualifier per group, its names joined the way GitHub ors them", () =>
2022 Effect.gen(function* () {
2023 mockedExecute.mockImplementation((call) =>
2024 Effect.succeed(
2025 call.kind === "graphql" && call.operationName === "PullRequestList"
2026 ? emptyList()
2027 : emptySearch(),
2028 ),
2029 );
2030 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2031
2032 yield* cli.listPullRequests({
2033 cwd: "/w",
2034 repository: "acme/web",
2035 host: "github.com",
2036 state: "open",
2037 involvement: "all",
2038 viewer: "bilal",
2039 limit: 10,
2040 filters: { labels: [["size:S", "size:XS"], ["bug"]] },
2041 });
2042
2043 expect(searchOfCall(0)).toBe(
2044 'is:pr is:open label:"size:S","size:XS" label:"bug" sort:updated-desc repo:acme/web',
2045 );
2046 }),
2047 );
2048
2049 it.effect(
2050 "falls back for a repository the index does not cover under a checks filter, keeping only the matching rows",
2051 () =>
2052 Effect.gen(function* () {
2053 mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
2054 mockedExecute.mockReturnValueOnce(
2055 Effect.succeed(
2056 output(
2057 listedPullRequests(2, 1, (number) => ({
2058 checks: number === 1 ? "SUCCESS" : "FAILURE",
2059 })),
2060 ),
2061 ),
2062 );
2063 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2064
2065 const batch = yield* cli.listPullRequests({
2066 cwd: "/w",
2067 repository: "acme/web",
2068 host: "github.com",
2069 state: "open",
2070 involvement: "all",
2071 viewer: "bilal",
2072 limit: 10,
2073 filters: { checks: "passing" },
2074 });
2075
2076 expect(searchOfCall(1)).toBeUndefined();
2077 assert.deepStrictEqual(
2078 batch.items.map((item) => item.number),
2079 [1],
2080 );
2081 }),
2082 );
2083
2084 it.effect("fails a checks filter for a row whose checks are still pending", () =>
2085 Effect.gen(function* () {
2086 mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
2087 mockedExecute.mockReturnValueOnce(
2088 Effect.succeed(output(listedPullRequests(1, 1, () => ({ checks: "PENDING" })))),
2089 );
2090 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2091
2092 const batch = yield* cli.listPullRequests({
2093 cwd: "/w",
2094 repository: "acme/web",
2095 host: "github.com",
2096 state: "open",
2097 involvement: "all",
2098 viewer: "bilal",
2099 limit: 10,
2100 filters: { checks: "passing" },
2101 });
2102
2103 assert.deepStrictEqual(batch.items, []);
2104 }),
2105 );
2106
2107 it.effect("escapes a backslash before the quote it would otherwise let out", () =>
2108 Effect.gen(function* () {
2109 mockedExecute.mockImplementation((call) =>
2110 Effect.succeed(
2111 call.kind === "graphql" && call.operationName === "PullRequestList"
2112 ? emptyList()
2113 : emptySearch(),
2114 ),
2115 );
2116 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2117
2118 yield* cli.listPullRequests({
2119 cwd: "/w",
2120 repository: "acme/web",
2121 host: "github.com",
2122 state: "open",
2123 involvement: "all",
2124 viewer: "bilal",
2125 limit: 10,
2126 query: String.raw`a\" is:merged`,
2127 });
2128
2129 expect(searchOfCall(0)).toBe(
2130 String.raw`is:pr is:open "a\\\" is:merged" sort:updated-desc repo:acme/web`,
2131 );
2132 }),
2133 );
2134
2135 it.effect("carries on from the instant the last slice ended on", () =>
2136 Effect.gen(function* () {
2137 mockedExecute.mockReturnValue(Effect.succeed(output(pullRequests(3, 1))));
2138 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2139
2140 const batch = yield* cli.listPullRequests({
2141 cwd: "/w",
2142 repository: "acme/web",
2143 host: "github.com",
2144 state: "open",
2145 involvement: "all",
2146 viewer: "bilal",
2147 limit: 10,
2148 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 10 },
2149 });
2150
2151 expect(searchOfCall(0)).toBe(
2152 "is:pr is:open updated:<=2026-07-02T00:00:00Z sort:updated-desc repo:acme/web",
2153 );
2154 assert.isTrue(batch.continues);
2155 }),
2156 );
2157
2158 it.effect("skips the rows already delivered at a tied boundary before applying the limit", () =>
2159 Effect.gen(function* () {
2160 // Twenty pull requests share the boundary instant, then five are older. GitHub's search
2161 // has no qualifier for a row number, so the boundary always comes back from its start.
2162 const repository = { nameWithOwner: "acme/web" };
2163 const tied = rows(20, 1, () => ({ repository }));
2164 const older = rows(5, 21, () => ({ updatedAt: "2026-07-01T00:00:00Z", repository }));
2165 mockedExecute.mockImplementation((call) => {
2166 const variables = call.kind === "graphql" ? (call.variables ?? {}) : {};
2167 const q = String(variables["q"] ?? "");
2168 const bound = /updated:<=(\S+)/.exec(q)?.[1];
2169 const matching = [...tied, ...older].filter(
2170 (row) => bound === undefined || String(row["updatedAt"]) <= bound,
2171 );
2172 const start = variables["after"] == null ? 0 : Number(variables["after"]);
2173 const end = start + Number(variables["first"]);
2174 const hasNextPage = end < matching.length;
2175 return Effect.succeed(
2176 output(
2177 encodeJson({
2178 data: {
2179 search: {
2180 pageInfo: { hasNextPage, endCursor: hasNextPage ? String(end) : null },
2181 nodes: matching.slice(start, end),
2182 },
2183 },
2184 }),
2185 ),
2186 );
2187 });
2188 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2189
2190 const batch = yield* cli.listPullRequests({
2191 cwd: "/w",
2192 repository: "acme/web",
2193 host: "github.com",
2194 state: "open",
2195 involvement: "all",
2196 viewer: "bilal",
2197 limit: 10,
2198 cursor: {
2199 updatedBefore: "2026-07-02T00:00:00Z",
2200 delivered: 10,
2201 seenAt: Array.from({ length: 10 }, (_, index) => index + 1),
2202 },
2203 });
2204
2205 expect(batch.items.map((item) => item.number)).toEqual([
2206 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2207 ]);
2208
2209 const across = yield* cli.searchPullRequests({
2210 cwd: "/w",
2211 host: "github.com",
2212 repositories: ["acme/web"],
2213 state: "open",
2214 involvement: "all",
2215 viewer: "bilal",
2216 limit: 10,
2217 cursor: {
2218 updatedBefore: "2026-07-02T00:00:00Z",
2219 delivered: 10,
2220 seenAt: Array.from({ length: 10 }, (_, index) => ({
2221 repository: "acme/web",
2222 number: index + 1,
2223 })),
2224 },
2225 });
2226 expect(across.items.map((item) => item.number)).toEqual([
2227 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2228 ]);
2229
2230 // Rows seen earlier that no longer match must not count as skipped, or the rest is lost.
2231 const moved = { updatedBefore: "2026-07-01T00:00:00Z", delivered: 10 };
2232 const listedPastMoved = yield* cli.listPullRequests({
2233 cwd: "/w",
2234 repository: "acme/web",
2235 host: "github.com",
2236 state: "open",
2237 involvement: "all",
2238 viewer: "bilal",
2239 limit: 3,
2240 cursor: { ...moved, seenAt: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] },
2241 });
2242 const searchedPastMoved = yield* cli.searchPullRequests({
2243 cwd: "/w",
2244 host: "github.com",
2245 repositories: ["acme/web"],
2246 state: "open",
2247 involvement: "all",
2248 viewer: "bilal",
2249 limit: 3,
2250 cursor: {
2251 ...moved,
2252 seenAt: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((number) => ({
2253 repository: "acme/web",
2254 number,
2255 })),
2256 },
2257 });
2258 for (const page of [listedPastMoved, searchedPastMoved]) {
2259 expect(page.items.map((item) => item.number)).toEqual([21, 22, 23]);
2260 expect(page.truncated).toBe(true);
2261 }
2262 }),
2263 );
2264
2265 it.effect("answers a search that found nothing with nothing, not with the whole repository", () =>
2266 Effect.gen(function* () {
2267 mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
2268 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2269
2270 const batch = yield* cli.listPullRequests({
2271 cwd: "/w",
2272 repository: "acme/web",
2273 host: "github.com",
2274 state: "open",
2275 involvement: "all",
2276 viewer: "bilal",
2277 limit: 10,
2278 query: "fdsfklj",
2279 });
2280
2281 assert.strictEqual(batch.items.length, 0);
2282 assert.strictEqual(mockedExecute.mock.calls.length, 1);
2283 }),
2284 );
2285
2286 it.effect("lists the repository when GitHub's search answers with a bad gateway", () =>
2287 Effect.gen(function* () {
2288 mockedExecute.mockImplementation((call) =>
2289 Effect.succeed(
2290 matches(call, "PullRequestSearch")
2291 ? output('{"message":"Server Error"}', false, false, {}, 502)
2292 : output(listedPullRequests(2, 1)),
2293 ),
2294 );
2295 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2296
2297 const batch = yield* cli.listPullRequests({
2298 cwd: "/w",
2299 repository: "acme/web",
2300 host: "github.com",
2301 state: "open",
2302 involvement: "all",
2303 viewer: "bilal",
2304 limit: 10,
2305 });
2306
2307 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
2308 }),
2309 );
2310
2311 it.effect("fails a text search GitHub answers with a bad gateway, not with unfiltered rows", () =>
2312 Effect.gen(function* () {
2313 mockedExecute.mockImplementation((call) =>
2314 Effect.succeed(
2315 matches(call, "PullRequestSearch")
2316 ? output('{"message":"Server Error"}', false, false, {}, 502)
2317 : output(listedPullRequests(2, 1)),
2318 ),
2319 );
2320 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2321
2322 const error = yield* Effect.flip(
2323 cli.listPullRequests({
2324 cwd: "/w",
2325 repository: "acme/web",
2326 host: "github.com",
2327 state: "open",
2328 involvement: "all",
2329 viewer: "bilal",
2330 limit: 10,
2331 query: "flaky",
2332 }),
2333 );
2334
2335 expect(error).toMatchObject({ _tag: "GitHubApiResponseError", status: 502 });
2336 assert.isFalse(mockedExecute.mock.calls.some(([call]) => matches(call, "PullRequestList")));
2337 }),
2338 );
2339
2340 it.effect("keeps state and involvement filters on the search-free fallback", () =>
2341 Effect.gen(function* () {
2342 mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
2343 mockedExecute.mockReturnValueOnce(
2344 Effect.succeed(
2345 output(
2346 listedPullRequests(4, 1, (number) => ({
2347 state: number === 4 ? "OPEN" : "CLOSED",
2348 ...(number === 3 ? { mergedAt: "2026-07-03T00:00:00Z" } : {}),
2349 reviewRequests:
2350 number === 2 ? [{ slug: "platform", name: "Platform" }] : [{ login: "bilal" }],
2351 })),
2352 ),
2353 ),
2354 );
2355 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2356
2357 const batch = yield* cli.listPullRequests({
2358 cwd: "/w",
2359 repository: "acme/web",
2360 host: "github.com",
2361 state: "closed",
2362 involvement: "reviewing",
2363 viewer: "bilal",
2364 limit: 10,
2365 });
2366
2367 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
2368 expect(searchOfCall(1)).toBeUndefined();
2369 assert.isFalse(batch.continues);
2370 }),
2371 );
2372
2373 it.effect("grows the search-free fallback until it fills the filtered page", () =>
2374 Effect.gen(function* () {
2375 const unrelated = () => ({ reviewRequests: [{ login: "somebody-else" }] });
2376 mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
2377 mockedExecute.mockReturnValueOnce(
2378 Effect.succeed(output(listedPullRequests(3, 1, unrelated))),
2379 );
2380 mockedExecute.mockReturnValueOnce(
2381 Effect.succeed(
2382 output(
2383 listedPullRequests(4, 1, (number) =>
2384 number === 4 ? { reviewRequests: [{ login: "bilal" }] } : unrelated(),
2385 ),
2386 ),
2387 ),
2388 );
2389 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2390
2391 const batch = yield* cli.listPullRequests({
2392 cwd: "/w",
2393 repository: "acme/web",
2394 host: "github.com",
2395 state: "open",
2396 involvement: "reviewing",
2397 viewer: "bilal",
2398 limit: 2,
2399 });
2400
2401 expect(batch.items.map((item) => item.number)).toEqual([4]);
2402 expect(varsAt(1)["first"]).toBe(3);
2403 expect(varsAt(2)["first"]).toBe(6);
2404 assert.isFalse(batch.truncated);
2405 }),
2406 );
2407
2408 const actionState = (pullRequest: Readonly<Record<string, unknown>> = {}) => ({
2409 data: {
2410 repository: {
2411 pullRequest: {
2412 id: "PR_7",
2413 headRefOid: "abc123",
2414 isMergeQueueEnabled: false,
2415 mergeStateStatus: "BLOCKED",
2416 baseRef: { compare: { behindBy: 2 } },
2417 ...pullRequest,
2418 },
2419 },
2420 },
2421 });
2422 const mergeMessage = (body: string, isMergeQueueEnabled = false) => ({
2423 data: {
2424 repository: {
2425 pullRequest: { isMergeQueueEnabled, headRefOid: "abc123", viewerMergeBodyText: body },
2426 },
2427 },
2428 });
2429
2430 it.effect.each([
2431 { queued: false, field: "mergePullRequest", state: "MERGED", autoMergeRequest: null },
2432 {
2433 queued: true,
2434 field: "enablePullRequestAutoMerge",
2435 state: "OPEN",
2436 autoMergeRequest: { mergeMethod: "MERGE" },
2437 },
2438 ] as const)(
2439 "returns the pull request from GitHub's $field reply",
2440 ({ queued, field, state, autoMergeRequest }) =>
2441 Effect.gen(function* () {
2442 const mergedAt = state === "MERGED" ? "2026-10-27T11:59:00Z" : null;
2443 route(
2444 ["query PullRequestActionState", actionState({ isMergeQueueEnabled: queued })],
2445 [
2446 field + "(",
2447 {
2448 data: {
2449 [field]: {
2450 pullRequest: {
2451 number: 7,
2452 title: "Pull request 7",
2453 url: "https://github.com/acme/web/pull/7",
2454 headRefName: "feat/page",
2455 baseRefName: "main",
2456 state,
2457 isDraft: false,
2458 updatedAt: "2026-10-27T12:00:00Z",
2459 mergedAt,
2460 closedAt: mergedAt,
2461 headRefOid: "response-head",
2462 author: { __typename: "User", login: "alice", avatarUrl: "", name: null },
2463 autoMergeRequest,
2464 },
2465 },
2466 },
2467 },
2468 ],
2469 );
2470 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2471 expect(yield* cli.runPullRequestAction({ ...pullRequestInput, action: "merge" })).toEqual({
2472 number: 7,
2473 title: "Pull request 7",
2474 url: "https://github.com/acme/web/pull/7",
2475 headBranch: "feat/page",
2476 baseBranch: "main",
2477 state: state.toLowerCase(),
2478 isDraft: false,
2479 updatedAt: "2026-10-27T12:00:00Z",
2480 mergedAt,
2481 closedAt: mergedAt,
2482 author: { login: "alice", name: null, avatarUrl: null },
2483 headSha: "response-head",
2484 autoMergeEnabled: queued,
2485 ...(queued ? { autoMergeMethod: "merge" } : {}),
2486 });
2487 // The action-state read and the mutation; no re-read of the pull request.
2488 expect(mockedExecute).toHaveBeenCalledTimes(2);
2489 }),
2490 );
2491
2492 it.effect("succeeds without a summary when GitHub's merge reply does not decode", () =>
2493 Effect.gen(function* () {
2494 route(
2495 ["query PullRequestActionState", actionState({ isMergeQueueEnabled: false })],
2496 [
2497 "mergePullRequest(",
2498 { data: { mergePullRequest: { pullRequest: { state: "MERGING" } } } },
2499 ],
2500 );
2501 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2502 expect(
2503 yield* cli.runPullRequestAction({ ...pullRequestInput, action: "merge" }),
2504 ).toBeUndefined();
2505 }),
2506 );
2507
2508 it.effect.each([
2509 {
2510 description: "base-only write",
2511 basePermission: "WRITE",
2512 sourcePermission: "READ",
2513 headRef: { id: "REF" },
2514 expected: false,
2515 actionAllowed: false,
2516 },
2517 {
2518 description: "source-only write",
2519 basePermission: "READ",
2520 sourcePermission: "WRITE",
2521 headRef: { id: "REF" },
2522 expected: true,
2523 actionAllowed: true,
2524 },
2525 {
2526 description: "a deleted branch",
2527 basePermission: "READ",
2528 sourcePermission: "WRITE",
2529 headRef: null,
2530 expected: false,
2531 actionAllowed: true,
2532 },
2533 {
2534 description: "an unavailable source repository",
2535 basePermission: "WRITE",
2536 sourcePermission: null,
2537 headRef: { id: "REF" },
2538 expected: false,
2539 actionAllowed: false,
2540 },
2541 ])(
2542 "uses source branch access in both permission reads for $description",
2543 ({ basePermission, sourcePermission, headRef, expected, actionAllowed }) =>
2544 Effect.gen(function* () {
2545 const answer = coreResponse({
2546 headRepository:
2547 sourcePermission === null
2548 ? null
2549 : { nameWithOwner: "acme/web", viewerPermission: sourcePermission },
2550 headRef,
2551 });
2552 answer.data.repository.viewerPermission = basePermission;
2553 mockedExecute.mockReturnValue(Effect.succeed(output(encodeJson(answer))));
2554 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2555 const input = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
2556 expect((yield* cli.getViewerAccess(input)).canDeleteBranch).toBe(actionAllowed);
2557 expect((yield* cli.getPullRequestDetail(input)).viewerAccess.canDeleteBranch).toBe(
2558 expected,
2559 );
2560 expect(variablesOf("ViewerPermissions")).toHaveLength(1);
2561 expect(variablesOf("PullRequestCore")).toHaveLength(1);
2562 }),
2563 );
2564
2565 it.effect("preserves the actual source fork name in provider detail", () =>
2566 Effect.gen(function* () {
2567 const answer = coreResponse({
2568 state: "MERGED",
2569 isCrossRepository: true,
2570 headRepository: { nameWithOwner: "contributor/web-fork", viewerPermission: "WRITE" },
2571 headRef: { id: "REF" },
2572 });
2573 mockedExecute.mockReturnValue(Effect.succeed(output(encodeJson(answer))));
2574 const provider = yield* GitHubPullRequestProvider.make;
2575 const detail = yield* provider.getChangeRequest({
2576 cwd: "/w",
2577 repository: "acme/web",
2578 host: "github.com",
2579 number: 7,
2580 });
2581 expect(detail.headRepositoryNameWithOwner).toBe("contributor/web-fork");
2582 expect(detail.viewerPermissions.actions).toContain("delete-branch");
2583 expect(queryAt(0)).toContain("headRepository{nameWithOwner viewerPermission}");
2584 }),
2585 );
2586
2587 const branchToDelete = (pullRequest: Readonly<Record<string, unknown>> = {}) => ({
2588 data: {
2589 repository: {
2590 pullRequest: {
2591 state: "MERGED",
2592 headRefName: "feat/delete",
2593 baseRefName: "main",
2594 headRefOid: "abc123",
2595 headRepository: { id: "FORK_REPO" },
2596 ...pullRequest,
2597 },
2598 },
2599 },
2600 });
2601 const sourceBranch = (repository: Readonly<Record<string, unknown>> = {}) => ({
2602 data: {
2603 node: {
2604 __typename: "Repository",
2605 defaultBranchRef: { name: "main" },
2606 ref: { target: { __typename: "Commit", oid: "abc123" } },
2607 ...repository,
2608 },
2609 },
2610 });
2611
2612 it.effect.each(["MERGED", "CLOSED"])("deletes the exact remote fork branch of a %s PR", (state) =>
2613 Effect.gen(function* () {
2614 route(
2615 ["PullRequestBranchToDelete", branchToDelete({ state })],
2616 ["PullRequestSourceBranch", sourceBranch()],
2617 );
2618 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2619 yield* cli.runPullRequestAction({
2620 cwd: "/w",
2621 repository: "acme/web",
2622 host: "github.enterprise.test",
2623 number: 7,
2624 action: "delete-branch",
2625 });
2626 expect(variablesOf("PullRequestBranchToDelete")).toEqual([
2627 { owner: "acme", name: "web", number: 7 },
2628 ]);
2629 expect(variablesOf("PullRequestSourceBranch")).toEqual([
2630 { repositoryId: "FORK_REPO", ref: "refs/heads/feat/delete" },
2631 ]);
2632 expect(variablesOf("updateRefs(")).toEqual([
2633 {
2634 input: {
2635 repositoryId: "FORK_REPO",
2636 refUpdates: [
2637 {
2638 name: "refs/heads/feat/delete",
2639 beforeOid: "abc123",
2640 afterOid: "0000000000000000000000000000000000000000",
2641 },
2642 ],
2643 },
2644 },
2645 ]);
2646 expect(mockedExecute.mock.calls.at(-1)?.[0].host).toBe("github.enterprise.test");
2647 expect(variablesOf("mergePullRequest(")).toEqual([]);
2648 expect(variablesOf("closePullRequest(")).toEqual([]);
2649 }),
2650 );
2651
2652 it.effect.each([
2653 { description: "an open PR", head: { state: "OPEN" }, source: {} },
2654 { description: "the base branch", head: { headRefName: "main" }, source: {} },
2655 {
2656 description: "the default branch",
2657 head: {},
2658 source: { defaultBranchRef: { name: "feat/delete" } },
2659 },
2660 {
2661 description: "a changed branch",
2662 head: {},
2663 source: { ref: { target: { __typename: "Commit", oid: "new-commit" } } },
2664 },
2665 ])("refuses to delete $description", ({ head, source }) =>
2666 Effect.gen(function* () {
2667 route(
2668 ["PullRequestBranchToDelete", branchToDelete(head)],
2669 [
2670 "PullRequestSourceBranch",
2671 source === null ? { data: { node: null } } : sourceBranch(source),
2672 ],
2673 );
2674 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2675 const error = yield* Effect.flip(
2676 cli.runPullRequestAction({
2677 cwd: "/w",
2678 repository: "acme/web",
2679 host: "github.com",
2680 number: 7,
2681 action: "delete-branch",
2682 }),
2683 );
2684 expect(error._tag).toBe("GitHubBranchDeletionRefusedError");
2685 expect(variablesOf("updateRefs(")).toEqual([]);
2686 }),
2687 );
2688
2689 it.effect("accepts an already deleted source branch", () =>
2690 Effect.gen(function* () {
2691 route(
2692 ["PullRequestBranchToDelete", branchToDelete()],
2693 ["PullRequestSourceBranch", sourceBranch({ ref: null })],
2694 );
2695 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2696 yield* cli.runPullRequestAction({
2697 cwd: "/w",
2698 repository: "acme/web",
2699 host: "github.com",
2700 number: 7,
2701 action: "delete-branch",
2702 });
2703 expect(variablesOf("updateRefs(")).toEqual([]);
2704 }),
2705 );
2706
2707 it.effect("keeps the source branch when GitHub refuses deletion", () =>
2708 Effect.gen(function* () {
2709 route(
2710 ["PullRequestBranchToDelete", branchToDelete()],
2711 ["PullRequestSourceBranch", sourceBranch()],
2712 );
2713 const answer = mockedExecute.getMockImplementation()!;
2714 mockedExecute.mockImplementation((call) =>
2715 call.kind === "graphql" && call.query.includes("updateRefs(")
2716 ? Effect.fail(
2717 new GitHubRequestPolicy.GitHubApiResponseError({
2718 host: call.host,
2719 operation: call.operation,
2720 status: 422,
2721 }),
2722 )
2723 : answer(call),
2724 );
2725 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2726 const error = yield* Effect.flip(
2727 cli.runPullRequestAction({
2728 cwd: "/w",
2729 repository: "acme/web",
2730 host: "github.com",
2731 number: 7,
2732 action: "delete-branch",
2733 }),
2734 );
2735 expect(error._tag).toBe("GitHubApiResponseError");
2736 expect(variablesOf("mergePullRequest(")).toEqual([]);
2737 expect(variablesOf("closePullRequest(")).toEqual([]);
2738 }),
2739 );
2740
2741 it.effect.each(["merge", "enable-auto-merge"] as const)(
2742 "removes agent credits from the proposed message for %s",
2743 (action) =>
2744 Effect.gen(function* () {
2745 route(
2746 [
2747 "query PullRequestMergeMessage",
2748 mergeMessage(
2749 "Details\n\nCo-authored-by: Alice <alice@example.com>\nCo-authored-by: Claude <noreply@anthropic.com>",
2750 ),
2751 ],
2752 ["query PullRequestActionState", actionState()],
2753 );
2754 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2755 yield* cli.runPullRequestAction({
2756 cwd: "/w",
2757 repository: "acme/web",
2758 host: "github.com",
2759 number: 7,
2760 action,
2761 mergeMethod: "squash",
2762 removeAgentCreditsOnMerge: true,
2763 });
2764 expect(variablesOf("query PullRequestMergeMessage")[0]?.["method"]).toBe("SQUASH");
2765 expect(
2766 variablesOf(action === "merge" ? "mergePullRequest(" : "enablePullRequestAutoMerge("),
2767 ).toEqual([
2768 {
2769 input: {
2770 pullRequestId: "PR_7",
2771 mergeMethod: "SQUASH",
2772 expectedHeadOid: "abc123",
2773 commitBody: "Details\n\nCo-authored-by: Alice <alice@example.com>",
2774 },
2775 },
2776 ]);
2777 }),
2778 );
2779
2780 it.effect.each([
2781 {
2782 description: "an unchanged message",
2783 body: "Details\n\nCo-authored-by: Alice <alice@example.com>",
2784 queued: false,
2785 },
2786 {
2787 description: "a merge queue",
2788 body: "Co-authored-by: Claude <noreply@anthropic.com>",
2789 queued: true,
2790 },
2791 ] as const)("keeps GitHub's default message for $description", ({ body, queued }) =>
2792 Effect.gen(function* () {
2793 route(
2794 ["query PullRequestMergeMessage", mergeMessage(body, queued)],
2795 ["query PullRequestActionState", actionState({ isMergeQueueEnabled: queued })],
2796 );
2797 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2798 yield* cli.runPullRequestAction({
2799 cwd: "/w",
2800 repository: "acme/web",
2801 host: "github.com",
2802 number: 7,
2803 action: "merge",
2804 removeAgentCreditsOnMerge: true,
2805 });
2806 expect(variablesOf("query PullRequestMergeMessage")[0]?.["method"]).toBe("MERGE");
2807 expect(variablesOf(queued ? "enablePullRequestAutoMerge(" : "mergePullRequest(")).toEqual([
2808 { input: { pullRequestId: "PR_7", mergeMethod: "MERGE" } },
2809 ]);
2810 }),
2811 );
2812
2813 it.effect("passes an explicitly empty body when the proposed message only credits an agent", () =>
2814 Effect.gen(function* () {
2815 route(
2816 [
2817 "query PullRequestMergeMessage",
2818 mergeMessage("Co-authored-by: Claude <noreply@anthropic.com>"),
2819 ],
2820 ["query PullRequestActionState", actionState()],
2821 );
2822 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2823 yield* cli.runPullRequestAction({
2824 cwd: "/w",
2825 repository: "acme/web",
2826 host: "github.com",
2827 number: 7,
2828 action: "merge",
2829 removeAgentCreditsOnMerge: true,
2830 });
2831 expect(variablesOf("mergePullRequest(")).toEqual([
2832 {
2833 input: {
2834 pullRequestId: "PR_7",
2835 mergeMethod: "MERGE",
2836 expectedHeadOid: "abc123",
2837 commitBody: "",
2838 },
2839 },
2840 ]);
2841 }),
2842 );
2843
2844 it.effect("refuses to merge when the proposed message cannot be read", () =>
2845 Effect.gen(function* () {
2846 route(
2847 ["query PullRequestMergeMessage", { data: { repository: { pullRequest: null } } }],
2848 ["query PullRequestActionState", actionState()],
2849 );
2850 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2851 const result = yield* Effect.result(
2852 cli.runPullRequestAction({
2853 cwd: "/w",
2854 repository: "acme/web",
2855 host: "github.com",
2856 number: 7,
2857 action: "merge",
2858 removeAgentCreditsOnMerge: true,
2859 }),
2860 );
2861 expect(result._tag).toBe("Failure");
2862 expect(variablesOf("mergePullRequest(")).toEqual([]);
2863 }),
2864 );
2865
2866 it.effect.each([
2867 { action: "merge", mutation: "mergePullRequest(" },
2868 { action: "update-branch", mutation: "updatePullRequestBranch(" },
2869 ] as const)("runs $action on a pull request GitHub has no pull ref for", ({ action, mutation }) =>
2870 Effect.gen(function* () {
2871 route([
2872 "query PullRequestActionState",
2873 { ...actionState({ baseRef: { compare: null } }), errors: [unresolvedPullRef] },
2874 ]);
2875 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2876
2877 yield* cli.runPullRequestAction({ ...pullRequestInput, action });
2878
2879 expect(variablesOf(mutation)).toHaveLength(1);
2880 }),
2881 );
2882
2883 it.effect("merges at once when auto-merge is asked of a pull request that is ready now", () =>
2884 Effect.gen(function* () {
2885 route(["query PullRequestActionState", actionState({ mergeStateStatus: "CLEAN" })]);
2886 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2887
2888 yield* cli.runPullRequestAction({
2889 cwd: "/w",
2890 repository: "acme/web",
2891 host: "github.com",
2892 number: 7,
2893 action: "enable-auto-merge",
2894 mergeMethod: "squash",
2895 });
2896
2897 expect(variablesOf("mergePullRequest(")).toEqual([
2898 { input: { pullRequestId: "PR_7", mergeMethod: "SQUASH" } },
2899 ]);
2900 expect(variablesOf("enablePullRequestAutoMerge(")).toEqual([]);
2901 }),
2902 );
2903
2904 it.effect("does not approve action-required runs for a same-repository pull request", () =>
2905 Effect.gen(function* () {
2906 mockedExecute.mockReturnValueOnce(
2907 Effect.succeed(
2908 output(
2909 encodeJson(
2910 coreResponse({
2911 number: 7,
2912 title: "Pull request 7",
2913 url: "https://github.com/acme/web/pull/7",
2914 headRefName: "feat/page",
2915 headRefOid: "abc123",
2916 isCrossRepository: false,
2917 headRepositoryOwner: { __typename: "Organization", login: "acme" },
2918 baseRefName: "main",
2919 createdAt: "2026-07-01T00:00:00Z",
2920 updatedAt: "2026-07-02T00:00:00Z",
2921 }),
2922 ),
2923 ),
2924 ),
2925 );
2926 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2927
2928 yield* cli.runPullRequestAction({
2929 cwd: "/w",
2930 repository: "acme/web",
2931 host: "github.com",
2932 number: 7,
2933 action: "approve-workflows",
2934 });
2935
2936 expect(mockedExecute).toHaveBeenCalledTimes(1);
2937 }),
2938 );
2939
2940 it.effect("finds and approves every workflow waiting on a maintainer", () =>
2941 Effect.gen(function* () {
2942 workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7]), workflowRuns([10, 11]));
2943 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2944
2945 yield* cli.runPullRequestAction({
2946 cwd: "/w",
2947 repository: "acme/web",
2948 host: "github.com",
2949 number: 7,
2950 action: "approve-workflows",
2951 });
2952
2953 expect(variablesOf("PullRequestHeads")[0]).toEqual({
2954 owner: "acme",
2955 name: "web",
2956 head: "feat/page",
2957 });
2958 expect(restCallsTo("actions/runs?")[0]?.path).toBe(
2959 "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fpage&event=pull_request&status=action_required&per_page=100&page=1",
2960 );
2961 expect(restCallsTo("/approve").map((call) => [call.method, call.path])).toEqual([
2962 ["POST", "repos/acme/web/actions/runs/10/approve"],
2963 ["POST", "repos/acme/web/actions/runs/11/approve"],
2964 ]);
2965 assert.strictEqual(restCallsTo("actions/runs?").length, 3);
2966 }),
2967 );
2968
2969 it.effect("counts revalidated runs that wait on a maintainer as GitHub reports them", () =>
2970 Effect.gen(function* () {
2971 workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7]), workflowRuns([]));
2972 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2973
2974 const runs = yield* cli
2975 .listWorkflowRunsRequiringApproval({
2976 cwd: "/w",
2977 repository: "acme/web",
2978 host: "github.com",
2979 number: 7,
2980 headSha: "abc123",
2981 headBranch: "feat/page",
2982 headRepositoryOwner: "octocat",
2983 isCrossRepository: true,
2984 })
2985 .pipe(
2986 Effect.provideService(KnownWorkflowRuns, {
2987 headSha: "abc123",
2988 runs: [
2989 {
2990 id: 10,
2991 status: "completed",
2992 conclusion: "action_required",
2993 head_branch: "feat/page",
2994 },
2995 { id: 11, status: "completed", conclusion: "success", head_branch: "feat/page" },
2996 ],
2997 }),
2998 );
2999
3000 expect(runs.map((run) => run.id)).toEqual([10]);
3001 assert.strictEqual(restCallsTo("actions/runs?").length, 0);
3002 }),
3003 );
3004
3005 it.effect("refuses a stale workflow approval after the pull request head changes", () =>
3006 Effect.gen(function* () {
3007 let detailReads = 0;
3008 workflowApprovalRoutes(
3009 () => crossRepositoryDetail(++detailReads === 1 ? "abc123" : "def456"),
3010 heads([7]),
3011 workflowRuns([10]),
3012 );
3013 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3014
3015 const error = yield* Effect.flip(
3016 cli.runPullRequestAction({
3017 cwd: "/w",
3018 repository: "acme/web",
3019 host: "github.com",
3020 number: 7,
3021 action: "approve-workflows",
3022 }),
3023 );
3024
3025 expect(error).toMatchObject({
3026 _tag: "GitHubWorkflowApprovalHeadChangedError",
3027 number: 7,
3028 });
3029 assert.strictEqual(detailReads, 2);
3030 expect(restCallsTo("/approve")).toEqual([]);
3031 }),
3032 );
3033
3034 it.effect("reads workflow runs and their pull request scope concurrently", () =>
3035 Effect.gen(function* () {
3036 const headsStarted = yield* Deferred.make<void>();
3037 const runsStarted = yield* Deferred.make<void>();
3038 mockedExecute.mockImplementation((call) =>
3039 call.kind === "graphql"
3040 ? Deferred.succeed(headsStarted, undefined).pipe(
3041 Effect.andThen(Deferred.await(runsStarted)),
3042 Effect.as(output(encodeJson(heads([7])))),
3043 )
3044 : Deferred.succeed(runsStarted, undefined).pipe(
3045 Effect.andThen(Deferred.await(headsStarted)),
3046 Effect.as(output(encodeJson(workflowRuns([10])))),
3047 ),
3048 );
3049 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3050
3051 const runs = yield* cli.listWorkflowRunsRequiringApproval({
3052 cwd: "/w",
3053 repository: "acme/web",
3054 host: "github.com",
3055 number: 7,
3056 headSha: "abc123",
3057 headBranch: "feat/page",
3058 headRepositoryOwner: "octocat",
3059 isCrossRepository: true,
3060 });
3061
3062 expect(runs).toEqual([{ id: 10, name: "build", url: "https://example.com/10" }]);
3063 }),
3064 );
3065
3066 it.effect("lists only the head's workflow runs that have not finished", () =>
3067 Effect.gen(function* () {
3068 mockedExecute.mockImplementation(() =>
3069 Effect.succeed(
3070 output(
3071 encodeJson({
3072 workflow_runs: ["queued", "in_progress", "completed", "action_required", null].map(
3073 (status, index) => ({ id: index, name: `${status}`, html_url: null, status }),
3074 ),
3075 }),
3076 ),
3077 ),
3078 );
3079 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3080
3081 const runs = yield* cli.listUnfinishedWorkflowRuns({
3082 cwd: "/w",
3083 repository: "acme/web",
3084 host: "github.com",
3085 headSha: "abc123",
3086 });
3087
3088 expect(restCallsTo("actions/runs?")[0]?.path).toBe(
3089 "repos/acme/web/actions/runs?head_sha=abc123&per_page=100",
3090 );
3091 expect(runs).toEqual([
3092 { id: 0, name: "queued", url: null },
3093 { id: 1, name: "in_progress", url: null },
3094 ]);
3095 }),
3096 );
3097
3098 it.effect("refuses workflow approval when one head belongs to several pull requests", () =>
3099 Effect.gen(function* () {
3100 workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7, 8]), workflowRuns([]));
3101 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3102
3103 const error = yield* Effect.flip(
3104 cli.listWorkflowRunsRequiringApproval({
3105 cwd: "/w",
3106 repository: "acme/web",
3107 host: "github.com",
3108 number: 7,
3109 headSha: "abc123",
3110 headBranch: "feat/page",
3111 headRepositoryOwner: "octocat",
3112 isCrossRepository: true,
3113 }),
3114 );
3115
3116 expect(error).toMatchObject({
3117 _tag: "GitHubWorkflowApprovalRefusedError",
3118 reason: "head-not-unique",
3119 number: 7,
3120 observedCount: 2,
3121 limit: 1_000,
3122 });
3123 expect(error.message).toContain("instead of uniquely matching #7");
3124 }),
3125 );
3126
3127 it.effect("refuses workflow approval when the head list stops before its end", () =>
3128 Effect.gen(function* () {
3129 const repeating = heads([7]);
3130 repeating.data.repository.pullRequests.pageInfo = {
3131 hasNextPage: true,
3132 endCursor: "same",
3133 } as never;
3134 workflowApprovalRoutes(() => crossRepositoryDetail(), repeating, workflowRuns([]));
3135 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3136
3137 const error = yield* Effect.flip(
3138 cli.listWorkflowRunsRequiringApproval({
3139 cwd: "/w",
3140 repository: "acme/web",
3141 host: "github.com",
3142 number: 7,
3143 headSha: "abc123",
3144 headBranch: "feat/page",
3145 headRepositoryOwner: "octocat",
3146 isCrossRepository: true,
3147 }),
3148 );
3149
3150 expect(error).toMatchObject({
3151 _tag: "GitHubWorkflowApprovalRefusedError",
3152 reason: "head-list-truncated",
3153 });
3154 }),
3155 );
3156
3157 it.effect("refuses workflow approval when GitHub omits the head repository", () =>
3158 Effect.gen(function* () {
3159 mockedExecute.mockReturnValueOnce(
3160 Effect.succeed(
3161 output(
3162 encodeJson(
3163 coreResponse({
3164 number: 7,
3165 title: "Pull request 7",
3166 url: "https://github.com/acme/web/pull/7",
3167 headRefName: "feat/page",
3168 headRefOid: "abc123",
3169 isCrossRepository: true,
3170 headRepositoryOwner: null,
3171 baseRefName: "main",
3172 createdAt: "2026-07-01T00:00:00Z",
3173 updatedAt: "2026-07-02T00:00:00Z",
3174 }),
3175 ),
3176 ),
3177 ),
3178 );
3179 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3180
3181 const error = yield* Effect.flip(
3182 cli.runPullRequestAction({
3183 cwd: "/w",
3184 repository: "acme/web",
3185 host: "github.com",
3186 number: 7,
3187 action: "approve-workflows",
3188 }),
3189 );
3190
3191 expect(error).toMatchObject({
3192 _tag: "GitHubWorkflowApprovalHeadUnavailableError",
3193 number: 7,
3194 });
3195 expect(mockedExecute).toHaveBeenCalledTimes(1);
3196 }),
3197 );
3198
3199 it.effect("surfaces a workflow run list beyond the safe approval bound", () =>
3200 Effect.gen(function* () {
3201 let runPages = 0;
3202 mockedExecute.mockImplementation((call) => {
3203 if (call.kind === "graphql") return Effect.succeed(output(encodeJson(heads([7]))));
3204 const page = runPages++;
3205 return Effect.succeed(
3206 output(
3207 encodeJson(
3208 workflowRuns(Array.from({ length: 100 }, (_, index) => page * 100 + index + 1)),
3209 ),
3210 ),
3211 );
3212 });
3213 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3214
3215 const error = yield* Effect.flip(
3216 cli.listWorkflowRunsRequiringApproval({
3217 cwd: "/w",
3218 repository: "acme/web",
3219 host: "github.com",
3220 number: 7,
3221 headSha: "abc123",
3222 headBranch: "feat/page",
3223 headRepositoryOwner: "octocat",
3224 isCrossRepository: true,
3225 }),
3226 );
3227
3228 expect(error).toMatchObject({
3229 _tag: "GitHubWorkflowApprovalRefusedError",
3230 reason: "run-list-truncated",
3231 number: 7,
3232 observedCount: 1_100,
3233 limit: 1_000,
3234 });
3235 expect(error.message).toContain("more than 1000 workflow runs");
3236 assert.strictEqual(runPages, 11);
3237 }),
3238 );
3239
3240 it.effect("sends a comment body as a variable, never inside the document", () =>
3241 Effect.gen(function* () {
3242 route([NODE_ID_QUERY, nodeIdAnswer("PR_7")]);
3243 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3244
3245 yield* cli.commentOnPullRequest({
3246 cwd: "/w",
3247 repository: "acme/web",
3248 host: "github.com",
3249 number: 7,
3250 body: "Looks good.",
3251 });
3252
3253 expect(variablesOf("addComment(")).toEqual([{ subjectId: "PR_7", body: "Looks good." }]);
3254 expect(queryAt(mockedExecute.mock.calls.length - 1)).not.toContain("Looks good.");
3255 }),
3256 );
3257
3258 it.effect("names the host on every repository it addresses", () =>
3259 Effect.gen(function* () {
3260 mockedExecute.mockImplementation((call) =>
3261 Effect.succeed(
3262 call.kind === "graphql" && call.operationName === "PullRequestList"
3263 ? emptyList()
3264 : emptySearch(),
3265 ),
3266 );
3267 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3268
3269 yield* cli.listPullRequests({
3270 cwd: "/w",
3271 repository: "acme/web",
3272 host: "github.acme.dev",
3273 state: "open",
3274 involvement: "all",
3275 viewer: "bilal",
3276 limit: 10,
3277 });
3278
3279 assert.isAbove(mockedExecute.mock.calls.length, 0);
3280 expect(new Set(mockedExecute.mock.calls.map(([call]) => call.host))).toEqual(
3281 new Set(["github.acme.dev"]),
3282 );
3283 expect(searchOfCall(0)).toContain("repo:acme/web");
3284 }),
3285 );
3286
3287 it.effect("reads one files page when GitHub refuses the diff, and says it is the last", () =>
3288 Effect.gen(function* () {
3289 mockedExecute.mockReturnValueOnce(Effect.fail(diffRefused));
3290 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestFiles(2, 1))));
3291 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3292
3293 const diff = yield* cli.getPullRequestDiff({
3294 cwd: "/w",
3295 repository: "acme/web",
3296 host: "github.acme.dev",
3297 number: 7,
3298 });
3299
3300 assert.isFalse(diff.truncated);
3301 assert.isNull(diff.nextCursor);
3302 // The refusal covers one file's read too.
3303 assert.isUndefined(diff.withheldFilesReadable);
3304 expect(diff.patch).toContain("diff --git a/src/file1.ts b/src/file1.ts");
3305 expect(diff.patch).toContain("diff --git a/src/file2.ts b/src/file2.ts");
3306 assert.strictEqual(callAt(1).host, "github.acme.dev");
3307 assert.strictEqual(pathAt(1), "repos/acme/web/pulls/7/files?per_page=30&page=1");
3308 }),
3309 );
3310
3311 it.effect("cuts one withheld file out of GitHub's whole diff", () =>
3312 Effect.gen(function* () {
3313 const sdk = "diff --git a/patches/sdk.patch b/patches/sdk.patch\n@@ -1 +1 @@\n-old\n+new\n";
3314 const patch = `diff --git a/a.ts b/a.ts\n@@ -1 +1 @@\n-a\n+b\n${sdk}diff --git a/z.ts b/z.ts\n@@ -1 +1 @@\n-y\n+z\n`;
3315 mockedExecute.mockReturnValueOnce(Effect.succeed(output(patch)));
3316 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3317 const ref = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
3318 const file = yield* cli.getPullRequestDiff({ ...ref, path: "patches/sdk.patch" });
3319 expect(file).toEqual({ patch: sdk, truncated: false, nextCursor: null });
3320 expect(pathAt(0)).toBe("repos/acme/web/pulls/7");
3321 expect(callAt(0)).toMatchObject({ kind: "rest", accept: "application/vnd.github.diff" });
3322
3323 const minified = `diff --git a/b.js b/b.js\n@@ -10,2 +10,2 @@\n ${"c".repeat(1200)}\n-${"a".repeat(3000)}\n+${"b".repeat(1500)}\n`;
3324 mockedExecute.mockReturnValueOnce(Effect.succeed(output(minified)));
3325 const shortened = yield* cli.getPullRequestDiff({ ...ref, path: "b.js" });
3326 expect(shortened.patch).toBe(
3327 `diff --git a/b.js b/b.js\n@@ -10,2 +10,2 @@\n ${"c".repeat(1000)} …[200 more characters]\n-${"a".repeat(1000)} …[2,000 more characters]\n+${"b".repeat(1000)} …[500 more characters]\n`,
3328 );
3329
3330 mockedExecute.mockReturnValueOnce(Effect.succeed(output(patch, true)));
3331 const error = yield* Effect.flip(
3332 cli.getPullRequestDiff({ ...ref, path: "patches/sdk.patch" }),
3333 );
3334 expect(error._tag).toBe("GitHubPullRequestReadError");
3335 }),
3336 );
3337
3338 it.effect("hands back a cursor for the next page rather than walking on by itself", () =>
3339 Effect.gen(function* () {
3340 mockedExecute.mockReturnValueOnce(Effect.fail(diffRefused));
3341 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestFiles(30, 0))));
3342 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3343
3344 const diff = yield* cli.getPullRequestDiff({
3345 cwd: "/w",
3346 repository: "acme/web",
3347 host: "github.com",
3348 number: 7,
3349 });
3350
3351 assert.isFalse(diff.truncated);
3352 assert.isNotNull(diff.nextCursor);
3353 assert.strictEqual(mockedExecute.mock.calls.length, 2);
3354 }),
3355 );
3356
3357 it.effect("refuses a cursor it never handed out rather than reading it into a request", () =>
3358 Effect.gen(function* () {
3359 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3360
3361 const error = yield* Effect.flip(
3362 cli.getPullRequestDiff({
3363 cwd: "/w",
3364 repository: "acme/web",
3365 host: "github.com",
3366 number: 7,
3367 cursor: "1&per_page=1",
3368 }),
3369 );
3370
3371 assert.strictEqual(error._tag, "GitHubDiffCursorError");
3372 assert.strictEqual(mockedExecute.mock.calls.length, 0);
3373 }),
3374 );
3375
3376 it.effect("reads a named commit from the commit endpoint rather than the whole diff", () =>
3377 Effect.gen(function* () {
3378 mockedExecute.mockReturnValueOnce(
3379 Effect.succeed(output(`{"files":${pullRequestFiles(2, 1)}}`)),
3380 );
3381 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3382
3383 const diff = yield* cli.getPullRequestDiff({
3384 cwd: "/w",
3385 repository: "acme/web",
3386 host: "github.com",
3387 number: 7,
3388 commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
3389 });
3390
3391 assert.strictEqual(mockedExecute.mock.calls.length, 1);
3392 assert.isNull(diff.nextCursor);
3393 expect(diff.patch).toContain("diff --git a/src/file1.ts b/src/file1.ts");
3394 assert.strictEqual(
3395 pathAt(0),
3396 "repos/acme/web/commits/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0?per_page=30&page=1",
3397 );
3398 }),
3399 );
3400
3401 it.effect("refuses a commit that is not a sha rather than reading it into a request", () =>
3402 Effect.gen(function* () {
3403 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3404
3405 const error = yield* Effect.flip(
3406 cli.getPullRequestDiff({
3407 cwd: "/w",
3408 repository: "acme/web",
3409 host: "github.com",
3410 number: 7,
3411 commit: "../../pulls/8/files",
3412 }),
3413 );
3414
3415 assert.strictEqual(error._tag, "GitHubDiffCommitError");
3416 assert.strictEqual(mockedExecute.mock.calls.length, 0);
3417 }),
3418 );
3419
3420 it.effect("expands a new file from a root commit without requiring a parent", () =>
3421 Effect.gen(function* () {
3422 mockedExecute.mockReturnValueOnce(
3423 Effect.succeed(output(encodeJson({ sha: "a1b2c3d", parents: [] }))),
3424 );
3425 mockedExecute.mockReturnValueOnce(Effect.succeed(output("root contents\n")));
3426 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3427
3428 const contents = yield* cli.getPullRequestDiffFileContents({
3429 cwd: "/w",
3430 repository: "acme/web",
3431 host: "github.com",
3432 number: 7,
3433 commit: "a1b2c3d",
3434 changeType: "new",
3435 oldPath: "src/root.ts",
3436 newPath: "src/root.ts",
3437 });
3438
3439 expect(contents).toEqual({ oldContents: "", newContents: "root contents\n" });
3440 assert.strictEqual(mockedExecute.mock.calls.length, 2);
3441 assert.strictEqual(pathAt(0), "repos/acme/web/commits/a1b2c3d");
3442 assert.strictEqual(pathAt(1), "repos/acme/web/contents/src/root.ts?ref=a1b2c3d");
3443 }),
3444 );
3445
3446 it.effect("expands a pull request file from its merge base, not the moved base tip", () =>
3447 Effect.gen(function* () {
3448 const answers: Record<string, string> = {
3449 "repos/acme/web/pulls/7": pullRequestRefs,
3450 "repos/acme/web/compare/a1b2c3d...b1c2d3e?per_page=1&page=2": pullRequestMergeBase,
3451 "repos/acme/web/contents/src/a.ts?ref=a1b2c3d": "base tip\n",
3452 "repos/acme/web/contents/src/a.ts?ref=c1d2e3f": "merge base\n",
3453 "repos/acme/web/contents/src/a.ts?ref=b1c2d3e": "head\n",
3454 };
3455 mockedExecute.mockImplementation((call) =>
3456 Effect.succeed(output(call.kind === "rest" ? (answers[call.path] ?? "") : "")),
3457 );
3458 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3459
3460 const contents = yield* cli.getPullRequestDiffFileContents({
3461 cwd: "/w",
3462 repository: "acme/web",
3463 host: "github.com",
3464 number: 7,
3465 changeType: "change",
3466 oldPath: "src/a.ts",
3467 newPath: "src/a.ts",
3468 });
3469
3470 expect(contents).toEqual({ oldContents: "merge base\n", newContents: "head\n" });
3471 }),
3472 );
3473
3474 it.effect("reports unusable diff revisions as a structured error", () =>
3475 Effect.gen(function* () {
3476 mockedExecute.mockReturnValueOnce(Effect.succeed(output("not-a-sha\tstill-not-a-sha\n")));
3477 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3478
3479 const error = yield* Effect.flip(
3480 cli.getPullRequestDiffFileContents({
3481 cwd: "/w",
3482 repository: "acme/web",
3483 host: "github.com",
3484 number: 7,
3485 commit: "a1b2c3d",
3486 changeType: "change",
3487 oldPath: "src/a.ts",
3488 newPath: "src/a.ts",
3489 }),
3490 );
3491
3492 assert.strictEqual(error._tag, "GitHubDiffRevisionsUnavailableError");
3493 if (error._tag === "GitHubDiffRevisionsUnavailableError") {
3494 assert.strictEqual(error.number, 7);
3495 assert.strictEqual(error.commit, "a1b2c3d");
3496 }
3497 }),
3498 );
3499
3500 it.effect("reports undecodable diff file contents as binary", () =>
3501 Effect.gen(function* () {
3502 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestRefs)));
3503 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestMergeBase)));
3504 mockedExecute.mockReturnValueOnce(Effect.succeed(output("binary�contents", false, true)));
3505 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3506
3507 const error = yield* Effect.flip(
3508 cli.getPullRequestDiffFileContents({
3509 cwd: "/w",
3510 repository: "acme/web",
3511 host: "github.com",
3512 number: 7,
3513 changeType: "deleted",
3514 oldPath: "assets/logo.png",
3515 newPath: "assets/logo.png",
3516 }),
3517 );
3518
3519 assert.strictEqual(error._tag, "GitHubDiffFileContentsUnavailableError");
3520 if (error._tag === "GitHubDiffFileContentsUnavailableError") {
3521 assert.strictEqual(error.path, "assets/logo.png");
3522 assert.strictEqual(error.reason, "binary");
3523 }
3524 }),
3525 );
3526
3527 it.effect("returns valid text containing a literal replacement character", () =>
3528 Effect.gen(function* () {
3529 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestRefs)));
3530 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestMergeBase)));
3531 mockedExecute.mockReturnValueOnce(Effect.succeed(output("before�after")));
3532 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3533
3534 const contents = yield* cli.getPullRequestDiffFileContents({
3535 cwd: "/w",
3536 repository: "acme/web",
3537 host: "github.com",
3538 number: 7,
3539 changeType: "deleted",
3540 oldPath: "docs/encoding.md",
3541 newPath: "docs/encoding.md",
3542 });
3543
3544 assert.strictEqual(contents.oldContents, "before�after");
3545 }),
3546 );
3547
3548 it.effect("ends the diff on a page with no files rather than asking for it again", () =>
3549 Effect.gen(function* () {
3550 mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
3551 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3552
3553 const diff = yield* cli.getPullRequestDiff({
3554 cwd: "/w",
3555 repository: "acme/web",
3556 host: "github.com",
3557 number: 7,
3558 cursor: "4",
3559 });
3560
3561 assert.strictEqual(diff.patch, "");
3562 assert.isNull(diff.nextCursor);
3563 }),
3564 );
3565
3566 it.effect("reports the refused diff when the files API cannot answer either", () =>
3567 Effect.gen(function* () {
3568 mockedExecute.mockReturnValueOnce(Effect.fail(diffRefused));
3569 mockedExecute.mockReturnValueOnce(Effect.succeed(output("not json")));
3570 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3571
3572 const error = yield* Effect.flip(
3573 cli.getPullRequestDiff({
3574 cwd: "/w",
3575 repository: "acme/web",
3576 host: "github.com",
3577 number: 7,
3578 }),
3579 );
3580
3581 assert.strictEqual(error, diffRefused);
3582 }),
3583 );
3584
3585 it.effect("verifies a REST-forbidden account through GraphQL with the pinned credential", () =>
3586 Effect.gen(function* () {
3587 const input = { cwd: "/w", host: "github.identity-fallback.test" };
3588 const original = {
3589 token: Redacted.make("original-token"),
3590 fingerprint: `${input.host}:original`,
3591 };
3592 mockedCredential.mockReturnValue(Effect.succeed(original));
3593 mockedExecute.mockImplementation((call) =>
3594 Effect.gen(function* () {
3595 expect(yield* SourceControlRateLimit.CredentialScope).toBe(original.fingerprint);
3596 if (call.kind === "rest") {
3597 expect(call.path).toBe("user");
3598 expect(yield* GitHubRequestPolicy.PinnedGitHubCredential).toMatchObject({
3599 host: input.host,
3600 credentialFingerprint: original.fingerprint,
3601 });
3602 mockedCredential.mockReturnValue(
3603 Effect.succeed({
3604 token: Redacted.make("replacement-token"),
3605 fingerprint: `${input.host}:replacement`,
3606 }),
3607 );
3608 return yield* new GitHubRequestPolicy.GitHubApiResponseError({
3609 host: input.host,
3610 operation: "getRoutingIdentity",
3611 status: 403,
3612 githubErrors: ["Resource not accessible by integration"],
3613 });
3614 }
3615 expect(call.host).toBe(input.host);
3616 expect(call.authorization).toBe("Bearer original-token");
3617 expect(call.query).toMatch(/viewer\s*\{/);
3618 expect(call.query).toContain("databaseId");
3619 expect(call.query).toContain("login");
3620 return output(
3621 '{"data":{"viewer":{"databaseId":789,"login":"acme-app[bot]"}}}',
3622 false,
3623 false,
3624 graphqlQuota(0),
3625 );
3626 }),
3627 );
3628 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3629 const quota = yield* GitHubQuota.GitHubQuota;
3630 yield* quota
3631 .observe(input.host, graphqlQuota(1))
3632 .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, original.fingerprint));
3633 const identity = { accountId: "789", viewer: "acme-app[bot]" };
3634 expect(yield* cli.getRoutingIdentity(input)).toEqual(identity);
3635
3636 mockedCredential.mockReturnValue(Effect.succeed(original));
3637 expect(yield* cli.getRoutingIdentity(input)).toEqual(identity);
3638 expect(mockedExecute).toHaveBeenCalledTimes(2);
3639
3640 const exhausted = yield* quota
3641 .admit(input.host, "graphql")
3642 .pipe(
3643 Effect.provideService(SourceControlRateLimit.CredentialScope, original.fingerprint),
3644 Effect.flip,
3645 );
3646 expect(exhausted._tag).toBe("SourceControlRateLimitPausedError");
3647 yield* quota
3648 .admit(input.host, "graphql")
3649 .pipe(
3650 Effect.provideService(
3651 SourceControlRateLimit.CredentialScope,
3652 `${input.host}:replacement`,
3653 ),
3654 );
3655 }),
3656 );
3657
3658 it.effect("rejects a null GraphQL account id without caching it", () =>
3659 Effect.gen(function* () {
3660 const input = { cwd: "/w", host: "github.identity-null.test" };
3661 const forbidden = new GitHubRequestPolicy.GitHubApiResponseError({
3662 host: input.host,
3663 operation: "getRoutingIdentity",
3664 status: 403,
3665 });
3666 mockedExecute
3667 .mockReturnValueOnce(Effect.fail(forbidden))
3668 .mockReturnValueOnce(
3669 Effect.succeed(output('{"data":{"viewer":{"databaseId":null,"login":"acme-app[bot]"}}}')),
3670 )
3671 .mockReturnValueOnce(Effect.fail(forbidden))
3672 .mockReturnValueOnce(
3673 Effect.succeed(output('{"data":{"viewer":{"databaseId":789,"login":"acme-app[bot]"}}}')),
3674 );
3675 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3676 const error = yield* cli.getRoutingIdentity(input).pipe(Effect.flip);
3677 expect(error._tag).toBe("GitHubViewerLoginUnavailableError");
3678 expect(yield* cli.getRoutingIdentity(input)).toEqual({
3679 accountId: "789",
3680 viewer: "acme-app[bot]",
3681 });
3682 expect(mockedExecute).toHaveBeenCalledTimes(4);
3683 }),
3684 );
3685
3686 // regression: #18780 credentials that cannot read /user still load pull requests
3687 it.effect.each([
3688 new GitHubRequestPolicy.GitHubApiAuthenticationError({
3689 host: "github.identity-auth-error.test",
3690 operation: "getRoutingIdentity",
3691 }),
3692 new GitHubRequestPolicy.GitHubApiResponseError({
3693 host: "github.identity-server-error.test",
3694 operation: "getRoutingIdentity",
3695 status: 500,
3696 }),
3697 ])("preserves $_tag from REST identity verification without trying GraphQL", (error) =>
3698 Effect.gen(function* () {
3699 mockedExecute.mockReturnValue(Effect.fail(error));
3700 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3701 expect(yield* cli.getRoutingIdentity({ cwd: "/w", host: error.host }).pipe(Effect.flip)).toBe(
3702 error,
3703 );
3704 expect(mockedExecute).toHaveBeenCalledTimes(1);
3705 expect(callAt(0)).toMatchObject({ kind: "rest", path: "user" });
3706 }),
3707 );
3708
3709 it.effect("reuses verified credentials offline and refuses an unverified replacement", () =>
3710 Effect.gen(function* () {
3711 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3712 const input = { cwd: "/w", host: "github.identity-cache.test" };
3713 mockedCredential.mockImplementation((host) =>
3714 Effect.succeed({ token: Redacted.make("test-credential-a"), fingerprint: `${host}:a` }),
3715 );
3716 mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"id":123,"login":"maria-rcks"}')));
3717 expect(yield* cli.getRoutingIdentity(input)).toEqual({
3718 accountId: "123",
3719 viewer: "maria-rcks",
3720 });
3721
3722 expect(yield* cli.getRoutingIdentity(input)).toEqual({
3723 accountId: "123",
3724 viewer: "maria-rcks",
3725 });
3726 expect(mockedExecute).toHaveBeenCalledTimes(1);
3727
3728 mockedCredential.mockImplementation((host) =>
3729 Effect.succeed({ token: Redacted.make("test-credential-b"), fingerprint: `${host}:b` }),
3730 );
3731 mockedExecute.mockReturnValueOnce(
3732 Effect.fail(
3733 new GitHubRequestPolicy.GitHubApiResponseError({
3734 host: "github.com",
3735 operation: "getRoutingIdentity",
3736 status: 502,
3737 }),
3738 ),
3739 );
3740 const failure = yield* cli.getRoutingIdentity(input).pipe(Effect.flip);
3741 expect(failure._tag).toBe("GitHubApiResponseError");
3742 expect(String(failure)).not.toContain("test-credential-b");
3743 expect(mockedExecute).toHaveBeenCalledTimes(2);
3744
3745 mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"id":456,"login":"maria-rcks"}')));
3746 expect(yield* cli.getRoutingIdentity(input)).toEqual({
3747 accountId: "456",
3748 viewer: "maria-rcks",
3749 });
3750 }),
3751 );
3752
3753 it.effect("confirms a given subject belongs to the named pull request, then reacts to it", () =>
3754 Effect.gen(function* () {
3755 route([SUBJECT_SCOPE_QUERY, subjectScope("IC_1", "PR_kwDOA")]);
3756 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3757
3758 yield* cli.setReaction({
3759 cwd: "/w",
3760 repository: "acme/web",
3761 host: "github.com",
3762 number: 7,
3763 subjectId: "IC_1",
3764 content: "heart",
3765 reacted: true,
3766 });
3767
3768 assert.strictEqual(mockedExecute.mock.calls.length, 2);
3769 expect(variablesOf(SUBJECT_SCOPE_QUERY)).toEqual([
3770 { owner: "acme", name: "web", number: 7, subjectId: "IC_1" },
3771 ]);
3772 expect(variablesOf("addReaction(")).toEqual([{ subjectId: "IC_1", content: "HEART" }]);
3773 }),
3774 );
3775
3776 it.effect("refuses a given subject that belongs to a different pull request", () =>
3777 Effect.gen(function* () {
3778 mockedExecute.mockReturnValueOnce(
3779 Effect.succeed(
3780 output(
3781 encodeJson({
3782 data: {
3783 repository: { pullRequest: { id: "PR_thisOne" } },
3784 node: {
3785 __typename: "IssueComment",
3786 id: "IC_99",
3787 pullRequest: { id: "PR_someOtherOne" },
3788 },
3789 },
3790 }),
3791 ),
3792 ),
3793 );
3794 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3795
3796 const error = yield* Effect.flip(
3797 cli.setReaction({
3798 cwd: "/w",
3799 repository: "acme/web",
3800 host: "github.com",
3801 number: 7,
3802 subjectId: "IC_99",
3803 content: "heart",
3804 reacted: true,
3805 }),
3806 );
3807
3808 assert.strictEqual(error._tag, "GitHubSubjectScopeError");
3809 assert.strictEqual(mockedExecute.mock.calls.length, 1);
3810 }),
3811 );
3812
3813 // regression: #19564 only a refused reviewer path is retried; other failures surface as-is
3814 it.effect.each([
3815 {
3816 name: "check path",
3817 errors: [
3818 {
3819 ...refusedReviewer,
3820 path: ["repository", "pullRequest", "commits", "nodes", 0, "commit", "statusCheckRollup"],
3821 },
3822 ],
3823 },
3824 { name: "HTTP 403", errors: [refusedReviewer], status: 403 },
3825 {
3826 name: "GraphQL rate limit",
3827 errors: [refusedReviewer, { message: "API rate limit exceeded", type: "RATE_LIMITED" }],
3828 tag: "GitHubApiRateLimitError",
3829 },
3830 ])("does not retry a reviewer refusal with $name", ({ name, errors, status = 200, tag }) =>
3831 Effect.gen(function* () {
3832 mockedExecute.mockReturnValue(
3833 Effect.succeed(
3834 output(
3835 encodeJson(status === 401 ? { message: "Bad credentials" } : { data: null, errors }),
3836 false,
3837 false,
3838 {},
3839 status,
3840 ),
3841 ),
3842 );
3843 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3844 const reads: ReadonlyArray<PullRequestRead> = [
3845 cli.getPullRequestDetail,
3846 cli.listReviewThreadComments,
3847 ];
3848 for (const [index, read] of reads.entries()) {
3849 const error = yield* read({
3850 ...pullRequestInput,
3851 host: `github-${name.replaceAll(" ", "-")}-${index}.test`,
3852 }).pipe(Effect.asVoid, Effect.flip);
3853 expect(error._tag).toBe(tag ?? "GitHubApiResponseError");
3854 if (error._tag === "GitHubApiResponseError")
3855 expect(error).toMatchObject({
3856 status,
3857 githubErrors: errors.map((e) =>
3858 "path" in e ? `${e.message} (at ${e.path.join(".")})` : e.message,
3859 ),
3860 });
3861 expect(mockedExecute).toHaveBeenCalledTimes(index + 1);
3862 }
3863 }),
3864 );
3865
3866 it.effect("keeps thread cursors after a reviewer refusal", () =>
3867 Effect.gen(function* () {
3868 mockedExecute.mockReturnValueOnce(refusedReviewerResponse());
3869 mockedExecute.mockReturnValueOnce(
3870 Effect.succeed(output(reviewThreadsPage([thread("T2", "c2")], "last"))),
3871 );
3872 mockedExecute.mockReturnValueOnce(
3873 Effect.succeed(output(reviewThreadsPage([thread("T3", "c3")], null))),
3874 );
3875 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3876 const read = cli.listReviewThreadComments({
3877 ...pullRequestInput,
3878 repository: "acme/refused-threads",
3879 });
3880 const conversation = yield* read;
3881 expect(variablesOf("ReviewThreads").map((v) => v["requestedReviewers"])).toEqual([50, 0]);
3882 expect(variablesOf("ReviewThreadPages").map((v) => v["after"])).toEqual(["last"]);
3883 expect(conversation.comments.map((c) => c.id)).toEqual(["c2", "c3"]);
3884 expect(conversation.reviewers).toEqual([]);
3885 expect(conversation.truncated).toBe(false);
3886
3887 mockedExecute.mockReturnValueOnce(Effect.succeed(output(reviewThreadsPage([], null))));
3888 yield* read;
3889 expect(variablesOf("ReviewThreads").at(-1)).toMatchObject({ requestedReviewers: 0 });
3890 }),
3891 );
3892
3893 it.effect("decodes reviewers, labels and workflow checks without another detail read", () =>
3894 Effect.gen(function* () {
3895 mockedExecute.mockReturnValueOnce(
3896 Effect.succeed(
3897 output(
3898 encodeJson(
3899 coreResponse({
3900 baseRef: null,
3901 reviewRequests: {
3902 nodes: [
3903 { requestedReviewer: { __typename: "User", login: "reviewer", name: null } },
3904 {
3905 requestedReviewer: {
3906 __typename: "Team",
3907 slug: "maintainers",
3908 combinedSlug: "octo/maintainers",
3909 teamName: "Maintainers",
3910 teamAvatarUrl: "https://avatars.githubusercontent.com/t/1",
3911 },
3912 },
3913 ],
3914 },
3915 labels: {
3916 nodes: [{ name: "bug", color: "ff0000", description: "Something is broken" }],
3917 },
3918 commits: {
3919 nodes: [
3920 {
3921 commit: {
3922 statusCheckRollup: {
3923 contexts: {
3924 nodes: [
3925 checkRun({
3926 name: "build",
3927 status: "COMPLETED",
3928 conclusion: "SUCCESS",
3929 checkSuite: { workflowRun: { workflow: { name: "linux" } } },
3930 }),
3931 checkRun({
3932 name: "build",
3933 status: "COMPLETED",
3934 conclusion: "FAILURE",
3935 checkSuite: { workflowRun: { workflow: { name: "windows" } } },
3936 }),
3937 ],
3938 pageInfo: { hasNextPage: false, endCursor: null },
3939 },
3940 },
3941 },
3942 },
3943 ],
3944 },
3945 }),
3946 ),
3947 ),
3948 ),
3949 );
3950 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3951 const detail = yield* cli.getPullRequestDetail({
3952 cwd: "/w",
3953 repository: "acme/web",
3954 host: "github.com",
3955 number: 7,
3956 });
3957 expect(mockedExecute).toHaveBeenCalledOnce();
3958 expect(detail.comparison).toBeNull();
3959 expect(detail.reviewRequestLogins).toEqual(["reviewer"]);
3960 expect(detail.hasTeamReviewRequest).toBe(true);
3961 expect(detail.reviewRequestTeams).toEqual([
3962 {
3963 login: "octo/maintainers",
3964 name: "Maintainers",
3965 avatarUrl: "https://avatars.githubusercontent.com/t/1",
3966 },
3967 ]);
3968 expect(detail.labels).toEqual([
3969 { name: "bug", color: "ff0000", description: "Something is broken" },
3970 ]);
3971 expect(detail.checks).toHaveLength(2);
3972 expect(detail.checksState).toBe("failing");
3973 }),
3974 );
3975
3976 const unresolvedCore = {
3977 ...coreResponse({ baseRef: { compare: null } }),
3978 errors: [unresolvedPullRef],
3979 };
3980 it.effect.each([
3981 { description: "alone", answers: [unresolvedCore], requestedReviewers: [100] },
3982 {
3983 description: "beside a refused reviewer",
3984 answers: [
3985 { ...unresolvedCore, errors: [unresolvedPullRef, refusedReviewer] },
3986 unresolvedCore,
3987 ],
3988 requestedReviewers: [100, 0],
3989 },
3990 ])(
3991 "reads a pull request without a pull ref, its comparison unknown ($description)",
3992 ({ answers, requestedReviewers }) =>
3993 Effect.gen(function* () {
3994 for (const answer of answers)
3995 mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(answer))));
3996 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3997 const detail = yield* cli.getPullRequestDetail(pullRequestInput);
3998 expect(detail.number).toBe(7);
3999 expect(detail.comparison).toBeNull();
4000 expect(variablesOf("PullRequestCore").map((v) => v["requestedReviewers"])).toEqual(
4001 requestedReviewers,
4002 );
4003 }),
4004 );
4005
4006 it.effect("fails a missing pull ref beside another error, in GitHub's words", () =>
4007 Effect.gen(function* () {
4008 const refusedChecks = {
4009 type: "FORBIDDEN",
4010 message: "Resource not accessible by integration",
4011 path: ["repository", "pullRequest", "commits", "nodes", 0, "commit", "statusCheckRollup"],
4012 };
4013 mockedExecute.mockReturnValueOnce(
4014 Effect.succeed(
4015 output(encodeJson({ ...unresolvedCore, errors: [unresolvedPullRef, refusedChecks] })),
4016 ),
4017 );
4018 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4019 const error = yield* Effect.flip(cli.getPullRequestDetail(pullRequestInput));
4020 expect(error).toMatchObject({
4021 _tag: "GitHubApiResponseError",
4022 status: 200,
4023 githubErrors: [
4024 "Could not resolve head ref 'refs/pull/7/head'. (at repository.pullRequest.baseRef.compare)",
4025 "Resource not accessible by integration (at repository.pullRequest.commits.nodes.0.commit.statusCheckRollup)",
4026 ],
4027 });
4028 }),
4029 );
4030
4031 it.effect("still reads a pull request GitHub cannot find as missing, in GitHub's words", () =>
4032 Effect.gen(function* () {
4033 const { data } = coreResponse();
4034 mockedExecute.mockReturnValueOnce(
4035 Effect.succeed(
4036 output(
4037 encodeJson({
4038 data: { repository: { ...data.repository, pullRequest: null } },
4039 errors: [
4040 {
4041 type: "NOT_FOUND",
4042 message: "Could not resolve to a PullRequest with the number of 7.",
4043 path: ["repository", "pullRequest"],
4044 },
4045 ],
4046 }),
4047 ),
4048 ),
4049 );
4050 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4051 const error = yield* Effect.flip(cli.getPullRequestDetail(pullRequestInput));
4052 expect(error).toMatchObject({
4053 _tag: "GitHubApiNotFoundError",
4054 githubErrors: [
4055 "Could not resolve to a PullRequest with the number of 7. (at repository.pullRequest)",
4056 ],
4057 });
4058 }),
4059 );
4060
4061 it.effect.each([false, true])(
4062 "continues after the core check page without reading it twice (reviewer refusal: %s)",
4063 (refused) =>
4064 Effect.gen(function* () {
4065 if (refused) mockedExecute.mockReturnValueOnce(refusedReviewerResponse());
4066 mockedExecute.mockReturnValueOnce(
4067 Effect.succeed(
4068 output(
4069 encodeJson(
4070 coreResponse({
4071 commits: {
4072 nodes: [
4073 {
4074 commit: {
4075 statusCheckRollup: {
4076 contexts: {
4077 nodes: [checkRun({ name: "first", conclusion: "SUCCESS" })],
4078 pageInfo: { hasNextPage: true, endCursor: "c1" },
4079 },
4080 },
4081 },
4082 },
4083 ],
4084 },
4085 }),
4086 ),
4087 ),
4088 ),
4089 );
4090 mockedExecute.mockReturnValueOnce(
4091 Effect.succeed(
4092 output(checkContextsPage([checkRun({ name: "last", conclusion: "FAILURE" })], null)),
4093 ),
4094 );
4095 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4096 const read = cli.getPullRequestDetail({
4097 ...pullRequestInput,
4098 repository: `acme/refused-checks-${refused}`,
4099 });
4100 const detail = yield* read;
4101 expect(detail.reviewRequestLogins).toEqual([]);
4102 expect(detail.reviewRequestTeams).toEqual([]);
4103 expect(detail.hasTeamReviewRequest).toBe(false);
4104 if (refused)
4105 expect(variablesOf("PullRequestCore").map((v) => v["requestedReviewers"])).toEqual([
4106 100, 0,
4107 ]);
4108 expect(detail.checks.map((check) => check.name).sort()).toEqual(["first", "last"]);
4109 expect(detail.checksState).toBe("failing");
4110 expect(detail.checksTruncated).toBe(false);
4111 expect(variablesOf("CheckContexts")).toEqual([
4112 expect.objectContaining({ number: 7, after: "c1" }),
4113 ]);
4114 expect(mockedExecute).toHaveBeenCalledTimes(refused ? 3 : 2);
4115
4116 if (refused) {
4117 mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(coreResponse()))));
4118 yield* read;
4119 expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 0 });
4120 expect(mockedExecute).toHaveBeenCalledTimes(4);
4121 }
4122 }),
4123 );
4124
4125 it.effect.each([false, true])(
4126 "refuses to combine checks from different head revisions (reviewer refusal: %s)",
4127 (refused) =>
4128 Effect.gen(function* () {
4129 if (refused) mockedExecute.mockReturnValueOnce(refusedReviewerResponse());
4130 const response = coreResponse({
4131 commits: {
4132 nodes: [
4133 {
4134 commit: {
4135 statusCheckRollup: {
4136 contexts: {
4137 nodes: [],
4138 pageInfo: { hasNextPage: true, endCursor: "c1" },
4139 },
4140 },
4141 },
4142 },
4143 ],
4144 },
4145 });
4146 mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(response))));
4147 mockedExecute.mockReturnValueOnce(
4148 Effect.succeed(output(checkContextsPage([], null, "new-head"))),
4149 );
4150 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4151 const error = yield* Effect.flip(
4152 cli.getPullRequestDetail({
4153 cwd: "/w",
4154 repository: `acme/head-changed-${refused}`,
4155 host: "github.com",
4156 number: 7,
4157 }),
4158 );
4159 expect(error._tag).toBe("GitHubPullRequestReadError");
4160 }),
4161 );
4162
4163 it.effect("preserves the reserve for automatic detail reads and allows manual checks", () =>
4164 Effect.gen(function* () {
4165 const response = coreResponse();
4166 mockedExecute.mockReturnValue(
4167 Effect.succeed(output(encodeJson(response), false, false, graphqlQuota(499))),
4168 );
4169 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4170 const input = {
4171 cwd: "/w",
4172 repository: "acme/web",
4173 host: "github.core-reserve.test",
4174 number: 7,
4175 };
4176 yield* cli.getPullRequestDetail(input);
4177 const error = yield* Effect.flip(cli.getPullRequestDetail(input));
4178 expect(error._tag).toBe("SourceControlRateLimitPausedError");
4179 expect(mockedExecute).toHaveBeenCalledOnce();
4180 yield* cli
4181 .getPullRequestDetail(input)
4182 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
4183 expect(mockedExecute).toHaveBeenCalledTimes(2);
4184 }),
4185 );
4186
4187 it.effect("fails a files page too large to read rather than calling the diff whole", () =>
4188 Effect.gen(function* () {
4189 mockedExecute.mockReturnValueOnce(Effect.fail(diffRefused));
4190 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestFiles(1, 1), true)));
4191 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4192
4193 const error = yield* Effect.flip(
4194 cli.getPullRequestDiff({
4195 cwd: "/w",
4196 repository: "acme/web",
4197 host: "github.com",
4198 number: 7,
4199 }),
4200 );
4201
4202 assert.strictEqual(error, diffRefused);
4203 }),
4204 );
4205
4206 it.effect("pages an oversized patch by file rather than handing back a severed one", () =>
4207 Effect.gen(function* () {
4208 mockedExecute.mockReturnValueOnce(
4209 Effect.succeed(output("diff --git a/a b/a\n@@ -1 +1 @@", true)),
4210 );
4211 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequestFiles(1, 1))));
4212 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4213
4214 const slice = yield* cli.getPullRequestDiff({
4215 cwd: "/w",
4216 repository: "acme/web",
4217 host: "github.com",
4218 number: 7,
4219 });
4220
4221 assert.strictEqual(pathAt(1), "repos/acme/web/pulls/7/files?per_page=30&page=1");
4222 expect(slice.patch).toContain("src/file1.ts");
4223 expect(slice.patch).not.toContain("diff --git a/a b/a");
4224 assert.isTrue(slice.withheldFilesReadable);
4225 assert.strictEqual(mockedExecute.mock.calls.length, 2);
4226 }),
4227 );
4228
4229 it.effect("follows the cursor to the review threads the first page left behind", () =>
4230 Effect.gen(function* () {
4231 mockedExecute.mockReturnValueOnce(
4232 Effect.succeed(
4233 output(
4234 reviewThreadsPage([thread("PRRT_1", "c1")], "Y3Vyc29yOjE", [
4235 { __typename: "User", login: "prior", name: null, avatarUrl: "https://avatars/p" },
4236 ]),
4237 ),
4238 ),
4239 );
4240 mockedExecute.mockReturnValueOnce(
4241 Effect.succeed(
4242 output(
4243 reviewThreadsPage(
4244 [
4245 {
4246 ...thread("PRRT_2", "c2"),
4247 comments: threadComments(["c2"], null, 1, {
4248 __typename: "Bot",
4249 login: "later-bot",
4250 avatarUrl: "https://avatars/later-bot",
4251 }),
4252 },
4253 ],
4254 null,
4255 ),
4256 ),
4257 ),
4258 );
4259 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4260
4261 const conversation = yield* cli.listReviewThreadComments({
4262 cwd: "/w",
4263 repository: "acme/web",
4264 host: "github.com",
4265 number: 7,
4266 });
4267
4268 expect(callAt(0)).toMatchObject({ operationName: "ReviewThreads" });
4269 // Later pages ask for the threads alone and keep the first page's PR-wide fields.
4270 const later = callAt(1);
4271 assert(later.kind === "graphql");
4272 expect(later).toMatchObject({
4273 operationName: "ReviewThreadPages",
4274 variables: { after: "Y3Vyc29yOjE" },
4275 });
4276 for (const field of ["reviewRequests", "commits(", "reviewDismissals", "latestReviews"])
4277 expect(later.query).not.toContain(field);
4278 expect(conversation.comments.map((comment) => comment.id)).toEqual(["c1", "c2"]);
4279 expect(conversation.reviewers.map((reviewer) => reviewer.login)).toEqual(["prior"]);
4280 expect(conversation.avatarsByLogin.get("later-bot")).toBe("https://avatars/later-bot");
4281 expect(conversation.botLogins.has("later-bot")).toBe(true);
4282 assert.isFalse(conversation.truncated);
4283 }),
4284 );
4285
4286 it.effect("stops at the thread bound and says the conversation was cut short", () =>
4287 Effect.gen(function* () {
4288 mockedExecute.mockReturnValue(
4289 Effect.succeed(
4290 output(
4291 reviewThreadsPage(
4292 [{ ...thread("PRRT_1", "c1"), comments: threadComments(["c1"], "Y3Vyc29yOjI", 3) }],
4293 "Y3Vyc29yOjE",
4294 ),
4295 ),
4296 ),
4297 );
4298 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4299
4300 const conversation = yield* cli.listReviewThreadComments({
4301 cwd: "/w",
4302 repository: "acme/web",
4303 host: "github.com",
4304 number: 7,
4305 });
4306
4307 assert.strictEqual(mockedExecute.mock.calls.length, 10);
4308 assert.isTrue(conversation.truncated);
4309 assert.isTrue(conversation.reviewThreadsTruncated);
4310 }),
4311 );
4312
4313 it.effect("leaves a long thread paged until the reader asks for more", () =>
4314 Effect.gen(function* () {
4315 mockedExecute.mockReturnValueOnce(
4316 Effect.succeed(
4317 output(
4318 reviewThreadsPage(
4319 [{ ...thread("PRRT_1", "c1"), comments: threadComments(["c1"], "Y3Vyc29yOjI", 3) }],
4320 null,
4321 ),
4322 ),
4323 ),
4324 );
4325 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4326
4327 const conversation = yield* cli.listReviewThreadComments({
4328 cwd: "/w",
4329 repository: "acme/web",
4330 host: "github.com",
4331 number: 7,
4332 });
4333
4334 assert.strictEqual(mockedExecute.mock.calls.length, 1);
4335 expect(conversation.comments.map((comment) => comment.id)).toEqual(["c1"]);
4336 expect(conversation.reviewThreads[0]).toMatchObject({
4337 commentCount: 3,
4338 nextCommentsCursor: "Y3Vyc29yOjI",
4339 });
4340 assert.isTrue(conversation.truncated);
4341 assert.isFalse(conversation.reviewThreadsTruncated);
4342 }),
4343 );
4344
4345 it.effect("reads one requested page from a review thread cursor", () =>
4346 Effect.gen(function* () {
4347 mockedExecute.mockReturnValueOnce(
4348 Effect.succeed(output(threadCommentsPage(["c2", "c3"], null, 3))),
4349 );
4350 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4351
4352 const page = yield* cli.getReviewThreadComments({
4353 cwd: "/w",
4354 repository: "acme/web",
4355 host: "github.com",
4356 number: 7,
4357 threadId: "PRRT_1",
4358 cursor: "Y3Vyc29yOjI",
4359 });
4360
4361 expect(varsAt(0)).toMatchObject({
4362 owner: "acme",
4363 name: "web",
4364 number: 7,
4365 threadId: "PRRT_1",
4366 after: "Y3Vyc29yOjI",
4367 });
4368 assert.strictEqual(mockedExecute.mock.calls.length, 1);
4369 expect(page.comments.map((comment) => comment.id)).toEqual(["c2", "c3"]);
4370 expect(page.nextCursor).toBeNull();
4371 }),
4372 );
4373
4374 it.effect("refuses a review thread from another pull request", () =>
4375 Effect.gen(function* () {
4376 mockedExecute.mockReturnValueOnce(
4377 Effect.succeed(output(threadCommentsPage(["foreign"], null, 1, "PR_8"))),
4378 );
4379 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4380
4381 const error = yield* Effect.flip(
4382 cli.getReviewThreadComments({
4383 cwd: "/w",
4384 repository: "acme/web",
4385 host: "github.com",
4386 number: 7,
4387 threadId: "PRRT_FOREIGN",
4388 cursor: "Y3Vyc29yOjI",
4389 }),
4390 );
4391
4392 assert.strictEqual(error._tag, "GitHubSubjectScopeError");
4393 }),
4394 );
4395
4396 it.effect("stops GraphQL reads at the protected reserve until reset", () =>
4397 Effect.gen(function* () {
4398 mockedExecute.mockReturnValue(
4399 Effect.succeed(
4400 output(
4401 encodeJson({
4402 data: {
4403 repository: {
4404 mergeCommitAllowed: true,
4405 squashMergeAllowed: false,
4406 rebaseMergeAllowed: true,
4407 autoMergeAllowed: true,
4408 viewerPermission: "READ",
4409 pullRequest: {
4410 viewerCanUpdate: true,
4411 viewerDidAuthor: true,
4412 headRepository: null,
4413 },
4414 },
4415 },
4416 }),
4417 false,
4418 false,
4419 graphqlQuota(499),
4420 ),
4421 ),
4422 );
4423 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4424 const input = {
4425 cwd: "/w",
4426 repository: "acme/web",
4427 host: "github.com",
4428 number: 7,
4429 } as const;
4430
4431 yield* cli.getViewerAccess(input);
4432
4433 const error = yield* Effect.flip(cli.getViewerAccess(input));
4434
4435 assert.strictEqual(error._tag, "SourceControlRateLimitPausedError");
4436 if (error._tag !== "SourceControlRateLimitPausedError") return;
4437 assert.strictEqual(error.host, "github.com");
4438 assert.strictEqual(error.retryAt, Date.parse("2099-08-13T14:00:00Z"));
4439 assert.strictEqual(mockedExecute.mock.calls.length, 1);
4440 yield* TestClock.setTime(Date.parse("2100-01-01T00:00:00Z"));
4441 }),
4442 );
4443
4444 it.effect("reads who may review and who already has in one request", () =>
4445 Effect.gen(function* () {
4446 mockedExecute.mockReturnValue(
4447 Effect.succeed(
4448 output(
4449 encodeJson({
4450 data: {
4451 repository: {
4452 assignableUsers: {
4453 pageInfo: { hasNextPage: false },
4454 nodes: ["bilal", "octocat", "hubot"].map((login) => ({
4455 login,
4456 name: null,
4457 avatarUrl: `https://avatars/${login}`,
4458 })),
4459 },
4460 pullRequest: {
4461 author: { __typename: "User", login: "bilal" },
4462 reviewRequests: {
4463 nodes: [
4464 {
4465 requestedReviewer: {
4466 __typename: "User",
4467 login: "octocat",
4468 name: null,
4469 avatarUrl: "https://avatars/octocat",
4470 },
4471 },
4472 ],
4473 },
4474 },
4475 },
4476 },
4477 }),
4478 ),
4479 ),
4480 );
4481 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4482
4483 const list = yield* cli.listReviewerCandidates({
4484 cwd: "/w",
4485 repository: "acme/web",
4486 host: "github.com",
4487 number: 7,
4488 });
4489
4490 assert.strictEqual(mockedExecute.mock.calls.length, 1);
4491 expect(varsAt(0)).toMatchObject({ owner: "acme", name: "web", number: 7 });
4492 expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([
4493 ["octocat", true],
4494 ["hubot", false],
4495 ]);
4496 }),
4497 );
4498
4499 it.effect("asks GitHub to search everyone assignable when the reviewer menu has a query", () =>
4500 Effect.gen(function* () {
4501 mockedExecute.mockReturnValue(
4502 Effect.succeed(
4503 output(
4504 encodeJson({
4505 data: {
4506 repository: {
4507 assignableUsers: {
4508 pageInfo: { hasNextPage: false },
4509 nodes: [{ login: "octocat", name: null, avatarUrl: "https://avatars/octocat" }],
4510 },
4511 pullRequest: {
4512 author: { __typename: "User", login: "bilal" },
4513 reviewRequests: {
4514 nodes: ["octocat", "unrelated"].map((login) => ({
4515 requestedReviewer: {
4516 __typename: "User",
4517 login,
4518 name: null,
4519 avatarUrl: "https://avatars/user",
4520 },
4521 })),
4522 },
4523 },
4524 },
4525 },
4526 }),
4527 ),
4528 ),
4529 );
4530 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4531
4532 const list = yield* cli.listReviewerCandidates({
4533 cwd: "/w",
4534 repository: "acme/web",
4535 host: "github.com",
4536 number: 7,
4537 query: "octo",
4538 });
4539
4540 expect(varsAt(0)).toMatchObject({ owner: "acme", name: "web", number: 7, query: "octo" });
4541 expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([
4542 ["octocat", true],
4543 ]);
4544 }),
4545 );
4546
4547 it.effect("takes labels off one at a time, naming each in the path encoded", () =>
4548 Effect.gen(function* () {
4549 mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
4550 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4551
4552 yield* cli.setLabels({
4553 cwd: "/w",
4554 repository: "acme/web",
4555 host: "github.com",
4556 number: 7,
4557 labels: ["good first issue", "area/web"],
4558 applied: false,
4559 });
4560
4561 assert.strictEqual(mockedExecute.mock.calls.length, 2);
4562 expect(callAt(0)).toMatchObject({
4563 method: "DELETE",
4564 path: "repos/acme/web/issues/7/labels/good%20first%20issue",
4565 });
4566 expect(callAt(1)).toMatchObject({
4567 method: "DELETE",
4568 path: "repos/acme/web/issues/7/labels/area%2Fweb",
4569 });
4570 }),
4571 );
4572
4573 it.effect("reads every page of viewed files, and says so when there are too many", () =>
4574 Effect.gen(function* () {
4575 const page = (index: number, hasNextPage: boolean) =>
4576 Effect.succeed(
4577 output(
4578 encodeJson({
4579 data: {
4580 repository: {
4581 pullRequest: {
4582 files: {
4583 pageInfo: { hasNextPage, endCursor: `cursor-${index}` },
4584 nodes: [
4585 { path: `src/file${index}.ts`, viewerViewedState: "VIEWED" },
4586 { path: `src/other${index}.ts`, viewerViewedState: "UNVIEWED" },
4587 ],
4588 },
4589 },
4590 },
4591 },
4592 }),
4593 ),
4594 );
4595 mockedExecute
4596 .mockReturnValueOnce(page(0, true))
4597 .mockReturnValueOnce(page(1, true))
4598 .mockReturnValueOnce(page(2, false));
4599 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4600
4601 const viewed = yield* cli.getPullRequestFilesViewed({
4602 cwd: "/w",
4603 repository: "acme/web",
4604 host: "github.com",
4605 number: 7,
4606 });
4607
4608 assert.strictEqual(mockedExecute.mock.calls.length, 3);
4609 expect([varsAt(0)["after"], varsAt(1)["after"], varsAt(2)["after"]]).toEqual([
4610 undefined,
4611 "cursor-0",
4612 "cursor-1",
4613 ]);
4614 assert.isFalse(viewed.truncated);
4615 expect(viewed.files.map((file) => [file.path, file.state])).toEqual([
4616 ["src/file0.ts", "viewed"],
4617 ["src/other0.ts", "unviewed"],
4618 ["src/file1.ts", "viewed"],
4619 ["src/other1.ts", "unviewed"],
4620 ["src/file2.ts", "viewed"],
4621 ["src/other2.ts", "unviewed"],
4622 ]);
4623 }),
4624 );
4625
4626 it.effect("stops paging viewed files rather than following a change without end", () =>
4627 Effect.gen(function* () {
4628 mockedExecute.mockReturnValue(
4629 Effect.succeed(
4630 output(
4631 encodeJson({
4632 data: {
4633 repository: {
4634 pullRequest: {
4635 files: {
4636 pageInfo: { hasNextPage: true, endCursor: "cursor" },
4637 nodes: [{ path: "src/file.ts", viewerViewedState: "VIEWED" }],
4638 },
4639 },
4640 },
4641 },
4642 }),
4643 ),
4644 ),
4645 );
4646 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4647
4648 const viewed = yield* cli.getPullRequestFilesViewed({
4649 cwd: "/w",
4650 repository: "acme/web",
4651 host: "github.com",
4652 number: 7,
4653 });
4654
4655 assert.strictEqual(mockedExecute.mock.calls.length, 2);
4656 assert.isTrue(viewed.truncated);
4657 }),
4658 );
4659
4660 it.effect("does not remember a node id lookup that failed", () =>
4661 Effect.gen(function* () {
4662 mockedExecute
4663 .mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')))
4664 .mockReturnValueOnce(
4665 Effect.succeed(
4666 output(encodeJson({ data: { repository: { pullRequest: { id: "PR_25" } } } })),
4667 ),
4668 )
4669 .mockReturnValueOnce(Effect.succeed(output("{}")));
4670 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4671 const write = () =>
4672 cli.setPullRequestFilesViewed({
4673 cwd: "/w",
4674 repository: "acme/web",
4675 host: "github.com",
4676 number: 25,
4677 files: [{ path: "src/a.ts", viewed: true }],
4678 });
4679
4680 const error = yield* Effect.flip(write());
4681 assert.strictEqual(error._tag, "GitHubPullRequestReadError");
4682
4683 yield* write();
4684
4685 assert.strictEqual(mockedExecute.mock.calls.length, 3);
4686 expect(varsAt(2)["_0_pullRequestId"]).toEqual("PR_25");
4687 }),
4688 );
4689 it.effect("keeps the pull request being ticked through, not the one looked up first", () =>
4690 Effect.gen(function* () {
4691 const HOT = 9_000;
4692 const lookupsOf = new Map<number, number>();
4693 mockedExecute.mockImplementation((input) => {
4694 if (input.kind !== "graphql" || input.operationName !== NODE_ID_QUERY) {
4695 return Effect.succeed(output("{}"));
4696 }
4697 const number = Number(input.variables?.["number"]);
4698 lookupsOf.set(number, (lookupsOf.get(number) ?? 0) + 1);
4699 return Effect.succeed(
4700 output(encodeJson({ data: { repository: { pullRequest: { id: `PR_${number}` } } } })),
4701 );
4702 });
4703 const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
4704 const tick = (number: number) =>
4705 cli.setPullRequestFilesViewed({
4706 cwd: "/w",
4707 repository: "acme/web",
4708 host: "github.com",
4709 number,
4710 files: [{ path: "src/a.ts", viewed: true }],
4711 });
4712
4713 yield* tick(HOT);
4714 for (let filled = 0; filled < GitHubPullRequestApi.NODE_ID_CACHE_CAPACITY; filled += 1) {
4715 yield* tick(HOT + 1 + filled);
4716 yield* tick(HOT);
4717 }
4718
4719 assert.strictEqual(lookupsOf.get(HOT), 1);
4720 }),
4721 );
4722 });