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