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