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

GitHubPullRequestProvider.test.ts

1,096 lines35.5 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 GitHubApi from "../sourceControl/GitHubApi.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(GitHubApi.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 GitHubApi.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 GitHubApi.GitHubApiRateLimitError({
676 host: "github.com",
677 operation: "listWorkflowRunsRequiringApproval",
678 }),
679 ),
680 getViewerAccess: () =>
681 Effect.succeed({
682 canWrite: true,
683 canTriage: true,
684 canUpdate: true,
685 didAuthor: false,
686 mergeCapabilities: { merge: true, squash: true, rebase: true },
687 }),
688 }),
689 ),
690 ),
691);
692​
693describe("getViewerPermissions", () => {
694 it.effect("checks fresh access without reading branch details for unrelated operations", () => {
695 let accessReads = 0;
696 return Effect.gen(function* () {
697 const provider = yield* make;
698 const permissions = yield* provider.getViewerPermissions({
699 cwd: "/w",
700 repository: "acme/web",
701 host: "github.com",
702 number: 7,
703 includeUpdateBranch: false,
704 });
705​
706 expect(accessReads).toBe(1);
707 expect(permissions.actions).toContain("merge");
708 expect(permissions.actions).not.toContain("update-branch");
709 }).pipe(
710 Effect.provide(
711 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
712 revalidateChecks: (_input, read) => read,
713 getPullRequestDetail: () => Effect.die("Unexpected detail read"),
714 getPullRequestBaseComparison: () => Effect.die("Unexpected comparison read"),
715 getViewerAccess: () =>
716 Effect.sync(() => {
717 accessReads++;
718 return {
719 canWrite: true,
720 canTriage: true,
721 canUpdate: true,
722 didAuthor: false,
723 mergeCapabilities: { merge: true, squash: true, rebase: true },
724 };
725 }),
726 }),
727 ),
728 );
729 });
730​
731 const layerWithComparison = (
732 comparison: Effect.Effect<{
733 readonly behindBy: number | null;
734 readonly viewerCanUpdate: boolean;
735 }>,
736 ) =>
737 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
738 revalidateChecks: (_input, read) => read,
739 getPullRequestDetail: () => Effect.succeed(openDetail),
740 getPullRequestBaseComparison: () => comparison,
741 getViewerAccess: () =>
742 Effect.succeed({
743 canWrite: true,
744 canTriage: true,
745 canUpdate: true,
746 didAuthor: false,
747 mergeCapabilities: { merge: true, squash: true, rebase: true },
748 }),
749 });
750​
751 it.effect("offers update-branch when the comparison grants it", () =>
752 Effect.gen(function* () {
753 const provider = yield* make;
754 const permissions = yield* provider.getViewerPermissions({
755 cwd: "/w",
756 repository: "acme/web",
757 host: "github.com",
758 number: 7,
759 });
760​
761 expect(permissions.actions).toContain("update-branch");
762 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
763 }).pipe(
764 Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
765 ),
766 );
767​
768 it.effect("uses the GraphQL reserve for manual permission checks", () => {
769 let viewerAllowReserve: boolean | undefined;
770 let comparisonAllowReserve: boolean | undefined;
771 return Effect.gen(function* () {
772 const provider = yield* make;
773 yield* provider.getViewerPermissions({
774 cwd: "/w",
775 repository: "acme/web",
776 host: "github.com",
777 number: 7,
778 });
779​
780 expect(viewerAllowReserve).toBe(true);
781 expect(comparisonAllowReserve).toBe(true);
782 }).pipe(
783 Effect.provide(
784 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
785 revalidateChecks: (_input, read) => read,
786 getPullRequestDetail: () => Effect.succeed(openDetail),
787 getPullRequestBaseComparison: (input) =>
788 Effect.sync(() => {
789 comparisonAllowReserve = input.allowReserve;
790 return { behindBy: 3, viewerCanUpdate: true };
791 }),
792 getViewerAccess: (input) =>
793 Effect.sync(() => {
794 viewerAllowReserve = input.allowReserve;
795 return {
796 canWrite: true,
797 canTriage: true,
798 canUpdate: true,
799 didAuthor: false,
800 mergeCapabilities: { merge: true, squash: true, rebase: true },
801 };
802 }),
803 }),
804 ),
805 );
806 });
807​
808 it.effect("withholds update-branch when the comparison cannot be read", () =>
809 Effect.gen(function* () {
810 const provider = yield* make;
811 const permissions = yield* provider.getViewerPermissions({
812 cwd: "/w",
813 repository: "acme/web",
814 host: "github.com",
815 number: 7,
816 });
817​
818 expect(permissions.actions).not.toContain("update-branch");
819 expect(permissions.updateMethods).toBeUndefined();
820 // The rest of the answer survives a comparison nobody could make.
821 expect(permissions.actions).toContain("merge");
822 }).pipe(
823 Effect.provide(
824 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
825 revalidateChecks: (_input, read) => read,
826 getPullRequestDetail: () => Effect.succeed(openDetail),
827 getPullRequestBaseComparison: () =>
828 Effect.fail(
829 new GitHubPullRequestCli.GitHubPullRequestReadError({
830 command: "gh",
831 cwd: "/w",
832 operation: "getPullRequestBaseComparison",
833 cause: new Error("unreadable"),
834 }),
835 ),
836 getViewerAccess: () =>
837 Effect.succeed({
838 canWrite: true,
839 canTriage: true,
840 canUpdate: true,
841 didAuthor: false,
842 mergeCapabilities: { merge: true, squash: true, rebase: true },
843 }),
844 }),
845 ),
846 ),
847 );
848});
849​
850describe("getChangeRequest commits", () => {
851 const baseDetail = {
852 authorId: null,
853 number: 7,
854 title: "Pull request 7",
855 url: "https://github.com/acme/web/pull/7",
856 author: null,
857 headBranch: "feat/page",
858 baseBranch: "main",
859 state: "open" as const,
860 isDraft: false,
861 mergeability: "mergeable" as const,
862 additions: 1,
863 deletions: 1,
864 createdAt: "2026-07-01T00:00:00Z",
865 updatedAt: "2026-07-02T00:00:00Z",
866 reviewRequestLogins: [],
867 hasTeamReviewRequest: false,
868 checksState: null,
869 labels: [],
870 body: "",
871 changedFiles: 1,
872 mergedAt: null,
873 closedAt: null,
874 checks: [],
875 comments: [],
876 };
877​
878 const baseThreadComments = {
879 comments: [],
880 dismissalsByReviewId: new Map<string, string>(),
881 reviewThreads: [],
882 commentCount: 0,
883 truncated: false,
884 reviewThreadsTruncated: false,
885 reactions: [],
886 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
887 editedAtById: new Map<string, string>(),
888 reviewers: [],
889 avatarsByLogin: new Map<string, string>(),
890 botLogins: new Set<string>(),
891 commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
892 viewer: { canUpdate: true, didAuthor: false },
893 };
894​
895 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
896 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
897 revalidateChecks: (_input, read) => read,
898 getPullRequestActivity: () =>
899 Effect.succeed({
900 author: baseDetail.author,
901 comments: baseDetail.comments,
902 commits: [
903 {
904 oid: "view-oldest",
905 messageHeadline: "gh pr view's oldest commit",
906 committedDate: "2026-01-01T00:00:00Z",
907 authors: [],
908 },
909 ],
910 }),
911 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
912 });
913​
914 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
915 Effect.gen(function* () {
916 const provider = yield* make;
917 const detail = yield* provider.getChangeRequestActivity({
918 cwd: "/w",
919 repository: "acme/web",
920 host: "github.com",
921 number: 7,
922 });
923​
924 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
925 }).pipe(
926 Effect.provide(
927 layerWith([
928 {
929 oid: "graphql-newest",
930 messageHeadline: "the newest commit gh pr view drops",
931 committedDate: "2026-07-06T00:00:00Z",
932 authors: [],
933 },
934 ]),
935 ),
936 ),
937 );
938​
939 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
940 Effect.gen(function* () {
941 const provider = yield* make;
942 const detail = yield* provider.getChangeRequestActivity({
943 cwd: "/w",
944 repository: "acme/web",
945 host: "github.com",
946 number: 7,
947 });
948​
949 expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
950 }).pipe(Effect.provide(layerWith([]))),
951 );
952});
953​
954describe("getChangeRequestActivity dismissed reviews", () => {
955 const dismissedReview = (body: string) => ({
956 id: "PRR_1",
957 kind: "review" as const,
958 author: { login: "macroscopeapp", name: null, avatarUrl: null },
959 body,
960 createdAt: "2026-07-03T00:00:00Z",
961 url: null,
962 path: null,
963 reviewState: "DISMISSED",
964 });
965 const threadComments: GitHubReviewThreadComments = {
966 comments: [],
967 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
968 reviewThreads: [],
969 commentCount: 0,
970 truncated: false,
971 reviewThreadsTruncated: false,
972 reactions: [],
973 reactionsById: new Map(),
974 editedAtById: new Map([["PRR_1", "2026-07-04T00:00:00Z"]]),
975 reviewers: [],
976 avatarsByLogin: new Map(),
977 botLogins: new Set(["macroscopeapp"]),
978 commitStats: new Map(),
979 commits: [],
980 viewer: { canUpdate: true, didAuthor: false },
981 };
982 const layerFor = (body: string) =>
983 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
984 revalidateChecks: (_input, read) => read,
985 getPullRequestActivity: () =>
986 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
987 listReviewThreadComments: () => Effect.succeed(threadComments),
988 });
989 const readActivity = Effect.gen(function* () {
990 const provider = yield* make;
991 return yield* provider.getChangeRequestActivity({
992 cwd: "/w",
993 repository: "acme/web",
994 host: "github.com",
995 number: 7,
996 });
997 });
998​
999 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
1000 // Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
1001 // an empty-string check misses them and the card opens onto nothing.
1002 readActivity.pipe(
1003 Effect.map((activity) => {
1004 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
1005 expect(activity.comments[0]?.author?.isBot).toBe(true);
1006 expect(activity.comments[0]?.editedAt).toBe("2026-07-04T00:00:00Z");
1007 }),
1008 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
1009 ),
1010 );
1011​
1012 it.effect("keeps the words of a dismissed review that has its own", () =>
1013 readActivity.pipe(
1014 Effect.map((activity) => {
1015 expect(activity.comments[0]?.body).toBe("These findings still stand.");
1016 }),
1017 Effect.provide(layerFor("These findings still stand.")),
1018 ),
1019 );
1020});
1021​
1022describe("editing", () => {
1023 const rewrites: Array<unknown> = [];
1024​
1025 it.effect("hands a rewrite to the CLI as the request named it", () =>
1026 Effect.gen(function* () {
1027 const provider = yield* make;
1028​
1029 expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
1030 yield* provider.updateChangeRequest!({
1031 cwd: "/w",
1032 repository: "acme/web",
1033 host: "github.com",
1034 number: 7,
1035 title: "A better title",
1036 });
1037 yield* provider.updateComment!({
1038 cwd: "/w",
1039 repository: "acme/web",
1040 host: "github.com",
1041 number: 7,
1042 commentId: "IC_1",
1043 kind: "review-comment",
1044 body: "Reworded.",
1045 });
1046​
1047 expect(rewrites).toEqual([
1049 cwd: "/w",
1050 repository: "acme/web",
1051 host: "github.com",
1052 number: 7,
1053 title: "A better title",
1054 },
1056 cwd: "/w",
1057 repository: "acme/web",
1058 host: "github.com",
1059 number: 7,
1060 commentId: "IC_1",
1061 kind: "review-comment",
1062 body: "Reworded.",
1063 },
1064 ]);
1065 }).pipe(
1066 Effect.provide(
1067 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
1068 revalidateChecks: (_input, read) => read,
1069 updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
1070 updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
1071 }),
1072 ),
1073 ),
1074 );
1075});
1076​
1077describe("loginAvatarUrl", () => {
1078 it("serves a user's picture from the host they belong to", () => {
1079 expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
1080 expect(loginAvatarUrl("octocat", "ghe.example.com")).toBe(
1081 "https://ghe.example.com/octocat.png?size=80",
1082 );
1083 });
1084​
1085 it("has nothing for an app, which names no page", () => {
1086 // `dependabot[bot]` has a picture, but not at `/dependabot[bot].png` — a guess that 404s is
1087 // worse than the initials it would replace.
1088 expect(loginAvatarUrl("dependabot[bot]", "github.com")).toBeNull();
1089 });
1090​
1091 it("refuses anything that is not a login, rather than building a URL out of it", () => {
1092 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
1093 expect(loginAvatarUrl(login, "github.com")).toBeNull();
1095 });
1096});