Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubPullRequestProvider.test.ts

1,019 lines32.4 KB

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 type { PullRequestReaction } from "@t3tools/contracts";
6​
7import * as GitHubCli from "../sourceControl/GitHubCli.ts";
8import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
9import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
10import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
11​
12const coreFields = {
13 checksTruncated: false,
14 comparison: { behindBy: 0, viewerCanUpdate: true },
15 viewerAccess: {
16 canWrite: true,
17 canTriage: true,
18 canUpdate: true,
19 didAuthor: false,
20 mergeCapabilities: { merge: true, squash: true, rebase: true },
21 },
22};
23​
24it.effect("maps credential verification failures without relabeling operation failures", () =>
25 Effect.gen(function* () {
26 let verificationFails = true;
27 let operations = 0;
28 const provider = yield* make.pipe(
29 Effect.provide(
30 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
31 withVerifiedCredential: (_input, use) =>
32 verificationFails
33 ? Effect.fail(
34 new GitHubPullRequestCli.GitHubViewerLoginUnavailableError({
35 command: "gh",
36 cwd: "/w",
37 }),
38 )
39 : use({ accountId: "123", viewer: "viewer", credentialFingerprint: "fingerprint" }),
40 }),
41 ),
42 );
43 const verify = provider.withVerifiedCredential;
44 if (verify === undefined)
45 return yield* Effect.die("credential verification was not implemented");
46 const input = { cwd: "/w", host: "github.com" };
47 const operation = () =>
48 Effect.sync(() => {
49 operations++;
50 }).pipe(Effect.andThen(Effect.fail("operation-failed")));
51 expect(yield* verify(input, operation).pipe(Effect.flip)).toMatchObject({
52 _tag: "PullRequestProviderError",
53 operation: "routeIdentity",
54 });
55 expect(operations).toBe(0);
56 verificationFails = false;
57 expect(yield* verify(input, operation).pipe(Effect.flip)).toBe("operation-failed");
58 expect(operations).toBe(1);
59 }),
60);
61​
62it.effect("uses one narrow read for a linked pull request summary", () =>
63 Effect.gen(function* () {
64 let summaryReads = 0;
65 const provider = yield* make.pipe(
66 Effect.provide(
67 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
68 getPullRequestSummary: () =>
69 Effect.sync(() => {
70 summaryReads += 1;
71 return {
72 number: 7,
73 title: "Summary",
74 url: "https://github.com/acme/web/pull/7",
75 headBranch: "feat/summary",
76 baseBranch: "main",
77 state: "open" as const,
78 updatedAt: "2026-08-24T12:34:56.000Z",
79 author: { login: "octocat", name: null, avatarUrl: null },
80 };
81 }),
82 }),
83 ),
84 );
85​
86 const readSummary = provider.getChangeRequestSummary;
87 if (readSummary === undefined) return yield* Effect.die("summary read was not implemented");
88 const summary = yield* readSummary({
89 cwd: "/w",
90 repository: "acme/web",
91 host: "github.com",
92 number: 7,
93 });
94​
95 expect(summary.state).toBe("open");
96 expect(summaryReads).toBe(1);
97 // The author's avatar comes from the login-shaped URL, not a second request.
98 expect(summary.author?.avatarUrl).toBe("https://github.com/octocat.png?size=80");
99 }),
100);
101​
102it.effect("declares host-native stacks and passes the one the CLI reads through", () =>
103 Effect.gen(function* () {
104 const stack = {
105 id: "42",
106 number: 3,
107 url: "https://github.com/acme/web/stacks/3",
108 base: "main",
109 layers: [
110 { number: 6, headBranch: "feat/one", state: "merged" as const },
111 { number: 7, headBranch: "feat/two", state: "open" as const },
112 ],
113 };
114 const provider = yield* make.pipe(
115 Effect.provide(
116 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
117 getPullRequestStack: (input) => Effect.succeed(input.number === 7 ? stack : null),
118 }),
119 ),
120 );
121​
122 expect(provider.capabilities.stacks).toBe(true);
123 const readStack = provider.getChangeRequestStack;
124 if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
125 const ref = { cwd: "/w", repository: "acme/web", host: "github.com" };
126 expect(yield* readStack({ ...ref, number: 7 })).toEqual(stack);
127 expect(yield* readStack({ ...ref, number: 8 })).toBeNull();
128 }),
129);
130​
131it.effect("reports a failed stack read against its own operation", () =>
132 Effect.gen(function* () {
133 const provider = yield* make.pipe(
134 Effect.provide(
135 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
136 getPullRequestStack: () =>
137 Effect.fail(
138 new GitHubPullRequestCli.GitHubPullRequestReadError({
139 command: "gh",
140 cwd: "/w",
141 operation: "getPullRequestStack",
142 cause: new Error("unreadable"),
143 }),
144 ),
145 }),
146 ),
147 );
148​
149 const readStack = provider.getChangeRequestStack;
150 if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
151 const error = yield* Effect.flip(
152 readStack({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }),
153 );
154​
155 expect(error.operation).toBe("getChangeRequestStack");
156 expect(error.reason).toBe("failed");
157 }),
158);
159​
160describe("gitHubViewerPermissions", () => {
161 it("offers everything to a viewer who can write to the repository", () => {
162 expect(
163 gitHubViewerPermissions({
164 canWrite: true,
165 canTriage: true,
166 canUpdate: true,
167 didAuthor: false,
168 }),
169 ).toEqual({
170 // Arming a merge for later is the merge, so it travels with it.
171 actions: [
172 "merge",
173 "enable-auto-merge",
174 "disable-auto-merge",
175 "revert",
176 "approve-workflows",
177 "ready",
178 "draft",
179 "close",
180 "reopen",
181 ],
182 comment: true,
183 resolve: true,
184 stackRebase: true,
185 verdicts: ["comment", "approve", "request-changes"],
186 requestReviewers: true,
187 labels: true,
188 });
189 });
190​
191 it("leaves a passer-by on a repository they can only read nothing but the review", () => {
192 // Every open-source pull request somebody else opened: GitHub says no to all five actions
193 // and to resolving, and yes to commenting and to every verdict.
194 expect(
195 gitHubViewerPermissions({
196 canWrite: false,
197 canTriage: false,
198 canUpdate: false,
199 didAuthor: false,
200 }),
201 ).toEqual({
202 actions: [],
203 comment: true,
204 resolve: false,
205 verdicts: ["comment", "approve", "request-changes"],
206 // Asking somebody else to review is the one thing read access never stretches to.
207 requestReviewers: false,
208 labels: false,
209 });
210 });
211​
212 it("lets a triager label without letting them merge or ask for a review", () => {
213 const permissions = gitHubViewerPermissions({
214 canWrite: false,
215 canTriage: true,
216 canUpdate: false,
217 didAuthor: false,
218 });
219 expect(permissions.labels).toBe(true);
220 expect(permissions.requestReviewers).toBe(false);
221 expect(permissions.actions).toEqual([]);
222 });
223​
224 it("keeps an author's own pull request theirs to close, with read access and no more", () => {
225 expect(
226 gitHubViewerPermissions({
227 canWrite: false,
228 canTriage: false,
229 canUpdate: true,
230 didAuthor: true,
231 }),
232 ).toEqual({
233 // Merging is the one thing writing is needed for, now or later; the rest an author may do.
234 actions: ["ready", "draft", "close", "reopen"],
235 comment: true,
236 resolve: true,
237 // GitHub refuses an author's approval of their own change, so the page does not offer one.
238 verdicts: ["comment"],
239 requestReviewers: false,
240 labels: false,
241 });
242 });
243​
244 it.effect("uses the permissions carried by the core read without a second request", () =>
245 Effect.gen(function* () {
246 const provider = yield* make;
247 const detail = yield* provider.getChangeRequest({
248 cwd: "/w",
249 repository: "acme/web",
250 host: "github.com",
251 number: 7,
252 });
253​
254 expect(detail.viewerPermissions).toEqual({
255 actions: ["ready", "draft", "close", "reopen"],
256 comment: true,
257 resolve: false,
258 verdicts: ["comment", "approve", "request-changes"],
259 requestReviewers: false,
260 labels: false,
261 });
262 expect(detail.workflowApprovalsRequired).toBeUndefined();
263 expect(detail.checks).toContainEqual({
264 name: "Workflow approval status",
265 status: "action-required",
266 description: "GitHub could not determine whether workflows are awaiting approval.",
267 url: null,
268 });
269 for (const fingerprint of ["broad", "restricted", "broad"]) {
270 const scoped = yield* provider
271 .getChangeRequest({
272 cwd: "/w",
273 repository: "acme/web",
274 host: "github.com",
275 number: 7,
276 })
277 .pipe(
278 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
279 host: "github.com",
280 token: Redacted.make("credential"),
281 credentialFingerprint: fingerprint,
282 }),
283 );
284 expect(scoped.mergeCapabilities.squash).toBe(fingerprint !== "restricted");
285 }
286 }).pipe(
287 Effect.provide(
288 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
289 getPullRequestDetail: () =>
290 Effect.succeed({
291 ...coreFields,
292 comparison: null,
293 viewerAccess: { ...coreFields.viewerAccess, canWrite: false, canTriage: false },
294 authorId: null,
295 number: 7,
296 title: "Pull request 7",
297 url: "https://github.com/acme/web/pull/7",
298 author: null,
299 isCrossRepository: true,
300 headRepositoryOwner: null,
301 headBranch: "feat/page",
302 baseBranch: "main",
303 state: "open" as const,
304 isDraft: false,
305 mergeability: "mergeable" as const,
306 reviewDecision: null,
307 additions: 1,
308 deletions: 1,
309 createdAt: "2026-07-01T00:00:00Z",
310 updatedAt: "2026-07-02T00:00:00Z",
311 reviewRequestLogins: [],
312 hasTeamReviewRequest: false,
313 checksState: null,
314 labels: [],
315 body: "",
316 changedFiles: 1,
317 mergedAt: null,
318 closedAt: null,
319 checks: [],
320 comments: [],
321 commits: [],
322 }).pipe(
323 Effect.flatMap((detail) =>
324 GitHubCli.PinnedGitHubCredential.pipe(
325 Effect.map((credential) => ({
326 ...detail,
327 viewerAccess: {
328 ...detail.viewerAccess,
329 mergeCapabilities: {
330 ...detail.viewerAccess.mergeCapabilities,
331 squash: credential?.credentialFingerprint !== "restricted",
332 },
333 },
334 })),
335 ),
336 ),
337 ),
338 }),
339 ),
340 ),
341 );
342​
343 it.effect("keeps fork workflows awaiting approval out of the passing state", () =>
344 Effect.gen(function* () {
345 const provider = yield* make;
346 const detail = yield* provider.getChangeRequest({
347 cwd: "/w",
348 repository: "acme/web",
349 host: "github.com",
350 number: 7,
351 });
352​
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(GitHubPullRequestCli.GitHubPullRequestCli)({
377 getPullRequestDetail: () =>
378 Effect.succeed({
379 ...coreFields,
380 authorId: null,
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 listWorkflowRunsRequiringApproval: () =>
419 Effect.succeed([
420 {
421 id: 123,
422 name: "contributor tests",
423 url: "https://github.com/acme/web/actions/runs/123",
424 },
425 ]),
426 getPullRequestBaseComparison: () =>
427 Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
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 }),
436 }),
437 ),
438 ),
439 );
440});
441​
442const openDetail = {
443 ...coreFields,
444 authorId: null,
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​
475it.effect(
476 "uses the core comparison and permissions while preserving workflow approval checks",
477 () =>
478 Effect.gen(function* () {
479 const provider = yield* make.pipe(
480 Effect.provide(
481 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
482 getPullRequestDetail: () =>
483 Effect.succeed({ ...openDetail, comparison: { behindBy: 2, viewerCanUpdate: true } }),
484 listWorkflowRunsRequiringApproval: () =>
485 Effect.succeed([{ id: 123, name: "tests", url: "https://example.com/runs/123" }]),
486 }),
487 ),
488 );
489​
490 const detail = yield* provider.getChangeRequest({
491 cwd: "/w",
492 repository: "acme/web",
493 host: "github.com",
494 number: 7,
495 });
496​
497 expect(detail.behindBy).toBe(2);
498 expect(detail.workflowApprovalsRequired).toBe(1);
499 expect(detail.checks).toContainEqual({
500 name: "tests",
501 status: "action-required",
502 description: "A maintainer must approve this workflow before it can run.",
503 url: "https://example.com/runs/123",
504 });
505 }),
506);
507​
508it.effect("does not classify same-repository gates as fork workflow approvals", () =>
509 Effect.gen(function* () {
510 const provider = yield* make;
511 const detail = yield* provider.getChangeRequest({
512 cwd: "/w",
513 repository: "acme/web",
514 host: "github.com",
515 number: 7,
516 });
517​
518 expect(detail.workflowApprovalsRequired).toBe(0);
519 expect(detail.checks).toEqual([]);
520 }).pipe(
521 Effect.provide(
522 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
523 getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
524 getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
525 listWorkflowRunsRequiringApproval: () =>
526 Effect.die("same-repository pull requests must not probe fork workflow approvals"),
527 getViewerAccess: () =>
528 Effect.succeed({
529 canWrite: true,
530 canTriage: true,
531 canUpdate: true,
532 didAuthor: false,
533 mergeCapabilities: { merge: true, squash: true, rebase: true },
534 }),
535 }),
536 ),
537 ),
538);
539​
540it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
541 Effect.gen(function* () {
542 const provider = yield* make;
543 const detail = yield* provider.getChangeRequest({
544 cwd: "/w",
545 repository: "acme/web",
546 host: "github.com",
547 number: 7,
548 });
549​
550 expect(detail.workflowApprovalsRequired).toBeUndefined();
551 expect(detail.checks).toEqual([
552 {
553 name: "Workflow approval status",
554 status: "action-required",
555 description: "GitHub could not determine whether workflows are awaiting approval.",
556 url: null,
557 },
558 ]);
559 }).pipe(
560 Effect.provide(
561 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
562 getPullRequestDetail: () => Effect.succeed(openDetail),
563 getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
564 listWorkflowRunsRequiringApproval: () =>
565 Effect.fail(
566 new GitHubPullRequestCli.GitHubWorkflowApprovalRefusedError({
567 command: "gh",
568 cwd: "/w",
569 number: 7,
570 reason: "head-not-unique",
571 observedCount: 2,
572 limit: 1_000,
573 }),
574 ),
575 getViewerAccess: () =>
576 Effect.succeed({
577 canWrite: true,
578 canTriage: true,
579 canUpdate: true,
580 didAuthor: false,
581 mergeCapabilities: { merge: true, squash: true, rebase: true },
582 }),
583 }),
584 ),
585 ),
586);
587​
588it.effect("propagates workflow discovery rate limits", () =>
589 Effect.gen(function* () {
590 const provider = yield* make;
591 const error = yield* provider
592 .getChangeRequest({
593 cwd: "/w",
594 repository: "acme/web",
595 host: "github.com",
596 number: 7,
597 })
598 .pipe(Effect.flip);
599​
600 expect(error.operation).toBe("getChangeRequest");
601 expect(error.reason).toBe("rate-limited");
602 }).pipe(
603 Effect.provide(
604 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
605 getPullRequestDetail: () => Effect.succeed(openDetail),
606 getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
607 listWorkflowRunsRequiringApproval: () =>
608 Effect.fail(
609 new GitHubCli.GitHubCliRateLimitError({
610 command: "gh",
611 cwd: "/w",
612 cause: new Error("rate limited"),
613 }),
614 ),
615 getViewerAccess: () =>
616 Effect.succeed({
617 canWrite: true,
618 canTriage: true,
619 canUpdate: true,
620 didAuthor: false,
621 mergeCapabilities: { merge: true, squash: true, rebase: true },
622 }),
623 }),
624 ),
625 ),
626);
627​
628describe("getViewerPermissions", () => {
629 it.effect("checks fresh access without reading branch details for unrelated operations", () => {
630 let accessReads = 0;
631 return Effect.gen(function* () {
632 const provider = yield* make;
633 const permissions = yield* provider.getViewerPermissions({
634 cwd: "/w",
635 repository: "acme/web",
636 host: "github.com",
637 number: 7,
638 includeUpdateBranch: false,
639 });
640​
641 expect(accessReads).toBe(1);
642 expect(permissions.actions).toContain("merge");
643 expect(permissions.actions).not.toContain("update-branch");
644 }).pipe(
645 Effect.provide(
646 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
647 getPullRequestDetail: () => Effect.die("Unexpected detail read"),
648 getPullRequestBaseComparison: () => Effect.die("Unexpected comparison read"),
649 getViewerAccess: () =>
650 Effect.sync(() => {
651 accessReads++;
652 return {
653 canWrite: true,
654 canTriage: true,
655 canUpdate: true,
656 didAuthor: false,
657 mergeCapabilities: { merge: true, squash: true, rebase: true },
658 };
659 }),
660 }),
661 ),
662 );
663 });
664​
665 const layerWithComparison = (
666 comparison: Effect.Effect<{
667 readonly behindBy: number | null;
668 readonly viewerCanUpdate: boolean;
669 }>,
670 ) =>
671 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
672 getPullRequestDetail: () => Effect.succeed(openDetail),
673 getPullRequestBaseComparison: () => comparison,
674 getViewerAccess: () =>
675 Effect.succeed({
676 canWrite: true,
677 canTriage: true,
678 canUpdate: true,
679 didAuthor: false,
680 mergeCapabilities: { merge: true, squash: true, rebase: true },
681 }),
682 });
683​
684 it.effect("offers update-branch when the comparison grants it", () =>
685 Effect.gen(function* () {
686 const provider = yield* make;
687 const permissions = yield* provider.getViewerPermissions({
688 cwd: "/w",
689 repository: "acme/web",
690 host: "github.com",
691 number: 7,
692 });
693​
694 expect(permissions.actions).toContain("update-branch");
695 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
696 }).pipe(
697 Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
698 ),
699 );
700​
701 it.effect("uses the GraphQL reserve for manual permission checks", () => {
702 let viewerAllowReserve: boolean | undefined;
703 let comparisonAllowReserve: boolean | undefined;
704 return Effect.gen(function* () {
705 const provider = yield* make;
706 yield* provider.getViewerPermissions({
707 cwd: "/w",
708 repository: "acme/web",
709 host: "github.com",
710 number: 7,
711 });
712​
713 expect(viewerAllowReserve).toBe(true);
714 expect(comparisonAllowReserve).toBe(true);
715 }).pipe(
716 Effect.provide(
717 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
718 getPullRequestDetail: () => Effect.succeed(openDetail),
719 getPullRequestBaseComparison: (input) =>
720 Effect.sync(() => {
721 comparisonAllowReserve = input.allowReserve;
722 return { behindBy: 3, viewerCanUpdate: true };
723 }),
724 getViewerAccess: (input) =>
725 Effect.sync(() => {
726 viewerAllowReserve = input.allowReserve;
727 return {
728 canWrite: true,
729 canTriage: true,
730 canUpdate: true,
731 didAuthor: false,
732 mergeCapabilities: { merge: true, squash: true, rebase: true },
733 };
734 }),
735 }),
736 ),
737 );
738 });
739​
740 it.effect("withholds update-branch when the comparison cannot be read", () =>
741 Effect.gen(function* () {
742 const provider = yield* make;
743 const permissions = yield* provider.getViewerPermissions({
744 cwd: "/w",
745 repository: "acme/web",
746 host: "github.com",
747 number: 7,
748 });
749​
750 expect(permissions.actions).not.toContain("update-branch");
751 expect(permissions.updateMethods).toBeUndefined();
752 // The rest of the answer survives a comparison nobody could make.
753 expect(permissions.actions).toContain("merge");
754 }).pipe(
755 Effect.provide(
756 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
757 getPullRequestDetail: () => Effect.succeed(openDetail),
758 getPullRequestBaseComparison: () =>
759 Effect.fail(
760 new GitHubPullRequestCli.GitHubPullRequestReadError({
761 command: "gh",
762 cwd: "/w",
763 operation: "getPullRequestBaseComparison",
764 cause: new Error("unreadable"),
765 }),
766 ),
767 getViewerAccess: () =>
768 Effect.succeed({
769 canWrite: true,
770 canTriage: true,
771 canUpdate: true,
772 didAuthor: false,
773 mergeCapabilities: { merge: true, squash: true, rebase: true },
774 }),
775 }),
776 ),
777 ),
778 );
779});
780​
781describe("getChangeRequest commits", () => {
782 const baseDetail = {
783 authorId: null,
784 number: 7,
785 title: "Pull request 7",
786 url: "https://github.com/acme/web/pull/7",
787 author: null,
788 headBranch: "feat/page",
789 baseBranch: "main",
790 state: "open" as const,
791 isDraft: false,
792 mergeability: "mergeable" as const,
793 additions: 1,
794 deletions: 1,
795 createdAt: "2026-07-01T00:00:00Z",
796 updatedAt: "2026-07-02T00:00:00Z",
797 reviewRequestLogins: [],
798 hasTeamReviewRequest: false,
799 checksState: null,
800 labels: [],
801 body: "",
802 changedFiles: 1,
803 mergedAt: null,
804 closedAt: null,
805 checks: [],
806 comments: [],
807 };
808​
809 const baseThreadComments = {
810 comments: [],
811 dismissalsByReviewId: new Map<string, string>(),
812 reviewThreads: [],
813 commentCount: 0,
814 truncated: false,
815 reactions: [],
816 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
817 reviewers: [],
818 avatarsByLogin: new Map<string, string>(),
819 botLogins: new Set<string>(),
820 commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
821 viewer: { canUpdate: true, didAuthor: false },
822 };
823​
824 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
825 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
826 getPullRequestActivity: () =>
827 Effect.succeed({
828 author: baseDetail.author,
829 comments: baseDetail.comments,
830 commits: [
831 {
832 oid: "view-oldest",
833 messageHeadline: "gh pr view's oldest commit",
834 committedDate: "2026-01-01T00:00:00Z",
835 authors: [],
836 },
837 ],
838 }),
839 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
840 });
841​
842 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
843 Effect.gen(function* () {
844 const provider = yield* make;
845 const detail = yield* provider.getChangeRequestActivity({
846 cwd: "/w",
847 repository: "acme/web",
848 host: "github.com",
849 number: 7,
850 });
851​
852 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
853 }).pipe(
854 Effect.provide(
855 layerWith([
856 {
857 oid: "graphql-newest",
858 messageHeadline: "the newest commit gh pr view drops",
859 committedDate: "2026-07-06T00:00:00Z",
860 authors: [],
861 },
862 ]),
863 ),
864 ),
865 );
866​
867 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
868 Effect.gen(function* () {
869 const provider = yield* make;
870 const detail = yield* provider.getChangeRequestActivity({
871 cwd: "/w",
872 repository: "acme/web",
873 host: "github.com",
874 number: 7,
875 });
876​
877 expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
878 }).pipe(Effect.provide(layerWith([]))),
879 );
880});
881​
882describe("getChangeRequestActivity dismissed reviews", () => {
883 const dismissedReview = (body: string) => ({
884 id: "PRR_1",
885 kind: "review" as const,
886 author: { login: "macroscopeapp", name: null, avatarUrl: null },
887 body,
888 createdAt: "2026-07-03T00:00:00Z",
889 url: null,
890 path: null,
891 reviewState: "DISMISSED",
892 });
893 const threadComments: GitHubReviewThreadComments = {
894 comments: [],
895 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
896 reviewThreads: [],
897 commentCount: 0,
898 truncated: false,
899 reactions: [],
900 reactionsById: new Map(),
901 reviewers: [],
902 avatarsByLogin: new Map(),
903 botLogins: new Set(["macroscopeapp"]),
904 commitStats: new Map(),
905 commits: [],
906 viewer: { canUpdate: true, didAuthor: false },
907 };
908 const layerFor = (body: string) =>
909 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
910 getPullRequestActivity: () =>
911 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
912 listReviewThreadComments: () => Effect.succeed(threadComments),
913 });
914 const readActivity = Effect.gen(function* () {
915 const provider = yield* make;
916 return yield* provider.getChangeRequestActivity({
917 cwd: "/w",
918 repository: "acme/web",
919 host: "github.com",
920 number: 7,
921 });
922 });
923​
924 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
925 // Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
926 // an empty-string check misses them and the card opens onto nothing.
927 readActivity.pipe(
928 Effect.map((activity) => {
929 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
930 expect(activity.comments[0]?.author?.isBot).toBe(true);
931 }),
932 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
933 ),
934 );
935​
936 it.effect("keeps the words of a dismissed review that has its own", () =>
937 readActivity.pipe(
938 Effect.map((activity) => {
939 expect(activity.comments[0]?.body).toBe("These findings still stand.");
940 }),
941 Effect.provide(layerFor("These findings still stand.")),
942 ),
943 );
944});
945​
946describe("editing", () => {
947 const rewrites: Array<unknown> = [];
948​
949 it.effect("hands a rewrite to the CLI as the request named it", () =>
950 Effect.gen(function* () {
951 const provider = yield* make;
952​
953 expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
954 yield* provider.updateChangeRequest!({
955 cwd: "/w",
956 repository: "acme/web",
957 host: "github.com",
958 number: 7,
959 title: "A better title",
960 });
961 yield* provider.updateComment!({
962 cwd: "/w",
963 repository: "acme/web",
964 host: "github.com",
965 number: 7,
966 commentId: "IC_1",
967 kind: "review-comment",
968 body: "Reworded.",
969 });
970​
971 expect(rewrites).toEqual([
972 {
973 cwd: "/w",
974 repository: "acme/web",
975 host: "github.com",
976 number: 7,
977 title: "A better title",
978 },
979 {
980 cwd: "/w",
981 repository: "acme/web",
982 host: "github.com",
983 number: 7,
984 commentId: "IC_1",
985 kind: "review-comment",
986 body: "Reworded.",
987 },
988 ]);
989 }).pipe(
990 Effect.provide(
991 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
992 updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
993 updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
994 }),
995 ),
996 ),
997 );
998});
999​
1000describe("loginAvatarUrl", () => {
1001 it("serves a user's picture from the host they belong to", () => {
1002 expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
1003 expect(loginAvatarUrl("octocat", "ghe.example.com")).toBe(
1004 "https://ghe.example.com/octocat.png?size=80",
1005 );
1006 });
1007​
1008 it("has nothing for an app, which names no page", () => {
1009 // `dependabot[bot]` has a picture, but not at `/dependabot[bot].png` — a guess that 404s is
1010 // worse than the initials it would replace.
1011 expect(loginAvatarUrl("dependabot[bot]", "github.com")).toBeNull();
1012 });
1013​
1014 it("refuses anything that is not a login, rather than building a URL out of it", () => {
1015 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
1016 expect(loginAvatarUrl(login, "github.com")).toBeNull();
1018 });
1019});