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

GitHubPullRequestProvider.test.ts

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