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