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 type { PullRequestReaction } from "@t3tools/contracts";
5
6import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
7import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
8import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
9
10describe("gitHubViewerPermissions", () => {
11 it("offers everything to a viewer who can write to the repository", () => {
12 expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
13 // Arming a merge for later is the merge, so it travels with it.
14 actions: [
15 "merge",
16 "enable-auto-merge",
17 "disable-auto-merge",
18 "ready",
19 "draft",
20 "close",
21 "reopen",
22 ],
23 comment: true,
24 resolve: true,
25 verdicts: ["comment", "approve", "request-changes"],
26 requestReviewers: true,
27 });
28 });
29
30 it("leaves a passer-by on a repository they can only read nothing but the review", () => {
31 // Every open-source pull request somebody else opened: GitHub says no to all five actions
32 // and to resolving, and yes to commenting and to every verdict.
33 expect(
34 gitHubViewerPermissions({ canWrite: false, canUpdate: false, didAuthor: false }),
35 ).toEqual({
36 actions: [],
37 comment: true,
38 resolve: false,
39 verdicts: ["comment", "approve", "request-changes"],
40 // Asking somebody else to review is the one thing read access never stretches to.
41 requestReviewers: false,
42 });
43 });
44
45 it("keeps an author's own pull request theirs to close, with read access and no more", () => {
46 expect(gitHubViewerPermissions({ canWrite: false, canUpdate: true, didAuthor: true })).toEqual({
47 // Merging is the one thing writing is needed for, now or later; the rest an author may do.
48 actions: ["ready", "draft", "close", "reopen"],
49 comment: true,
50 resolve: true,
51 // GitHub refuses an author's approval of their own change, so the page does not offer one.
52 verdicts: ["comment"],
53 requestReviewers: false,
54 });
55 });
56
57 it.effect("uses the small viewer-access read for core permissions", () =>
58 Effect.gen(function* () {
59 const provider = yield* make;
60 const detail = yield* provider.getChangeRequest({
61 cwd: "/w",
62 repository: "acme/web",
63 host: "github.com",
64 number: 7,
65 });
66
67 expect(detail.viewerPermissions).toEqual({
68 actions: ["ready", "draft", "close", "reopen"],
69 comment: true,
70 resolve: false,
71 verdicts: ["comment", "approve", "request-changes"],
72 requestReviewers: false,
73 });
74 }).pipe(
75 Effect.provide(
76 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
77 getPullRequestDetail: () =>
78 Effect.succeed({
79 authorId: null,
80 number: 7,
81 title: "Pull request 7",
82 url: "https://github.com/acme/web/pull/7",
83 author: null,
84 headRepositoryOwner: null,
85 headBranch: "feat/page",
86 baseBranch: "main",
87 state: "open",
88 isDraft: false,
89 mergeability: "mergeable",
90 reviewDecision: null,
91 additions: 1,
92 deletions: 1,
93 createdAt: "2026-07-01T00:00:00Z",
94 updatedAt: "2026-07-02T00:00:00Z",
95 reviewRequestLogins: [],
96 hasTeamReviewRequest: false,
97 checksState: null,
98 labels: [],
99 body: "",
100 changedFiles: 1,
101 mergedAt: null,
102 closedAt: null,
103 checks: [],
104 comments: [],
105 commits: [],
106 }),
107 getRepositoryAccess: () =>
108 Effect.succeed({
109 canWrite: false,
110 mergeCapabilities: { merge: true, squash: true, rebase: true },
111 }),
112 getViewerAccess: () =>
113 Effect.succeed({ canWrite: false, canUpdate: true, didAuthor: false }),
114 }),
115 ),
116 ),
117 );
118});
119
120describe("getViewerPermissions", () => {
121 const openDetail = {
122 authorId: null,
123 number: 7,
124 title: "Pull request 7",
125 url: "https://github.com/acme/web/pull/7",
126 author: null,
127 headRepositoryOwner: "acme",
128 headBranch: "feat/page",
129 baseBranch: "main",
130 state: "open" as const,
131 isDraft: false,
132 mergeability: "mergeable" as const,
133 reviewDecision: null,
134 additions: 1,
135 deletions: 1,
136 createdAt: "2026-07-01T00:00:00Z",
137 updatedAt: "2026-07-02T00:00:00Z",
138 reviewRequestLogins: [],
139 hasTeamReviewRequest: false,
140 checksState: null,
141 labels: [],
142 body: "",
143 changedFiles: 1,
144 mergedAt: null,
145 closedAt: null,
146 checks: [],
147 comments: [],
148 commits: [],
149 };
150
151 const layerWithComparison = (
152 comparison: Effect.Effect<{
153 readonly behindBy: number | null;
154 readonly viewerCanUpdate: boolean;
155 }>,
156 ) =>
157 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
158 getPullRequestDetail: () => Effect.succeed(openDetail),
159 getPullRequestBaseComparison: () => comparison,
160 getViewerAccess: () => Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
161 });
162
163 it.effect("offers update-branch when the comparison grants it", () =>
164 Effect.gen(function* () {
165 const provider = yield* make;
166 const permissions = yield* provider.getViewerPermissions({
167 cwd: "/w",
168 repository: "acme/web",
169 host: "github.com",
170 number: 7,
171 });
172
173 expect(permissions.actions).toContain("update-branch");
174 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
175 }).pipe(
176 Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
177 ),
178 );
179
180 it.effect("uses the GraphQL reserve for manual permission checks", () => {
181 let viewerAllowReserve: boolean | undefined;
182 let comparisonAllowReserve: boolean | undefined;
183 return Effect.gen(function* () {
184 const provider = yield* make;
185 yield* provider.getViewerPermissions({
186 cwd: "/w",
187 repository: "acme/web",
188 host: "github.com",
189 number: 7,
190 });
191
192 expect(viewerAllowReserve).toBe(true);
193 expect(comparisonAllowReserve).toBe(true);
194 }).pipe(
195 Effect.provide(
196 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
197 getPullRequestDetail: () => Effect.succeed(openDetail),
198 getPullRequestBaseComparison: (input) =>
199 Effect.sync(() => {
200 comparisonAllowReserve = input.allowReserve;
201 return { behindBy: 3, viewerCanUpdate: true };
202 }),
203 getViewerAccess: (input) =>
204 Effect.sync(() => {
205 viewerAllowReserve = input.allowReserve;
206 return { canWrite: true, canUpdate: true, didAuthor: false };
207 }),
208 }),
209 ),
210 );
211 });
212
213 it.effect("withholds update-branch when the comparison cannot be read", () =>
214 Effect.gen(function* () {
215 const provider = yield* make;
216 const permissions = yield* provider.getViewerPermissions({
217 cwd: "/w",
218 repository: "acme/web",
219 host: "github.com",
220 number: 7,
221 });
222
223 expect(permissions.actions).not.toContain("update-branch");
224 expect(permissions.updateMethods).toBeUndefined();
225 // The rest of the answer survives a comparison nobody could make.
226 expect(permissions.actions).toContain("merge");
227 }).pipe(
228 Effect.provide(
229 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
230 getPullRequestDetail: () => Effect.succeed(openDetail),
231 getPullRequestBaseComparison: () =>
232 Effect.fail(
233 new GitHubPullRequestCli.GitHubPullRequestReadError({
234 command: "gh",
235 cwd: "/w",
236 operation: "getPullRequestBaseComparison",
237 cause: new Error("unreadable"),
238 }),
239 ),
240 getViewerAccess: () =>
241 Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
242 }),
243 ),
244 ),
245 );
246});
247
248describe("getChangeRequest commits", () => {
249 const baseDetail = {
250 authorId: null,
251 number: 7,
252 title: "Pull request 7",
253 url: "https://github.com/acme/web/pull/7",
254 author: null,
255 headBranch: "feat/page",
256 baseBranch: "main",
257 state: "open" as const,
258 isDraft: false,
259 mergeability: "mergeable" as const,
260 additions: 1,
261 deletions: 1,
262 createdAt: "2026-07-01T00:00:00Z",
263 updatedAt: "2026-07-02T00:00:00Z",
264 reviewRequestLogins: [],
265 hasTeamReviewRequest: false,
266 checksState: null,
267 labels: [],
268 body: "",
269 changedFiles: 1,
270 mergedAt: null,
271 closedAt: null,
272 checks: [],
273 comments: [],
274 };
275
276 const baseThreadComments = {
277 comments: [],
278 dismissalsByReviewId: new Map<string, string>(),
279 reviewThreads: [],
280 commentCount: 0,
281 truncated: false,
282 reactions: [],
283 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
284 reviewers: [],
285 avatarsByLogin: new Map<string, string>(),
286 commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
287 viewer: { canUpdate: true, didAuthor: false },
288 };
289
290 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
291 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
292 getPullRequestActivity: () =>
293 Effect.succeed({
294 author: baseDetail.author,
295 comments: baseDetail.comments,
296 commits: [
297 {
298 oid: "view-oldest",
299 messageHeadline: "gh pr view's oldest commit",
300 committedDate: "2026-01-01T00:00:00Z",
301 authors: [],
302 },
303 ],
304 }),
305 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
306 });
307
308 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
309 Effect.gen(function* () {
310 const provider = yield* make;
311 const detail = yield* provider.getChangeRequestActivity({
312 cwd: "/w",
313 repository: "acme/web",
314 host: "github.com",
315 number: 7,
316 });
317
318 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
319 }).pipe(
320 Effect.provide(
321 layerWith([
322 {
323 oid: "graphql-newest",
324 messageHeadline: "the newest commit gh pr view drops",
325 committedDate: "2026-07-06T00:00:00Z",
326 authors: [],
327 },
328 ]),
329 ),
330 ),
331 );
332
333 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
334 Effect.gen(function* () {
335 const provider = yield* make;
336 const detail = yield* provider.getChangeRequestActivity({
337 cwd: "/w",
338 repository: "acme/web",
339 host: "github.com",
340 number: 7,
341 });
342
343 expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
344 }).pipe(Effect.provide(layerWith([]))),
345 );
346});
347
348describe("getChangeRequestActivity dismissed reviews", () => {
349 const dismissedReview = (body: string) => ({
350 id: "PRR_1",
351 kind: "review" as const,
352 author: null,
353 body,
354 createdAt: "2026-07-03T00:00:00Z",
355 url: null,
356 path: null,
357 reviewState: "DISMISSED",
358 });
359 const threadComments: GitHubReviewThreadComments = {
360 comments: [],
361 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
362 reviewThreads: [],
363 commentCount: 0,
364 truncated: false,
365 reactions: [],
366 reactionsById: new Map(),
367 reviewers: [],
368 avatarsByLogin: new Map(),
369 commitStats: new Map(),
370 commits: [],
371 viewer: { canUpdate: true, didAuthor: false },
372 };
373 const layerFor = (body: string) =>
374 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
375 getPullRequestActivity: () =>
376 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
377 listReviewThreadComments: () => Effect.succeed(threadComments),
378 });
379 const readActivity = Effect.gen(function* () {
380 const provider = yield* make;
381 return yield* provider.getChangeRequestActivity({
382 cwd: "/w",
383 repository: "acme/web",
384 host: "github.com",
385 number: 7,
386 });
387 });
388
389 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
390 // Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
391 // an empty-string check misses them and the card opens onto nothing.
392 readActivity.pipe(
393 Effect.map((activity) => {
394 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
395 }),
396 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
397 ),
398 );
399
400 it.effect("keeps the words of a dismissed review that has its own", () =>
401 readActivity.pipe(
402 Effect.map((activity) => {
403 expect(activity.comments[0]?.body).toBe("These findings still stand.");
404 }),
405 Effect.provide(layerFor("These findings still stand.")),
406 ),
407 );
408});
409
410describe("editing", () => {
411 const rewrites: Array<unknown> = [];
412
413 it.effect("hands a rewrite to the CLI as the request named it", () =>
414 Effect.gen(function* () {
415 const provider = yield* make;
416
417 expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
418 yield* provider.updateChangeRequest!({
419 cwd: "/w",
420 repository: "acme/web",
421 host: "github.com",
422 number: 7,
423 title: "A better title",
424 });
425 yield* provider.updateComment!({
426 cwd: "/w",
427 repository: "acme/web",
428 host: "github.com",
429 number: 7,
430 commentId: "IC_1",
431 kind: "review-comment",
432 body: "Reworded.",
433 });
434
435 expect(rewrites).toEqual([
436 {
437 cwd: "/w",
438 repository: "acme/web",
439 host: "github.com",
440 number: 7,
441 title: "A better title",
442 },
443 {
444 cwd: "/w",
445 repository: "acme/web",
446 host: "github.com",
447 number: 7,
448 commentId: "IC_1",
449 kind: "review-comment",
450 body: "Reworded.",
451 },
452 ]);
453 }).pipe(
454 Effect.provide(
455 Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
456 updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
457 updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
458 }),
459 ),
460 ),
461 );
462});
463
464describe("loginAvatarUrl", () => {
465 it("serves a user's picture from the host they belong to", () => {
466 expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
467 expect(loginAvatarUrl("octocat", "ghe.example.com")).toBe(
468 "https://ghe.example.com/octocat.png?size=80",
469 );
470 });
471
472 it("has nothing for an app, which names no page", () => {
473 // `dependabot[bot]` has a picture, but not at `/dependabot[bot].png` — a guess that 404s is
474 // worse than the initials it would replace.
475 expect(loginAvatarUrl("dependabot[bot]", "github.com")).toBeNull();
476 });
477
478 it("refuses anything that is not a login, rather than building a URL out of it", () => {
479 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
480 expect(loginAvatarUrl(login, "github.com")).toBeNull();
481 }
482 });
483});