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

GitHubPullRequestProvider.test.ts

1,104 lines35.0 KB

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