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