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

GitHubPullRequestProvider.test.ts

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