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

GitHubPullRequestProvider.test.ts

1,068 lines34.4 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 SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
11import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
12import type { GitHubPullRequestCore } from "./gitHubPullRequestJson.ts";
13import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
14import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
15​
16const coreFields = {
17 checksTruncated: false,
18 comparison: { behindBy: 0, viewerCanUpdate: true },
19 viewerAccess: {
20 canWrite: true,
21 canTriage: true,
22 canUpdate: true,
23 didAuthor: false,
24 mergeCapabilities: { merge: true, squash: true, rebase: true },
25 },
26};
27​
28it.effect("maps credential verification failures without relabeling operation failures", () =>
29 Effect.gen(function* () {
30 let verificationFails = true;
31 let operations = 0;
32 const provider = yield* make.pipe(
33 Effect.provide(
34 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
35 revalidateChecks: (_input, read) => read,
36 withVerifiedCredential: (_input, use) =>
37 verificationFails
38 ? Effect.fail(
39 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({
40 cwd: "/w",
41 }),
42 )
43 : use({ accountId: "123", viewer: "viewer", credentialFingerprint: "fingerprint" }),
44 }),
45 ),
46 );
47 const verify = provider.withVerifiedCredential;
48 if (verify === undefined)
49 return yield* Effect.die("credential verification was not implemented");
50 const input = { cwd: "/w", host: "github.com" };
51 const operation = () =>
52 Effect.sync(() => {
53 operations++;
54 }).pipe(Effect.andThen(Effect.fail("operation-failed")));
55 expect(yield* verify(input, operation).pipe(Effect.flip)).toMatchObject({
56 _tag: "PullRequestProviderError",
57 operation: "routeIdentity",
58 });
59 expect(operations).toBe(0);
60 verificationFails = false;
61 expect(yield* verify(input, operation).pipe(Effect.flip)).toBe("operation-failed");
62 expect(operations).toBe(1);
63 }),
64);
65​
66it.effect("refreshes checks without permissions or comparison reads", () =>
67 Effect.gen(function* () {
68 let reads = 0;
69 const snapshot = Result.getOrThrow(
70 decodePullRequestDetailJson(`{
71 "number": 7, "title": "Checks", "url": "https://github.com/acme/web/pull/7",
72 "headRefName": "feature", "baseRefName": "main", "state": "OPEN",
73 "createdAt": "2026-07-01T00:00:00Z", "updatedAt": "2026-07-01T00:00:00Z"
74 }`),
75 );
76 const provider = yield* make.pipe(
77 Effect.provide(
78 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
79 revalidateChecks: (_input, read) => read,
80 getPullRequestDetail: () =>
81 Effect.sync(() => {
82 reads++;
83 return {
84 ...snapshot,
85 ...coreFields,
86 state: reads === 3 ? ("merged" as const) : ("open" as const),
87 checks: [
88 {
89 name: "build",
90 status: reads === 1 ? ("pending" as const) : ("success" as const),
91 description: null,
92 url: null,
93 },
94 ],
95 };
96 }),
97 }),
98 ),
99 );
100 const read = provider.getChangeRequestChecks;
101 if (read === undefined) return yield* Effect.die("checks read missing");
102 for (let tick = 1; tick <= 3; tick++) {
103 const result = yield* read({
104 cwd: "/w",
105 repository: "acme/web",
106 host: "github.com",
107 number: 7,
108 });
109 expect(result.checks[0]?.status).toBe(tick === 1 ? "pending" : "success");
110 expect(result.state).toBe(tick === 3 ? "merged" : "open");
111 }
112 expect(reads).toBe(3);
113 }),
114);
115​
116it.effect("uses one narrow read for a linked pull request summary", () =>
117 Effect.gen(function* () {
118 let summaryReads = 0;
119 const provider = yield* make.pipe(
120 Effect.provide(
121 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
122 revalidateChecks: (_input, read) => read,
123 getPullRequestSummary: () =>
124 Effect.sync(() => {
125 summaryReads += 1;
126 return {
127 number: 7,
128 title: "Summary",
129 url: "https://github.com/acme/web/pull/7",
130 headBranch: "feat/summary",
131 baseBranch: "main",
132 state: "open" as const,
133 updatedAt: "2026-08-24T12:34:56.000Z",
134 author: { login: "octocat", name: null, avatarUrl: null },
135 };
136 }),
137 }),
138 ),
139 );
140​
141 const readSummary = provider.getChangeRequestSummary;
142 if (readSummary === undefined) return yield* Effect.die("summary read was not implemented");
143 const summary = yield* readSummary({
144 cwd: "/w",
145 repository: "acme/web",
146 host: "github.com",
147 number: 7,
148 });
149​
150 expect(summary.state).toBe("open");
151 expect(summaryReads).toBe(1);
152 // The author's avatar comes from the login-shaped URL, not a second request.
153 expect(summary.author?.avatarUrl).toBe("https://github.com/octocat.png?size=80");
154 }),
155);
156​
157it.effect("declares host-native stacks and passes the one the CLI reads through", () =>
158 Effect.gen(function* () {
159 const stack = {
160 id: "42",
161 number: 3,
162 url: "https://github.com/acme/web/stacks/3",
163 base: "main",
164 layers: [
165 { number: 6, headBranch: "feat/one", state: "merged" as const },
166 { number: 7, headBranch: "feat/two", state: "open" as const },
167 ],
168 };
169 const provider = yield* make.pipe(
170 Effect.provide(
171 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
172 revalidateChecks: (_input, read) => read,
173 getPullRequestStack: (input) => Effect.succeed(input.number === 7 ? stack : null),
174 }),
175 ),
176 );
177​
178 expect(provider.capabilities.stacks).toBe(true);
179 const readStack = provider.getChangeRequestStack;
180 if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
181 const ref = { cwd: "/w", repository: "acme/web", host: "github.com" };
182 expect(yield* readStack({ ...ref, number: 7 })).toEqual(stack);
183 expect(yield* readStack({ ...ref, number: 8 })).toBeNull();
184 }),
185);
186​
187it.effect("reports a failed stack read against its own operation", () =>
188 Effect.gen(function* () {
189 const provider = yield* make.pipe(
190 Effect.provide(
191 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
192 revalidateChecks: (_input, read) => read,
193 getPullRequestStack: () =>
194 Effect.fail(
195 new GitHubPullRequestApi.GitHubPullRequestReadError({
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(GitHubPullRequestApi.GitHubPullRequestApi)({
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(GitHubPullRequestApi.GitHubPullRequestApi)({
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 getViewerAccess: () =>
490 Effect.succeed({
491 canWrite: true,
492 canTriage: true,
493 canUpdate: true,
494 didAuthor: false,
495 mergeCapabilities: { merge: true, squash: true, rebase: true },
496 }),
497 }),
498 ),
499 ),
500 );
501});
502​
503const openDetail = {
504 ...coreFields,
505 authorId: null,
506 number: 7,
507 title: "Pull request 7",
508 url: "https://github.com/acme/web/pull/7",
509 author: null,
510 isCrossRepository: true,
511 headRepositoryOwner: "acme",
512 headSha: "abc123",
513 headBranch: "feat/page",
514 baseBranch: "main",
515 state: "open" as const,
516 isDraft: false,
517 mergeability: "mergeable" as const,
518 reviewDecision: null,
519 additions: 1,
520 deletions: 1,
521 createdAt: "2026-07-01T00:00:00Z",
522 updatedAt: "2026-07-02T00:00:00Z",
523 reviewRequestLogins: [],
524 hasTeamReviewRequest: false,
525 checksState: null,
526 labels: [],
527 body: "",
528 changedFiles: 1,
529 mergedAt: null,
530 closedAt: null,
531 checks: [],
532 comments: [],
533 commits: [],
534};
535​
536it.effect(
537 "uses the core comparison and permissions while preserving workflow approval checks",
538 () =>
539 Effect.gen(function* () {
540 const provider = yield* make.pipe(
541 Effect.provide(
542 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
543 getPullRequestDetail: () =>
544 Effect.succeed({ ...openDetail, comparison: { behindBy: 2, viewerCanUpdate: true } }),
545 listWorkflowRunsRequiringApproval: () =>
546 Effect.succeed([{ id: 123, name: "tests", url: "https://example.com/runs/123" }]),
547 }),
548 ),
549 );
550​
551 const detail = yield* provider.getChangeRequest({
552 cwd: "/w",
553 repository: "acme/web",
554 host: "github.com",
555 number: 7,
556 });
557​
558 expect(detail.behindBy).toBe(2);
559 expect(detail.workflowApprovalsRequired).toBe(1);
560 expect(detail.checks).toContainEqual({
561 name: "tests",
562 status: "action-required",
563 description: "A maintainer must approve this workflow before it can run.",
564 url: "https://example.com/runs/123",
565 });
566 }),
567);
568​
569it.effect("does not classify same-repository gates as fork workflow approvals", () =>
570 Effect.gen(function* () {
571 const provider = yield* make;
572 const detail = yield* provider.getChangeRequest({
573 cwd: "/w",
574 repository: "acme/web",
575 host: "github.com",
576 number: 7,
577 });
578​
579 expect(detail.workflowApprovalsRequired).toBe(0);
580 expect(detail.checks).toEqual([]);
581 }).pipe(
582 Effect.provide(
583 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
584 revalidateChecks: (_input, read) => read,
585 getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
586 listWorkflowRunsRequiringApproval: () =>
587 Effect.die("same-repository pull requests must not probe fork workflow approvals"),
588 getViewerAccess: () =>
589 Effect.succeed({
590 canWrite: true,
591 canTriage: true,
592 canUpdate: true,
593 didAuthor: false,
594 mergeCapabilities: { merge: true, squash: true, rebase: true },
595 }),
596 }),
597 ),
598 ),
599);
600​
601it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
602 Effect.gen(function* () {
603 const provider = yield* make;
604 const detail = yield* provider.getChangeRequest({
605 cwd: "/w",
606 repository: "acme/web",
607 host: "github.com",
608 number: 7,
609 });
610​
611 expect(detail.workflowApprovalsRequired).toBeUndefined();
612 expect(detail.checks).toEqual([
613 {
614 name: "Workflow approval status",
615 status: "action-required",
616 description: "GitHub could not determine whether workflows are awaiting approval.",
617 url: null,
618 },
619 ]);
620 }).pipe(
621 Effect.provide(
622 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
623 revalidateChecks: (_input, read) => read,
624 getPullRequestDetail: () => Effect.succeed(openDetail),
625 listWorkflowRunsRequiringApproval: () =>
626 Effect.fail(
627 new GitHubPullRequestApi.GitHubWorkflowApprovalRefusedError({
628 cwd: "/w",
629 number: 7,
630 reason: "head-not-unique",
631 observedCount: 2,
632 limit: 1_000,
633 }),
634 ),
635 getViewerAccess: () =>
636 Effect.succeed({
637 canWrite: true,
638 canTriage: true,
639 canUpdate: true,
640 didAuthor: false,
641 mergeCapabilities: { merge: true, squash: true, rebase: true },
642 }),
643 }),
644 ),
645 ),
646);
647​
648it.effect("propagates workflow discovery rate limits", () =>
649 Effect.gen(function* () {
650 const provider = yield* make;
651 const error = yield* provider
652 .getChangeRequest({
653 cwd: "/w",
654 repository: "acme/web",
655 host: "github.com",
656 number: 7,
657 })
658 .pipe(Effect.flip);
659​
660 expect(error.operation).toBe("getChangeRequest");
661 expect(error.reason).toBe("rate-limited");
662 }).pipe(
663 Effect.provide(
664 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
665 revalidateChecks: (_input, read) => read,
666 getPullRequestDetail: () => Effect.succeed(openDetail),
667 listWorkflowRunsRequiringApproval: () =>
668 Effect.fail(
669 new GitHubApi.GitHubApiRateLimitError({
670 host: "github.com",
671 operation: "listWorkflowRunsRequiringApproval",
672 }),
673 ),
674 getViewerAccess: () =>
675 Effect.succeed({
676 canWrite: true,
677 canTriage: true,
678 canUpdate: true,
679 didAuthor: false,
680 mergeCapabilities: { merge: true, squash: true, rebase: true },
681 }),
682 }),
683 ),
684 ),
685);
686​
687describe("getViewerPermissions", () => {
688 const access = {
689 canWrite: true,
690 canTriage: true,
691 canUpdate: true,
692 didAuthor: false,
693 mergeCapabilities: { merge: true, squash: true, rebase: true },
694 };
695​
696 it.effect("checks fresh access without reading branch details for unrelated operations", () => {
697 let accessReads = 0;
698 return Effect.gen(function* () {
699 const provider = yield* make;
700 const permissions = yield* provider.getViewerPermissions({
701 cwd: "/w",
702 repository: "acme/web",
703 host: "github.com",
704 number: 7,
705 includeUpdateBranch: false,
706 });
707​
708 expect(accessReads).toBe(1);
709 expect(permissions.actions).toContain("merge");
710 expect(permissions.actions).not.toContain("update-branch");
711 }).pipe(
712 Effect.provide(
713 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
714 revalidateChecks: (_input, read) => read,
715 getPullRequestDetail: () => Effect.die("Unexpected detail read"),
716 getViewerAccess: () => Effect.sync(() => (accessReads++, access)),
717 }),
718 ),
719 );
720 });
721​
722 const layerWithDetail = (
723 detail: Effect.Effect<GitHubPullRequestCore, GitHubPullRequestApi.GitHubPullRequestApiError>,
724 onDetail: (allowReserve: boolean) => void = () => {},
725 ) =>
726 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
727 revalidateChecks: (_input, read) => read,
728 getPullRequestDetail: () =>
729 SourceControlRateLimit.Interactive.pipe(
730 Effect.tap((allowReserve) => Effect.sync(() => onDetail(allowReserve))),
731 Effect.flatMap(() => detail),
732 ),
733 getViewerAccess: () => Effect.die("Unexpected access read"),
734 });
735​
736 it.effect("answers access and update-branch from the one detail read", () =>
737 Effect.gen(function* () {
738 const provider = yield* make;
739 const permissions = yield* provider.getViewerPermissions({
740 cwd: "/w",
741 repository: "acme/web",
742 host: "github.com",
743 number: 7,
744 });
745​
746 expect(permissions.actions).toContain("merge");
747 expect(permissions.actions).toContain("update-branch");
748 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
749 }).pipe(
750 Effect.provide(
751 layerWithDetail(
752 Effect.succeed({ ...openDetail, comparison: { behindBy: 3, viewerCanUpdate: true } }),
753 ),
754 ),
755 ),
756 );
757​
758 it.effect("uses the GraphQL reserve for manual permission checks", () => {
759 let allowed: boolean | undefined;
760 return Effect.gen(function* () {
761 const provider = yield* make;
762 yield* provider.getViewerPermissions({
763 cwd: "/w",
764 repository: "acme/web",
765 host: "github.com",
766 number: 7,
767 });
768 expect(allowed).toBe(true);
769 }).pipe(
770 Effect.provide(
771 layerWithDetail(Effect.succeed(openDetail), (allowReserve) => (allowed = allowReserve)),
772 ),
773 );
774 });
775​
776 it.effect("still answers from the light access read when the detail read fails", () =>
777 Effect.gen(function* () {
778 const provider = yield* make;
779 const permissions = yield* provider.getViewerPermissions({
780 cwd: "/w",
781 repository: "acme/web",
782 host: "github.com",
783 number: 7,
784 });
785 expect(permissions.actions).toContain("merge");
786 expect(permissions.actions).not.toContain("update-branch");
787 }).pipe(
788 Effect.provide(
789 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
790 revalidateChecks: (_input, read) => read,
791 getPullRequestDetail: () =>
792 Effect.fail(
793 new GitHubPullRequestApi.GitHubPullRequestReadError({
794 cwd: "/w",
795 operation: "getPullRequestDetail",
796 cause: new Error("head changed"),
797 }),
798 ),
799 getViewerAccess: () => Effect.succeed(access),
800 }),
801 ),
802 ),
803 );
804​
805 it.effect("withholds update-branch where GitHub could not compare the branch", () =>
806 Effect.gen(function* () {
807 const provider = yield* make;
808 const permissions = yield* provider.getViewerPermissions({
809 cwd: "/w",
810 repository: "acme/web",
811 host: "github.com",
812 number: 7,
813 });
814​
815 expect(permissions.actions).not.toContain("update-branch");
816 expect(permissions.updateMethods).toBeUndefined();
817 expect(permissions.actions).toContain("merge");
818 }).pipe(Effect.provide(layerWithDetail(Effect.succeed({ ...openDetail, comparison: null })))),
819 );
820});
821​
822describe("getChangeRequest commits", () => {
823 const baseDetail = {
824 authorId: null,
825 number: 7,
826 title: "Pull request 7",
827 url: "https://github.com/acme/web/pull/7",
828 author: null,
829 headBranch: "feat/page",
830 baseBranch: "main",
831 state: "open" as const,
832 isDraft: false,
833 mergeability: "mergeable" as const,
834 additions: 1,
835 deletions: 1,
836 createdAt: "2026-07-01T00:00:00Z",
837 updatedAt: "2026-07-02T00:00:00Z",
838 reviewRequestLogins: [],
839 hasTeamReviewRequest: false,
840 checksState: null,
841 labels: [],
842 body: "",
843 changedFiles: 1,
844 mergedAt: null,
845 closedAt: null,
846 checks: [],
847 comments: [],
848 };
849​
850 const baseThreadComments = {
851 comments: [],
852 dismissalsByReviewId: new Map<string, string>(),
853 reviewThreads: [],
854 commentCount: 0,
855 truncated: false,
856 reviewThreadsTruncated: false,
857 reactions: [],
858 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
859 editedAtById: new Map<string, string>(),
860 reviewers: [],
861 avatarsByLogin: new Map<string, string>(),
862 botLogins: new Set<string>(),
863 commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
864 viewer: { canUpdate: true, didAuthor: false },
865 };
866​
867 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
868 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
869 revalidateChecks: (_input, read) => read,
870 getPullRequestActivity: () =>
871 Effect.succeed({
872 author: baseDetail.author,
873 comments: baseDetail.comments,
874 commits: [
875 {
876 oid: "view-oldest",
877 messageHeadline: "gh pr view's oldest commit",
878 committedDate: "2026-01-01T00:00:00Z",
879 authors: [],
880 },
881 ],
882 }),
883 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
884 });
885​
886 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
887 Effect.gen(function* () {
888 const provider = yield* make;
889 const detail = yield* provider.getChangeRequestActivity({
890 cwd: "/w",
891 repository: "acme/web",
892 host: "github.com",
893 number: 7,
894 });
895​
896 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
897 }).pipe(
898 Effect.provide(
899 layerWith([
900 {
901 oid: "graphql-newest",
902 messageHeadline: "the newest commit gh pr view drops",
903 committedDate: "2026-07-06T00:00:00Z",
904 authors: [],
905 },
906 ]),
907 ),
908 ),
909 );
910​
911 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
912 Effect.gen(function* () {
913 const provider = yield* make;
914 const detail = yield* provider.getChangeRequestActivity({
915 cwd: "/w",
916 repository: "acme/web",
917 host: "github.com",
918 number: 7,
919 });
920​
921 expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
922 }).pipe(Effect.provide(layerWith([]))),
923 );
924});
925​
926describe("getChangeRequestActivity dismissed reviews", () => {
927 const dismissedReview = (body: string) => ({
928 id: "PRR_1",
929 kind: "review" as const,
930 author: { login: "macroscopeapp", name: null, avatarUrl: null },
931 body,
932 createdAt: "2026-07-03T00:00:00Z",
933 url: null,
934 path: null,
935 reviewState: "DISMISSED",
936 });
937 const threadComments: GitHubReviewThreadComments = {
938 comments: [],
939 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
940 reviewThreads: [],
941 commentCount: 0,
942 truncated: false,
943 reviewThreadsTruncated: false,
944 reactions: [],
945 reactionsById: new Map(),
946 editedAtById: new Map([["PRR_1", "2026-07-04T00:00:00Z"]]),
947 reviewers: [],
948 avatarsByLogin: new Map(),
949 botLogins: new Set(["macroscopeapp"]),
950 commitStats: new Map(),
951 commits: [],
952 viewer: { canUpdate: true, didAuthor: false },
953 };
954 const layerFor = (body: string) =>
955 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
956 revalidateChecks: (_input, read) => read,
957 getPullRequestActivity: () =>
958 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
959 listReviewThreadComments: () => Effect.succeed(threadComments),
960 });
961 const readActivity = Effect.gen(function* () {
962 const provider = yield* make;
963 return yield* provider.getChangeRequestActivity({
964 cwd: "/w",
965 repository: "acme/web",
966 host: "github.com",
967 number: 7,
968 });
969 });
970​
971 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
972 // Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
973 // an empty-string check misses them and the card opens onto nothing.
974 readActivity.pipe(
975 Effect.map((activity) => {
976 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
977 expect(activity.comments[0]?.author?.isBot).toBe(true);
978 expect(activity.comments[0]?.editedAt).toBe("2026-07-04T00:00:00Z");
979 }),
980 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
981 ),
982 );
983​
984 it.effect("keeps the words of a dismissed review that has its own", () =>
985 readActivity.pipe(
986 Effect.map((activity) => {
987 expect(activity.comments[0]?.body).toBe("These findings still stand.");
988 }),
989 Effect.provide(layerFor("These findings still stand.")),
990 ),
991 );
992});
993​
994describe("editing", () => {
995 const rewrites: Array<unknown> = [];
996​
997 it.effect("hands a rewrite to the CLI as the request named it", () =>
998 Effect.gen(function* () {
999 const provider = yield* make;
1000​
1001 expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
1002 yield* provider.updateChangeRequest!({
1003 cwd: "/w",
1004 repository: "acme/web",
1005 host: "github.com",
1006 number: 7,
1007 title: "A better title",
1008 });
1009 yield* provider.updateComment!({
1010 cwd: "/w",
1011 repository: "acme/web",
1012 host: "github.com",
1013 number: 7,
1014 commentId: "IC_1",
1015 kind: "review-comment",
1016 body: "Reworded.",
1017 });
1018​
1019 expect(rewrites).toEqual([
1021 cwd: "/w",
1022 repository: "acme/web",
1023 host: "github.com",
1024 number: 7,
1025 title: "A better title",
1026 },
1028 cwd: "/w",
1029 repository: "acme/web",
1030 host: "github.com",
1031 number: 7,
1032 commentId: "IC_1",
1033 kind: "review-comment",
1034 body: "Reworded.",
1035 },
1036 ]);
1037 }).pipe(
1038 Effect.provide(
1039 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
1040 revalidateChecks: (_input, read) => read,
1041 updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
1042 updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
1043 }),
1044 ),
1045 ),
1046 );
1047});
1048​
1049describe("loginAvatarUrl", () => {
1050 it("serves a user's picture from the host they belong to", () => {
1051 expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
1052 expect(loginAvatarUrl("octocat", "ghe.example.com")).toBe(
1053 "https://ghe.example.com/octocat.png?size=80",
1054 );
1055 });
1056​
1057 it("has nothing for an app, which names no page", () => {
1058 // `dependabot[bot]` has a picture, but not at `/dependabot[bot].png` — a guess that 404s is
1059 // worse than the initials it would replace.
1060 expect(loginAvatarUrl("dependabot[bot]", "github.com")).toBeNull();
1061 });
1062​
1063 it("refuses anything that is not a login, rather than building a URL out of it", () => {
1064 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
1065 expect(loginAvatarUrl(login, "github.com")).toBeNull();
1067 });
1068});