Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Redacted from "effect/Redacted";
5import * as TestClock from "effect/testing/TestClock";
6import { SourceControlProviderKind, type PullRequestReaction } from "@t3tools/contracts";
7
8import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
9import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
10import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
11import type {
12 GitHubPullRequestCore,
13 GitHubPullRequestSearchItem,
14} from "./gitHubPullRequestJson.ts";
15import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
16import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
17
18const coreFields = {
19 maintainerCanModify: true,
20 canEditMaintainerEdits: false,
21 reviewRequestTeams: [],
22 checksTruncated: false,
23 comparison: { behindBy: 0, viewerCanUpdate: true },
24 viewerAccess: {
25 canWrite: true,
26 canTriage: true,
27 canUpdate: true,
28 didAuthor: false,
29 mergeCapabilities: { merge: true, squash: true, rebase: true },
30 autoMergeAllowed: true,
31 },
32};
33
34it.effect("maps credential verification failures without relabeling operation failures", () =>
35 Effect.gen(function* () {
36 let verificationFails = true;
37 let operations = 0;
38 const provider = yield* make.pipe(
39 Effect.provide(
40 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
41 revalidateChecks: (_input, read) => read,
42 withVerifiedCredential: (_input, use) =>
43 verificationFails
44 ? Effect.fail(
45 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({
46 cwd: "/w",
47 }),
48 )
49 : use({ accountId: "123", viewer: "viewer", credentialFingerprint: "fingerprint" }),
50 }),
51 ),
52 );
53 const verify = provider.withVerifiedCredential;
54 if (verify === undefined)
55 return yield* Effect.die("credential verification was not implemented");
56 const input = { cwd: "/w", host: "github.com" };
57 const operation = () =>
58 Effect.sync(() => {
59 operations++;
60 }).pipe(Effect.andThen(Effect.fail("operation-failed")));
61 expect(yield* verify(input, operation).pipe(Effect.flip)).toMatchObject({
62 _tag: "PullRequestProviderError",
63 operation: "routeIdentity",
64 });
65 expect(operations).toBe(0);
66 verificationFails = false;
67 expect(yield* verify(input, operation).pipe(Effect.flip)).toBe("operation-failed");
68 expect(operations).toBe(1);
69 }),
70);
71
72it.effect.each([
73 { status: 403, githubErrorTypes: [], reason: "forbidden" },
74 { status: 503, githubErrorTypes: [], reason: "failed" },
75 { status: 200, githubErrorTypes: ["FORBIDDEN"], reason: "forbidden" },
76 { status: 200, githubErrorTypes: ["INTERNAL"], reason: "failed" },
77 { status: 200, githubErrorTypes: ["FORBIDDEN", "NOT_FOUND"], reason: "forbidden" },
78 { status: 200, githubErrorTypes: ["FORBIDDEN", "INTERNAL"], reason: "failed" },
79 { status: 200, githubErrorTypes: ["FORBIDDEN", null], reason: "failed" },
80])("classifies GitHub response $status as $reason", ({ status, githubErrorTypes, reason }) =>
81 Effect.gen(function* () {
82 const provider = yield* make.pipe(
83 Effect.provide(
84 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
85 revalidateChecks: (_input, read) => read,
86 getPullRequestDetail: () =>
87 Effect.fail(
88 new GitHubRequestPolicy.GitHubApiResponseError({
89 host: "github.com",
90 operation: "detail",
91 status,
92 githubErrorTypes,
93 }),
94 ),
95 }),
96 ),
97 );
98 const error = yield* provider
99 .getChangeRequest({
100 cwd: "/w",
101 repository: "acme/web",
102 host: "github.com",
103 number: 7,
104 })
105 .pipe(Effect.flip);
106 expect(error.reason).toBe(reason);
107 }),
108);
109
110it.effect("advertises standalone branch deletion for source repository writers", () =>
111 Effect.gen(function* () {
112 let action: string | undefined;
113 const provider = yield* make.pipe(
114 Effect.provide(
115 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
116 runPullRequestAction: (input) =>
117 Effect.sync(() => {
118 action = input.action;
119 }),
120 }),
121 ),
122 );
123 expect(provider.capabilities.deleteBranch).toBe(true);
124 expect(provider.capabilities.actions).toContain("delete-branch");
125 yield* provider.runAction({
126 cwd: "/w",
127 repository: "acme/web",
128 host: "github.com",
129 number: 7,
130 action: "delete-branch",
131 });
132 expect(action).toBe("delete-branch");
133 const access = {
134 canWrite: false,
135 canTriage: false,
136 canUpdate: false,
137 didAuthor: false,
138 canDeleteBranch: true,
139 autoMergeAllowed: true,
140 };
141 expect(gitHubViewerPermissions(access).actions).toContain("delete-branch");
142 expect(
143 gitHubViewerPermissions({
144 ...access,
145 canWrite: true,
146 didAuthor: true,
147 canDeleteBranch: false,
148 }).actions,
149 ).not.toContain("delete-branch");
150 }),
151);
152
153describe("gitHubViewerPermissions", () => {
154 it("offers everything to a viewer who can write to the repository", () => {
155 expect(
156 gitHubViewerPermissions({
157 canWrite: true,
158 canDeleteBranch: true,
159 canTriage: true,
160 canUpdate: true,
161 didAuthor: false,
162 autoMergeAllowed: true,
163 }),
164 ).toEqual({
165 actions: [
166 "delete-branch",
167 "merge",
168 "enable-auto-merge",
169 "disable-auto-merge",
170 "revert",
171 "approve-workflows",
172 "ready",
173 "draft",
174 "close",
175 "reopen",
176 ],
177 comment: true,
178 resolve: true,
179 stackRebase: true,
180 verdicts: ["comment", "approve", "request-changes"],
181 requestReviewers: true,
182 labels: true,
183 });
184 });
185
186 it("leaves a passer-by on a repository they can only read nothing but the review", () => {
187 expect(
188 gitHubViewerPermissions({
189 canWrite: false,
190 canTriage: false,
191 canUpdate: false,
192 didAuthor: false,
193 autoMergeAllowed: true,
194 }),
195 ).toEqual({
196 actions: [],
197 comment: true,
198 resolve: false,
199 verdicts: ["comment", "approve", "request-changes"],
200 requestReviewers: false,
201 labels: false,
202 });
203 });
204
205 it("lets a triager label without letting them merge or ask for a review", () => {
206 const permissions = gitHubViewerPermissions({
207 canWrite: false,
208 canTriage: true,
209 canUpdate: false,
210 didAuthor: false,
211 autoMergeAllowed: true,
212 });
213 expect(permissions.labels).toBe(true);
214 expect(permissions.requestReviewers).toBe(false);
215 expect(permissions.actions).toEqual([]);
216 });
217
218 it("keeps an author's own pull request theirs to close, with read access and no more", () => {
219 expect(
220 gitHubViewerPermissions({
221 canWrite: false,
222 canTriage: false,
223 canUpdate: true,
224 didAuthor: true,
225 autoMergeAllowed: true,
226 }),
227 ).toEqual({
228 actions: ["ready", "draft", "close", "reopen"],
229 comment: true,
230 resolve: true,
231 verdicts: ["comment"],
232 requestReviewers: false,
233 labels: false,
234 });
235 });
236
237 it.effect("uses the permissions carried by the core read without a second request", () =>
238 Effect.gen(function* () {
239 const provider = yield* make;
240 const detail = yield* provider.getChangeRequest({
241 cwd: "/w",
242 repository: "acme/web",
243 host: "github.com",
244 number: 7,
245 });
246
247 expect(detail.viewerPermissions).toEqual({
248 maintainerEdits: false,
249 actions: ["ready", "draft", "close", "reopen"],
250 comment: true,
251 resolve: false,
252 verdicts: ["comment", "approve", "request-changes"],
253 requestReviewers: false,
254 labels: false,
255 });
256 expect(detail.workflowApprovalsRequired).toBeUndefined();
257 expect(detail.checks).toContainEqual({
258 name: "Workflow approval status",
259 status: "action-required",
260 description: "GitHub could not determine whether workflows are awaiting approval.",
261 url: null,
262 placeholder: true,
263 });
264 for (const fingerprint of ["broad", "restricted", "broad"]) {
265 const scoped = yield* provider
266 .getChangeRequest({
267 cwd: "/w",
268 repository: "acme/web",
269 host: "github.com",
270 number: 7,
271 })
272 .pipe(
273 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
274 host: "github.com",
275 token: Redacted.make("credential"),
276 credentialFingerprint: fingerprint,
277 }),
278 );
279 expect(scoped.mergeCapabilities.squash).toBe(fingerprint !== "restricted");
280 }
281 }).pipe(
282 Effect.provide(
283 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
284 revalidateChecks: (_input, read) => read,
285 getPullRequestDetail: () =>
286 Effect.succeed({
287 ...coreFields,
288 comparison: null,
289 viewerAccess: { ...coreFields.viewerAccess, canWrite: false, canTriage: false },
290 number: 7,
291 title: "Pull request 7",
292 url: "https://github.com/acme/web/pull/7",
293 author: null,
294 isCrossRepository: true,
295 headRepositoryOwner: null,
296 headBranch: "feat/page",
297 baseBranch: "main",
298 state: "open" as const,
299 isDraft: false,
300 mergeability: "mergeable" as const,
301 reviewDecision: null,
302 additions: 1,
303 deletions: 1,
304 createdAt: "2026-07-01T00:00:00Z",
305 updatedAt: "2026-07-02T00:00:00Z",
306 reviewRequestLogins: [],
307 hasTeamReviewRequest: false,
308 checksState: null,
309 labels: [],
310 body: "",
311 changedFiles: 1,
312 mergedAt: null,
313 closedAt: null,
314 checks: [],
315 comments: [],
316 commits: [],
317 }).pipe(
318 Effect.flatMap((detail) =>
319 GitHubRequestPolicy.PinnedGitHubCredential.pipe(
320 Effect.map((credential) => ({
321 ...detail,
322 viewerAccess: {
323 ...detail.viewerAccess,
324 mergeCapabilities: {
325 ...detail.viewerAccess.mergeCapabilities,
326 squash: credential?.credentialFingerprint !== "restricted",
327 },
328 },
329 })),
330 ),
331 ),
332 ),
333 }),
334 ),
335 ),
336 );
337
338 it.effect("keeps fork workflows awaiting approval out of the passing state", () =>
339 Effect.gen(function* () {
340 const provider = yield* make;
341 const detail = yield* provider.getChangeRequest({
342 cwd: "/w",
343 repository: "acme/web",
344 host: "github.com",
345 number: 7,
346 });
347
348 const readChecks = provider.getChangeRequestChecks;
349 if (readChecks === undefined) return yield* Effect.die("checks read missing");
350 expect(
351 yield* readChecks({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }),
352 ).toEqual({ state: detail.state, checks: detail.checks, workflowApprovalsRequired: 1 });
353 expect(detail.workflowApprovalsRequired).toBe(1);
354 expect(detail.checks).toEqual([
355 {
356 name: "manual gate",
357 status: "action-required",
358 description: null,
359 url: "https://example.com/manual-gate",
360 },
361 {
362 name: "build",
363 status: "success",
364 description: null,
365 url: null,
366 },
367 {
368 name: "contributor tests",
369 status: "action-required",
370 description: "A maintainer must approve this workflow before it can run.",
371 url: "https://github.com/acme/web/actions/runs/123",
372 },
373 ]);
374 }).pipe(
375 Effect.provide(
376 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
377 revalidateChecks: (_input, read) => read,
378 getPullRequestDetail: () =>
379 Effect.succeed({
380 ...coreFields,
381 number: 7,
382 title: "Pull request 7",
383 url: "https://github.com/acme/web/pull/7",
384 author: null,
385 isCrossRepository: true,
386 headRepositoryOwner: "octocat",
387 headSha: "abc123",
388 headBranch: "feat/page",
389 baseBranch: "main",
390 state: "open",
391 isDraft: false,
392 mergeability: "mergeable",
393 reviewDecision: null,
394 additions: 1,
395 deletions: 1,
396 createdAt: "2026-07-01T00:00:00Z",
397 updatedAt: "2026-07-02T00:00:00Z",
398 reviewRequestLogins: [],
399 hasTeamReviewRequest: false,
400 checksState: "passing",
401 labels: [],
402 body: "",
403 changedFiles: 1,
404 mergedAt: null,
405 closedAt: null,
406 checks: [
407 {
408 name: "manual gate",
409 status: "action-required",
410 description: null,
411 url: "https://example.com/manual-gate",
412 },
413 { name: "build", status: "success", description: null, url: null },
414 ],
415 comments: [],
416 commits: [],
417 }),
418 listUnfinishedWorkflowRuns: () => Effect.succeed([]),
419 listWorkflowRunsRequiringApproval: () =>
420 Effect.succeed([
421 {
422 pullRequestNumbers: [7],
423 id: 123,
424 name: "contributor tests",
425 url: "https://github.com/acme/web/actions/runs/123",
426 },
427 ]),
428 getViewerAccess: () =>
429 Effect.succeed({
430 canWrite: true,
431 canTriage: true,
432 canUpdate: true,
433 didAuthor: false,
434 mergeCapabilities: { merge: true, squash: true, rebase: true },
435 autoMergeAllowed: true,
436 }),
437 }),
438 ),
439 ),
440 );
441});
442
443const openDetail = {
444 ...coreFields,
445 number: 7,
446 title: "Pull request 7",
447 url: "https://github.com/acme/web/pull/7",
448 author: null,
449 isCrossRepository: true,
450 headRepositoryOwner: "acme",
451 headSha: "abc123",
452 headBranch: "feat/page",
453 baseBranch: "main",
454 state: "open" as const,
455 isDraft: false,
456 mergeability: "mergeable" as const,
457 reviewDecision: null,
458 additions: 1,
459 deletions: 1,
460 createdAt: "2026-07-01T00:00:00Z",
461 updatedAt: "2026-07-02T00:00:00Z",
462 reviewRequestLogins: [],
463 hasTeamReviewRequest: false,
464 checksState: null,
465 labels: [],
466 body: "",
467 changedFiles: 1,
468 mergedAt: null,
469 closedAt: null,
470 checks: [],
471 comments: [],
472 commits: [],
473};
474
475const sameRepositoryChecks = [
476 { name: "CodeRabbit", status: "skipped" as const, description: null, url: null },
477 {
478 name: "lint",
479 status: "pending" as const,
480 description: null,
481 url: "https://github.com/acme/web/actions/runs/201/job/1",
482 },
483];
484
485it.effect("adds unstarted same-repository workflow runs as pending, not as approvals", () =>
486 Effect.gen(function* () {
487 const provider = yield* make;
488 const detail = yield* provider.getChangeRequest({
489 cwd: "/w",
490 repository: "acme/web",
491 host: "github.com",
492 number: 7,
493 });
494
495 expect(detail.workflowApprovalsRequired).toBe(0);
496 expect(detail.checks).toEqual([
497 ...sameRepositoryChecks,
498 {
499 name: "CI",
500 status: "pending",
501 description: "This workflow run has not finished.",
502 url: "https://github.com/acme/web/actions/runs/202",
503 },
504 ]);
505 }).pipe(
506 Effect.provide(
507 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
508 revalidateChecks: (_input, read) => read,
509 getPullRequestDetail: () =>
510 Effect.succeed({ ...openDetail, isCrossRepository: false, checks: sameRepositoryChecks }),
511 // Run 201 is represented by its running job; run 202 is queued before any job exists.
512 listUnfinishedWorkflowRuns: () =>
513 Effect.succeed([
514 {
515 pullRequestNumbers: [],
516 id: 201,
517 name: "Lint",
518 url: "https://github.com/acme/web/actions/runs/201",
519 },
520 {
521 pullRequestNumbers: [],
522 id: 202,
523 name: "CI",
524 url: "https://github.com/acme/web/actions/runs/202",
525 },
526 ]),
527 listWorkflowRunsRequiringApproval: () => Effect.succeed([]),
528 getViewerAccess: () =>
529 Effect.succeed({
530 canWrite: true,
531 canTriage: true,
532 canUpdate: true,
533 didAuthor: false,
534 mergeCapabilities: { merge: true, squash: true, rebase: true },
535 autoMergeAllowed: true,
536 }),
537 }),
538 ),
539 ),
540);
541
542it.effect("discovers workflow approval for a same-repository bot pull request", () =>
543 Effect.gen(function* () {
544 const provider = yield* make;
545 const detail = yield* provider.getChangeRequest({
546 cwd: "/w",
547 repository: "acme/web",
548 host: "github.com",
549 number: 7,
550 });
551
552 expect(detail.workflowApprovalsRequired).toBe(1);
553 expect(detail.checks).toEqual([
554 {
555 name: "bot tests",
556 status: "action-required",
557 description: "A maintainer must approve this workflow before it can run.",
558 url: "https://github.com/acme/web/actions/runs/123",
559 },
560 ]);
561 }).pipe(
562 Effect.provide(
563 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
564 revalidateChecks: (_input, read) => read,
565 getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
566 listUnfinishedWorkflowRuns: () => Effect.succeed([]),
567 listWorkflowRunsRequiringApproval: () =>
568 Effect.succeed([
569 {
570 pullRequestNumbers: [7],
571 id: 123,
572 name: "bot tests",
573 url: "https://github.com/acme/web/actions/runs/123",
574 },
575 ]),
576 getViewerAccess: () =>
577 Effect.succeed({
578 canWrite: true,
579 canTriage: true,
580 canUpdate: true,
581 didAuthor: false,
582 mergeCapabilities: { merge: true, squash: true, rebase: true },
583 autoMergeAllowed: true,
584 }),
585 }),
586 ),
587 ),
588);
589
590it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
591 Effect.gen(function* () {
592 const provider = yield* make;
593 const detail = yield* provider.getChangeRequest({
594 cwd: "/w",
595 repository: "acme/web",
596 host: "github.com",
597 number: 7,
598 });
599
600 expect(detail.workflowApprovalsRequired).toBeUndefined();
601 expect(detail.checks).toEqual([
602 {
603 name: "Workflow approval status",
604 status: "action-required",
605 description: "GitHub could not determine whether workflows are awaiting approval.",
606 url: null,
607 placeholder: true,
608 },
609 ]);
610 }).pipe(
611 Effect.provide(
612 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
613 revalidateChecks: (_input, read) => read,
614 getPullRequestDetail: () => Effect.succeed(openDetail),
615 listUnfinishedWorkflowRuns: () => Effect.succeed([]),
616 listWorkflowRunsRequiringApproval: () =>
617 Effect.fail(
618 new GitHubPullRequestApi.GitHubWorkflowApprovalRefusedError({
619 cwd: "/w",
620 number: 7,
621 reason: "head-not-unique",
622 observedCount: 2,
623 limit: 1_000,
624 }),
625 ),
626 getViewerAccess: () =>
627 Effect.succeed({
628 canWrite: true,
629 canTriage: true,
630 canUpdate: true,
631 didAuthor: false,
632 mergeCapabilities: { merge: true, squash: true, rebase: true },
633 autoMergeAllowed: true,
634 }),
635 }),
636 ),
637 ),
638);
639
640describe("getViewerPermissions", () => {
641 const access = {
642 canWrite: true,
643 canTriage: true,
644 canUpdate: true,
645 didAuthor: false,
646 mergeCapabilities: { merge: true, squash: true, rebase: true },
647 autoMergeAllowed: true,
648 };
649
650 const layerWithDetail = (
651 detail: Effect.Effect<GitHubPullRequestCore, GitHubPullRequestApi.GitHubPullRequestApiError>,
652 onDetail: (allowReserve: boolean) => void = () => {},
653 ) =>
654 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
655 revalidateChecks: (_input, read) => read,
656 getPullRequestDetail: () =>
657 SourceControlRateLimit.Interactive.pipe(
658 Effect.tap((allowReserve) => Effect.sync(() => onDetail(allowReserve))),
659 Effect.flatMap(() => detail),
660 ),
661 getViewerAccess: () => Effect.die("Unexpected access read"),
662 });
663
664 it.effect("answers access and update-branch from the one detail read", () =>
665 Effect.gen(function* () {
666 const provider = yield* make;
667 const permissions = yield* provider.getViewerPermissions({
668 cwd: "/w",
669 repository: "acme/web",
670 host: "github.com",
671 number: 7,
672 });
673
674 expect(permissions.actions).toContain("merge");
675 expect(permissions.actions).toContain("update-branch");
676 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
677 }).pipe(
678 Effect.provide(
679 layerWithDetail(
680 Effect.succeed({ ...openDetail, comparison: { behindBy: 3, viewerCanUpdate: true } }),
681 ),
682 ),
683 ),
684 );
685
686 it.effect("still answers from the light access read when the detail read fails", () =>
687 Effect.gen(function* () {
688 const provider = yield* make;
689 const permissions = yield* provider.getViewerPermissions({
690 cwd: "/w",
691 repository: "acme/web",
692 host: "github.com",
693 number: 7,
694 });
695 expect(permissions.actions).toContain("merge");
696 expect(permissions.actions).not.toContain("update-branch");
697 }).pipe(
698 Effect.provide(
699 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
700 revalidateChecks: (_input, read) => read,
701 getPullRequestDetail: () =>
702 Effect.fail(
703 new GitHubPullRequestApi.GitHubPullRequestReadError({
704 cwd: "/w",
705 operation: "getPullRequestDetail",
706 cause: new Error("head changed"),
707 }),
708 ),
709 getViewerAccess: () => Effect.succeed(access),
710 }),
711 ),
712 ),
713 );
714
715 it.effect("withholds update-branch where GitHub could not compare the branch", () =>
716 Effect.gen(function* () {
717 const provider = yield* make;
718 const permissions = yield* provider.getViewerPermissions({
719 cwd: "/w",
720 repository: "acme/web",
721 host: "github.com",
722 number: 7,
723 });
724
725 expect(permissions.actions).not.toContain("update-branch");
726 expect(permissions.updateMethods).toBeUndefined();
727 expect(permissions.actions).toContain("merge");
728 }).pipe(Effect.provide(layerWithDetail(Effect.succeed({ ...openDetail, comparison: null })))),
729 );
730});
731
732describe("getChangeRequest commits", () => {
733 const baseDetail = {
734 number: 7,
735 title: "Pull request 7",
736 url: "https://github.com/acme/web/pull/7",
737 author: null,
738 headBranch: "feat/page",
739 baseBranch: "main",
740 state: "open" as const,
741 isDraft: false,
742 mergeability: "mergeable" as const,
743 additions: 1,
744 deletions: 1,
745 createdAt: "2026-07-01T00:00:00Z",
746 updatedAt: "2026-07-02T00:00:00Z",
747 reviewRequestLogins: [],
748 hasTeamReviewRequest: false,
749 checksState: null,
750 labels: [],
751 body: "",
752 changedFiles: 1,
753 mergedAt: null,
754 closedAt: null,
755 checks: [],
756 comments: [],
757 };
758
759 const baseThreadComments = {
760 comments: [],
761 dismissalsByReviewId: new Map<string, string>(),
762 reviewThreads: [],
763 commentCount: 0,
764 truncated: false,
765 reviewThreadsTruncated: false,
766 reactions: [],
767 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
768 editedAtById: new Map<string, string>(),
769 reviewers: [],
770 avatarsByLogin: new Map<string, string>(),
771 botLogins: new Set<string>(),
772 viewer: { canUpdate: true, didAuthor: false },
773 };
774
775 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
776 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
777 revalidateChecks: (_input, read) => read,
778 getPullRequestActivity: () =>
779 Effect.succeed({
780 author: baseDetail.author,
781 comments: baseDetail.comments,
782 commits: [
783 {
784 oid: "graphql-newest",
785 messageHeadline: "Activity metadata",
786 committedDate: "2026-07-06T00:00:00Z",
787 additions: 18,
788 deletions: 7,
789 authors: [],
790 },
791 {
792 oid: "view-oldest",
793 messageHeadline: "gh pr view's oldest commit",
794 committedDate: "2026-01-01T00:00:00Z",
795 authors: [],
796 },
797 ],
798 truncated: false,
799 }),
800 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
801 });
802
803 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
804 Effect.gen(function* () {
805 const provider = yield* make;
806 const detail = yield* provider.getChangeRequestActivity({
807 cwd: "/w",
808 repository: "acme/web",
809 host: "github.com",
810 number: 7,
811 });
812
813 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
814 expect(detail.commits[0]).toMatchObject({
815 messageHeadline: "the newest commit gh pr view drops",
816 additions: 18,
817 deletions: 7,
818 });
819 }).pipe(
820 Effect.provide(
821 layerWith([
822 {
823 oid: "graphql-newest",
824 messageHeadline: "the newest commit gh pr view drops",
825 committedDate: "2026-07-06T00:00:00Z",
826 authors: [],
827 },
828 ]),
829 ),
830 ),
831 );
832
833 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
834 Effect.gen(function* () {
835 const provider = yield* make;
836 const detail = yield* provider.getChangeRequestActivity({
837 cwd: "/w",
838 repository: "acme/web",
839 host: "github.com",
840 number: 7,
841 });
842
843 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest", "view-oldest"]);
844 }).pipe(Effect.provide(layerWith([]))),
845 );
846});
847
848describe("getChangeRequestActivity", () => {
849 const dismissedReview = (body: string) => ({
850 id: "PRR_1",
851 kind: "review" as const,
852 author: { login: "macroscopeapp", name: null, avatarUrl: null },
853 body,
854 createdAt: "2026-07-03T00:00:00Z",
855 url: null,
856 path: null,
857 reviewState: "DISMISSED",
858 });
859 const threadComments: GitHubReviewThreadComments = {
860 comments: [],
861 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
862 reviewThreads: [],
863 commentCount: 0,
864 truncated: false,
865 reviewThreadsTruncated: false,
866 reactions: [],
867 reactionsById: new Map(),
868 editedAtById: new Map([["PRR_1", "2026-07-04T00:00:00Z"]]),
869 reviewers: [],
870 avatarsByLogin: new Map(),
871 botLogins: new Set(["macroscopeapp"]),
872 commits: [],
873 viewer: { canUpdate: true, didAuthor: false },
874 };
875 const layerFor = (body: string) =>
876 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
877 revalidateChecks: (_input, read) => read,
878 getPullRequestActivity: () =>
879 Effect.succeed({
880 author: null,
881 comments: [dismissedReview(body)],
882 commits: [],
883 truncated: false,
884 }),
885 listReviewThreadComments: () => Effect.succeed(threadComments),
886 });
887 const readActivity = Effect.gen(function* () {
888 const provider = yield* make;
889 return yield* provider.getChangeRequestActivity({
890 cwd: "/w",
891 repository: "acme/web",
892 host: "github.com",
893 number: 7,
894 });
895 });
896
897 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
898 readActivity.pipe(
899 Effect.map((activity) => {
900 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
901 expect(activity.comments[0]?.author?.isBot).toBe(true);
902 expect(activity.comments[0]?.editedAt).toBe("2026-07-04T00:00:00Z");
903 }),
904 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
905 ),
906 );
907
908 const failingThreadRead = (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
909 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
910 getPullRequestActivity: () =>
911 Effect.succeed({ author: null, comments: [], commits: [], truncated: false }),
912 listReviewThreadComments: () => Effect.fail(error),
913 });
914 const retryAt = 1_900_000_000_000;
915
916 it.effect.each([
917 {
918 name: "rate limit",
919 error: new GitHubRequestPolicy.GitHubApiRateLimitError({
920 host: "github.com",
921 operation: "listReviewThreadComments",
922 retryAt,
923 }),
924 },
925 {
926 name: "rate-limit pause",
927 error: new SourceControlRateLimit.SourceControlRateLimitPausedError({
928 provider: SourceControlProviderKind.make("github"),
929 host: "github.com",
930 retryAt,
931 }),
932 },
933 ])("fails rate-limited when the review-thread read hits a $name", ({ error }) =>
934 readActivity.pipe(
935 Effect.flip,
936 Effect.map((failure) => expect(failure).toMatchObject({ reason: "rate-limited", retryAt })),
937 Effect.provide(failingThreadRead(error)),
938 ),
939 );
940
941 it.effect(
942 "keeps activity with truncated threads when the review-thread read fails otherwise",
943 () =>
944 readActivity.pipe(
945 Effect.map((activity) => {
946 expect(activity.reviewThreads).toEqual([]);
947 expect(activity.reviewThreadsTruncated).toBe(true);
948 }),
949 Effect.provide(
950 failingThreadRead(
951 new GitHubRequestPolicy.GitHubApiResponseError({
952 host: "github.com",
953 operation: "listReviewThreadComments",
954 status: 500,
955 }),
956 ),
957 ),
958 ),
959 );
960});
961
962describe("loginAvatarUrl", () => {
963 it("refuses anything that is not a login, rather than building a URL out of it", () => {
964 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
965 expect(loginAvatarUrl(login, "github.com")).toBeNull();
966 }
967 });
968});
969
970describe("listChangeRequestsAcross", () => {
971 const searched = (repository: string): GitHubPullRequestSearchItem => ({
972 repository,
973 number: 1,
974 title: "Change",
975 url: `https://github.com/${repository}/pull/1`,
976 author: null,
977 headBranch: "feature",
978 baseBranch: "main",
979 state: "open" as const,
980 isDraft: false,
981 mergeability: "mergeable" as const,
982 additions: 0,
983 deletions: 0,
984 createdAt: "2026-07-01T00:00:00Z",
985 updatedAt: "2026-07-02T00:00:00Z",
986 reviewRequestLogins: [],
987 hasTeamReviewRequest: false,
988 labels: [],
989 reviewDecision: null,
990 checksState: null,
991 });
992 const across = {
993 cwd: "/w",
994 host: "github.com",
995 repositories: ["acme/web", "acme/docs"],
996 state: "open" as const,
997 involvement: "all" as const,
998 viewer: "viewer",
999 limit: 50,
1000 };
1001 type Search = Parameters<
1002 GitHubPullRequestApi.GitHubPullRequestApi["Service"]["searchPullRequests"]
1003 >[0];
1004 // Pages answer in turn; a one-repository check for any pull request answers from `covered`.
1005 const providerAnswering = (input: {
1006 readonly pages: Array<GitHubPullRequestApi.GitHubPullRequestSearchBatch>;
1007 readonly covered?: (repository: string) => boolean;
1008 readonly checks?: Array<string>;
1009 }) =>
1010 make.pipe(
1011 Effect.provide(
1012 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
1013 searchPullRequests: (search: Search) => {
1014 if (search.state !== "all") return Effect.succeed(input.pages.shift()!);
1015 const repository = search.repositories[0]!;
1016 input.checks?.push(repository);
1017 return input.covered === undefined
1018 ? Effect.fail(
1019 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({ cwd: search.cwd }),
1020 )
1021 : Effect.succeed({
1022 items: input.covered(repository) ? [searched(repository)] : [],
1023 truncated: false,
1024 });
1025 },
1026 }),
1027 ),
1028 Effect.map((provider) => provider.listChangeRequestsAcross!),
1029 );
1030
1031 it.effect("believes silence about a repository search covers, and checks it once", () =>
1032 Effect.gen(function* () {
1033 const checks: Array<string> = [];
1034 const read = yield* providerAnswering({
1035 pages: [
1036 { items: [searched("acme/web")], truncated: false },
1037 { items: [searched("acme/web")], truncated: false },
1038 ],
1039 covered: () => true,
1040 checks,
1041 });
1042 expect((yield* read(across)).unresolved).toEqual([]);
1043 expect((yield* read(across)).unresolved).toEqual([]);
1044 expect(checks).toEqual(["acme/docs"]);
1045 }),
1046 );
1047
1048 it.effect("leaves a repository search does not cover to be read on its own", () =>
1049 Effect.gen(function* () {
1050 const read = yield* providerAnswering({
1051 pages: [{ items: [searched("acme/web")], truncated: false }],
1052 covered: (repository) => repository !== "acme/docs",
1053 });
1054 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
1055 }),
1056 );
1057
1058 it.effect("does not check a repository a page had rows for", () =>
1059 Effect.gen(function* () {
1060 const checks: Array<string> = [];
1061 const read = yield* providerAnswering({
1062 pages: [
1063 { items: [searched("acme/web"), searched("acme/docs")], truncated: false },
1064 { items: [searched("acme/web")], truncated: false },
1065 ],
1066 covered: () => true,
1067 checks,
1068 });
1069 yield* read(across);
1070 expect((yield* read(across)).unresolved).toEqual([]);
1071 expect(checks).toEqual([]);
1072 }),
1073 );
1074
1075 it.effect("vouches for no silent repository in a truncated first slice", () =>
1076 Effect.gen(function* () {
1077 const read = yield* providerAnswering({
1078 pages: [{ items: [searched("acme/web")], truncated: true }],
1079 covered: () => true,
1080 });
1081 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
1082 }),
1083 );
1084
1085 it.effect("past the first slice, believes a covered repository and not an uncovered one", () =>
1086 Effect.gen(function* () {
1087 const read = yield* providerAnswering({
1088 pages: [
1089 { items: [searched("acme/web")], truncated: true },
1090 { items: [searched("acme/web")], truncated: true },
1091 ],
1092 covered: (repository) => repository !== "acme/renamed",
1093 });
1094 const later = { ...across, cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 1 } };
1095 expect((yield* read(later)).unresolved).toEqual([]);
1096 expect(
1097 (yield* read({ ...later, repositories: ["acme/web", "acme/renamed"] })).unresolved,
1098 ).toEqual(["acme/renamed"]);
1099 }),
1100 );
1101
1102 it.effect("asks again after a failed check, and after coverage has had time to change", () =>
1103 Effect.gen(function* () {
1104 const checks: Array<string> = [];
1105 const failing = yield* providerAnswering({
1106 pages: [
1107 { items: [searched("acme/web")], truncated: false },
1108 { items: [searched("acme/web")], truncated: false },
1109 ],
1110 checks,
1111 });
1112 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
1113 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
1114 expect(checks).toEqual(["acme/docs", "acme/docs"]);
1115
1116 checks.length = 0;
1117 const read = yield* providerAnswering({
1118 pages: [
1119 { items: [searched("acme/web")], truncated: false },
1120 { items: [searched("acme/web")], truncated: false },
1121 ],
1122 covered: () => true,
1123 checks,
1124 });
1125 yield* read(across);
1126 yield* TestClock.adjust("61 minutes");
1127 yield* read(across);
1128 expect(checks).toEqual(["acme/docs", "acme/docs"]);
1129 }),
1130 );
1131});