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