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 changedFiles: 12,
790 authors: [],
791 },
792 {
793 oid: "view-oldest",
794 messageHeadline: "gh pr view's oldest commit",
795 committedDate: "2026-01-01T00:00:00Z",
796 authors: [],
797 },
798 ],
799 truncated: false,
800 }),
801 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
802 });
803
804 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
805 Effect.gen(function* () {
806 const provider = yield* make;
807 const detail = yield* provider.getChangeRequestActivity({
808 cwd: "/w",
809 repository: "acme/web",
810 host: "github.com",
811 number: 7,
812 });
813
814 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
815 expect(detail.commits[0]).toMatchObject({
816 messageHeadline: "the newest commit gh pr view drops",
817 additions: 18,
818 deletions: 7,
819 changedFiles: 12,
820 });
821 }).pipe(
822 Effect.provide(
823 layerWith([
824 {
825 oid: "graphql-newest",
826 messageHeadline: "the newest commit gh pr view drops",
827 committedDate: "2026-07-06T00:00:00Z",
828 authors: [],
829 },
830 ]),
831 ),
832 ),
833 );
834
835 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
836 Effect.gen(function* () {
837 const provider = yield* make;
838 const detail = yield* provider.getChangeRequestActivity({
839 cwd: "/w",
840 repository: "acme/web",
841 host: "github.com",
842 number: 7,
843 });
844
845 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest", "view-oldest"]);
846 }).pipe(Effect.provide(layerWith([]))),
847 );
848});
849
850describe("getChangeRequestActivity", () => {
851 const dismissedReview = (body: string) => ({
852 id: "PRR_1",
853 kind: "review" as const,
854 author: { login: "macroscopeapp", name: null, avatarUrl: null },
855 body,
856 createdAt: "2026-07-03T00:00:00Z",
857 url: null,
858 path: null,
859 reviewState: "DISMISSED",
860 });
861 const threadComments: GitHubReviewThreadComments = {
862 comments: [],
863 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
864 reviewThreads: [],
865 commentCount: 0,
866 truncated: false,
867 reviewThreadsTruncated: false,
868 reactions: [],
869 reactionsById: new Map(),
870 editedAtById: new Map([["PRR_1", "2026-07-04T00:00:00Z"]]),
871 reviewers: [],
872 avatarsByLogin: new Map(),
873 botLogins: new Set(["macroscopeapp"]),
874 commits: [],
875 viewer: { canUpdate: true, didAuthor: false },
876 };
877 const layerFor = (body: string) =>
878 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
879 revalidateChecks: (_input, read) => read,
880 getPullRequestActivity: () =>
881 Effect.succeed({
882 author: null,
883 comments: [dismissedReview(body)],
884 commits: [],
885 truncated: false,
886 }),
887 listReviewThreadComments: () => Effect.succeed(threadComments),
888 });
889 const readActivity = Effect.gen(function* () {
890 const provider = yield* make;
891 return yield* provider.getChangeRequestActivity({
892 cwd: "/w",
893 repository: "acme/web",
894 host: "github.com",
895 number: 7,
896 });
897 });
898
899 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
900 readActivity.pipe(
901 Effect.map((activity) => {
902 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
903 expect(activity.comments[0]?.author?.isBot).toBe(true);
904 expect(activity.comments[0]?.editedAt).toBe("2026-07-04T00:00:00Z");
905 }),
906 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
907 ),
908 );
909
910 const failingThreadRead = (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
911 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
912 getPullRequestActivity: () =>
913 Effect.succeed({ author: null, comments: [], commits: [], truncated: false }),
914 listReviewThreadComments: () => Effect.fail(error),
915 });
916 const retryAt = 1_900_000_000_000;
917
918 it.effect.each([
919 {
920 name: "rate limit",
921 error: new GitHubRequestPolicy.GitHubApiRateLimitError({
922 host: "github.com",
923 operation: "listReviewThreadComments",
924 retryAt,
925 }),
926 },
927 {
928 name: "rate-limit pause",
929 error: new SourceControlRateLimit.SourceControlRateLimitPausedError({
930 provider: SourceControlProviderKind.make("github"),
931 host: "github.com",
932 retryAt,
933 }),
934 },
935 ])("fails rate-limited when the review-thread read hits a $name", ({ error }) =>
936 readActivity.pipe(
937 Effect.flip,
938 Effect.map((failure) => expect(failure).toMatchObject({ reason: "rate-limited", retryAt })),
939 Effect.provide(failingThreadRead(error)),
940 ),
941 );
942
943 it.effect(
944 "keeps activity with truncated threads when the review-thread read fails otherwise",
945 () =>
946 readActivity.pipe(
947 Effect.map((activity) => {
948 expect(activity.reviewThreads).toEqual([]);
949 expect(activity.reviewThreadsTruncated).toBe(true);
950 }),
951 Effect.provide(
952 failingThreadRead(
953 new GitHubRequestPolicy.GitHubApiResponseError({
954 host: "github.com",
955 operation: "listReviewThreadComments",
956 status: 500,
957 }),
958 ),
959 ),
960 ),
961 );
962});
963
964describe("loginAvatarUrl", () => {
965 it("refuses anything that is not a login, rather than building a URL out of it", () => {
966 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
967 expect(loginAvatarUrl(login, "github.com")).toBeNull();
968 }
969 });
970});
971
972describe("listChangeRequests", () => {
973 it.effect("counts a team review request as the viewer's only on search rows", () =>
974 Effect.gen(function* () {
975 const teamOnly = {
976 number: 1,
977 title: "Change",
978 url: "https://github.com/acme/web/pull/1",
979 author: null,
980 headBranch: "feature",
981 baseBranch: "main",
982 state: "open" as const,
983 isDraft: false,
984 mergeability: "mergeable" as const,
985 additions: 0,
986 deletions: 0,
987 createdAt: "2026-07-01T00:00:00Z",
988 updatedAt: "2026-07-02T00:00:00Z",
989 reviewRequestLogins: ["someone-else"],
990 hasTeamReviewRequest: true,
991 labels: [],
992 reviewDecision: null,
993 checksState: null,
994 };
995 const list = (continues: boolean, involvement: "all" | "reviewing") =>
996 make.pipe(
997 Effect.provide(
998 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
999 listPullRequests: () =>
1000 Effect.succeed({ items: [teamOnly], truncated: false, continues }),
1001 }),
1002 ),
1003 Effect.flatMap((provider) =>
1004 provider.listChangeRequests({
1005 cwd: "/w",
1006 host: "github.com",
1007 repository: "acme/web",
1008 state: "open",
1009 involvement,
1010 viewer: "Viewer",
1011 limit: 50,
1012 }),
1013 ),
1014 );
1015 const searched = yield* list(true, "reviewing");
1016 expect(searched.items[0]!.reviewRequestLogins).toEqual(["someone-else", "Viewer"]);
1017 const all = yield* list(true, "all");
1018 expect(all.items[0]!.reviewRequestLogins).toEqual(["someone-else"]);
1019 // The listing fallback keeps any team's request; it cannot say the team is the viewer's.
1020 const listed = yield* list(false, "reviewing");
1021 expect(listed.items[0]!.reviewRequestLogins).toEqual(["someone-else"]);
1022 }),
1023 );
1024});
1025
1026describe("listChangeRequestsAcross", () => {
1027 const searched = (repository: string): GitHubPullRequestSearchItem => ({
1028 repository,
1029 number: 1,
1030 title: "Change",
1031 url: `https://github.com/${repository}/pull/1`,
1032 author: null,
1033 headBranch: "feature",
1034 baseBranch: "main",
1035 state: "open" as const,
1036 isDraft: false,
1037 mergeability: "mergeable" as const,
1038 additions: 0,
1039 deletions: 0,
1040 createdAt: "2026-07-01T00:00:00Z",
1041 updatedAt: "2026-07-02T00:00:00Z",
1042 reviewRequestLogins: [],
1043 hasTeamReviewRequest: false,
1044 labels: [],
1045 reviewDecision: null,
1046 checksState: null,
1047 });
1048 const across = {
1049 cwd: "/w",
1050 host: "github.com",
1051 repositories: ["acme/web", "acme/docs"],
1052 state: "open" as const,
1053 involvement: "all" as const,
1054 viewer: "viewer",
1055 limit: 50,
1056 };
1057 type Search = Parameters<
1058 GitHubPullRequestApi.GitHubPullRequestApi["Service"]["searchPullRequests"]
1059 >[0];
1060 // Pages answer in turn; a one-repository check for any pull request answers from `covered`.
1061 const providerAnswering = (input: {
1062 readonly pages: Array<GitHubPullRequestApi.GitHubPullRequestSearchBatch>;
1063 readonly covered?: (repository: string) => boolean;
1064 readonly checks?: Array<string>;
1065 }) =>
1066 make.pipe(
1067 Effect.provide(
1068 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
1069 searchPullRequests: (search: Search) => {
1070 if (search.state !== "all") return Effect.succeed(input.pages.shift()!);
1071 const repository = search.repositories[0]!;
1072 input.checks?.push(repository);
1073 return input.covered === undefined
1074 ? Effect.fail(
1075 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({ cwd: search.cwd }),
1076 )
1077 : Effect.succeed({
1078 items: input.covered(repository) ? [searched(repository)] : [],
1079 truncated: false,
1080 });
1081 },
1082 }),
1083 ),
1084 Effect.map((provider) => provider.listChangeRequestsAcross!),
1085 );
1086
1087 it.effect("believes silence about a repository search covers, and checks it once", () =>
1088 Effect.gen(function* () {
1089 const checks: Array<string> = [];
1090 const read = yield* providerAnswering({
1091 pages: [
1092 { items: [searched("acme/web")], truncated: false },
1093 { items: [searched("acme/web")], truncated: false },
1094 ],
1095 covered: () => true,
1096 checks,
1097 });
1098 expect((yield* read(across)).unresolved).toEqual([]);
1099 expect((yield* read(across)).unresolved).toEqual([]);
1100 expect(checks).toEqual(["acme/docs"]);
1101 }),
1102 );
1103
1104 it.effect("leaves a repository search does not cover to be read on its own", () =>
1105 Effect.gen(function* () {
1106 const read = yield* providerAnswering({
1107 pages: [{ items: [searched("acme/web")], truncated: false }],
1108 covered: (repository) => repository !== "acme/docs",
1109 });
1110 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
1111 }),
1112 );
1113
1114 it.effect("does not check a repository a page had rows for", () =>
1115 Effect.gen(function* () {
1116 const checks: Array<string> = [];
1117 const read = yield* providerAnswering({
1118 pages: [
1119 { items: [searched("acme/web"), searched("acme/docs")], truncated: false },
1120 { items: [searched("acme/web")], truncated: false },
1121 ],
1122 covered: () => true,
1123 checks,
1124 });
1125 yield* read(across);
1126 expect((yield* read(across)).unresolved).toEqual([]);
1127 expect(checks).toEqual([]);
1128 }),
1129 );
1130
1131 it.effect("vouches for no silent repository in a truncated first slice", () =>
1132 Effect.gen(function* () {
1133 const read = yield* providerAnswering({
1134 pages: [{ items: [searched("acme/web")], truncated: true }],
1135 covered: () => true,
1136 });
1137 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
1138 }),
1139 );
1140
1141 it.effect("counts a review requested from the viewer's team as requested from the viewer", () =>
1142 Effect.gen(function* () {
1143 const teamOnly = { ...searched("acme/web"), hasTeamReviewRequest: true };
1144 const read = yield* providerAnswering({
1145 pages: [
1146 { items: [teamOnly], truncated: false },
1147 { items: [teamOnly], truncated: false },
1148 ],
1149 covered: () => true,
1150 });
1151 const reviewing = yield* read({ ...across, involvement: "reviewing" });
1152 expect(reviewing.items[0]!.reviewRequestLogins).toEqual(["viewer"]);
1153 const all = yield* read(across);
1154 expect(all.items[0]!.reviewRequestLogins).toEqual([]);
1155 }),
1156 );
1157
1158 it.effect("past the first slice, believes a covered repository and not an uncovered one", () =>
1159 Effect.gen(function* () {
1160 const read = yield* providerAnswering({
1161 pages: [
1162 { items: [searched("acme/web")], truncated: true },
1163 { items: [searched("acme/web")], truncated: true },
1164 ],
1165 covered: (repository) => repository !== "acme/renamed",
1166 });
1167 const later = { ...across, cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 1 } };
1168 expect((yield* read(later)).unresolved).toEqual([]);
1169 expect(
1170 (yield* read({ ...later, repositories: ["acme/web", "acme/renamed"] })).unresolved,
1171 ).toEqual(["acme/renamed"]);
1172 }),
1173 );
1174
1175 it.effect("asks again after a failed check, and after coverage has had time to change", () =>
1176 Effect.gen(function* () {
1177 const checks: Array<string> = [];
1178 const failing = yield* providerAnswering({
1179 pages: [
1180 { items: [searched("acme/web")], truncated: false },
1181 { items: [searched("acme/web")], truncated: false },
1182 ],
1183 checks,
1184 });
1185 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
1186 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
1187 expect(checks).toEqual(["acme/docs", "acme/docs"]);
1188
1189 checks.length = 0;
1190 const read = yield* providerAnswering({
1191 pages: [
1192 { items: [searched("acme/web")], truncated: false },
1193 { items: [searched("acme/web")], truncated: false },
1194 ],
1195 covered: () => true,
1196 checks,
1197 });
1198 yield* read(across);
1199 yield* TestClock.adjust("61 minutes");
1200 yield* read(across);
1201 expect(checks).toEqual(["acme/docs", "acme/docs"]);
1202 }),
1203 );
1204});