Open History to see the last commit
1import * as Result from "effect/Result";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 buildReviewSubmissionJson,
6 buildReviewerRequestJson,
7 decodeBaseComparisonJson,
8 decodePullRequestActivityJson,
9 decodePullRequestDetailJson,
10 decodePullRequestFilesJson,
11 decodePullRequestListJson,
12 decodePullRequestNodeIdJson,
13 decodePullRequestSearchJson,
14 decodeRepositoryAccessJson,
15 decodeReviewerCandidatesJson,
16 decodeReviewThreadCommentsJson,
17 decodeReviewThreadsJson,
18 decodeViewerPermissionsJson,
19 reviewThreadConversation,
20 REVIEW_THREADS_GRAPHQL_QUERY,
21} from "./gitHubPullRequestJson.ts";
22
23function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
24 return JSON.stringify(
25 entries.map((entry) => ({
26 number: 1,
27 title: "Add the pull requests page",
28 url: "https://github.com/pingdotgg/t3code/pull/1",
29 headRefName: "feat/page",
30 baseRefName: "main",
31 createdAt: "2026-07-01T00:00:00Z",
32 updatedAt: "2026-07-02T00:00:00Z",
33 ...entry,
34 })),
35 );
36}
37
38function expectSuccess<A>(result: Result.Result<A, unknown>): A {
39 expect(Result.isSuccess(result)).toBe(true);
40 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
41 return result.success;
42}
43
44describe("pull request list decoding", () => {
45 it("treats a merge timestamp as merged even when the state still says closed", () => {
46 const [entry] = expectSuccess(
47 decodePullRequestListJson(listJson([{ state: "CLOSED", mergedAt: "2026-07-03T00:00:00Z" }])),
48 ).items;
49 expect(entry?.state).toBe("merged");
50 });
51
52 it("normalizes mergeability and defaults unknown values", () => {
53 const batch = expectSuccess(
54 decodePullRequestListJson(
55 listJson([{ mergeable: "CONFLICTING" }, { mergeable: "SOMETHING_NEW" }, {}]),
56 ),
57 );
58 expect(batch.items.map((entry) => entry.mergeability)).toEqual([
59 "conflicting",
60 "unknown",
61 "unknown",
62 ]);
63 });
64
65 it("keeps user review requests and drops team ones, which are not logins", () => {
66 const [entry] = expectSuccess(
67 decodePullRequestListJson(
68 listJson([{ reviewRequests: [{ login: "octocat" }, { slug: "web-platform" }] }]),
69 ),
70 ).items;
71 expect(entry?.reviewRequestLogins).toEqual(["octocat"]);
72 });
73
74 it("normalizes the review decision and reports nothing for one GitHub does not summarize", () => {
75 const batch = expectSuccess(
76 decodePullRequestListJson(
77 listJson([
78 { reviewDecision: "APPROVED" },
79 { reviewDecision: "CHANGES_REQUESTED" },
80 { reviewDecision: "REVIEW_REQUIRED" },
81 { reviewDecision: null },
82 ]),
83 ),
84 );
85 expect(batch.items.map((entry) => entry.reviewDecision)).toEqual([
86 "approved",
87 "changes-requested",
88 "review-required",
89 null,
90 ]);
91 });
92
93 it("rolls the head commit's checks up to the one word a row has space for", () => {
94 const batch = expectSuccess(
95 decodePullRequestListJson(
96 listJson([
97 // A failure outranks a run still going, and a completed run has to be read through its
98 // conclusion rather than its status.
99 {
100 statusCheckRollup: [
101 { name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
102 { name: "build", status: "IN_PROGRESS" },
103 { name: "test", status: "COMPLETED", conclusion: "FAILURE" },
104 ],
105 },
106 {
107 statusCheckRollup: [
108 { name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
109 { name: "build", status: "QUEUED" },
110 ],
111 },
112 { statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }] },
113 // A commit status reports one `state` and no `status` at all.
114 { statusCheckRollup: [{ context: "ci/legacy", state: "ERROR" }] },
115 // Neither a pass, a failure nor a wait is no verdict rather than a green tick.
116 { statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SKIPPED" }] },
117 { statusCheckRollup: [] },
118 {},
119 ]),
120 ),
121 );
122 expect(batch.items.map((entry) => entry.checksState)).toEqual([
123 "failing",
124 "pending",
125 "passing",
126 "failing",
127 null,
128 null,
129 null,
130 ]);
131 });
132
133 it("skips malformed entries but still counts them, so paging does not stop early", () => {
134 const raw = `[${listJson([{}]).slice(1, -1)},{"number":"not-a-number"}]`;
135 const batch = expectSuccess(decodePullRequestListJson(raw));
136 expect(batch.items).toHaveLength(1);
137 expect(batch.rawCount).toBe(2);
138 });
139});
140
141describe("pull request search decoding", () => {
142 function searchJson(rollupStates: ReadonlyArray<string | null>): string {
143 return JSON.stringify({
144 data: {
145 search: {
146 pageInfo: { hasNextPage: false },
147 nodes: rollupStates.map((state, index) => ({
148 number: index + 1,
149 title: "Add the pull requests page",
150 url: "https://github.com/pingdotgg/t3code/pull/1",
151 headRefName: "feat/page",
152 baseRefName: "main",
153 createdAt: "2026-07-01T00:00:00Z",
154 updatedAt: "2026-07-02T00:00:00Z",
155 repository: { nameWithOwner: "pingdotgg/t3code" },
156 commits: {
157 nodes: [{ commit: { statusCheckRollup: state === null ? null : { state } } }],
158 },
159 })),
160 },
161 },
162 });
163 }
164
165 it("maps the rollup enum the search answers with onto the same three words", () => {
166 // The search asks GitHub for the verdict rather than the checks behind it, so this path sees
167 // one enum where the listing sees an array.
168 const batch = expectSuccess(
169 decodePullRequestSearchJson(
170 searchJson(["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED", null]),
171 ),
172 );
173 expect(batch.items.map((entry) => entry.checksState)).toEqual([
174 "passing",
175 "failing",
176 "failing",
177 "pending",
178 "pending",
179 null,
180 ]);
181 });
182});
183
184describe("pull request detail decoding", () => {
185 const detailJson = JSON.stringify({
186 number: 7,
187 title: "Detail",
188 url: "https://github.com/pingdotgg/t3code/pull/7",
189 headRefName: "feat/detail",
190 baseRefName: "main",
191 createdAt: "2026-07-01T00:00:00Z",
192 updatedAt: "2026-07-05T00:00:00Z",
193 body: "Body",
194 statusCheckRollup: [
195 { __typename: "CheckRun", name: "build", status: "IN_PROGRESS" },
196 { __typename: "CheckRun", name: "test", status: "COMPLETED", conclusion: "FAILURE" },
197 { __typename: "StatusContext", context: "ci/legacy", state: "SUCCESS" },
198 ],
199 comments: [{ id: "c1", body: "second", createdAt: "2026-07-04T00:00:00Z" }],
200 reviews: [
201 { id: "r1", body: "first", state: "CHANGES_REQUESTED", submittedAt: "2026-07-03T00:00:00Z" },
202 { id: "r2", body: " ", state: "APPROVED", submittedAt: "2026-07-06T00:00:00Z" },
203 ],
204 commits: [
205 {
206 oid: "abc1234",
207 messageHeadline: "Ship the timeline",
208 committedDate: "2026-07-05T00:00:00Z",
209 authors: [
210 { login: "octocat", name: "Octo Cat", email: "octo@example.com" },
211 { name: "Pair Author", email: "pair@example.com" },
212 ],
213 },
214 ],
215 });
216
217 it("maps check-run status and commit-status state onto one vocabulary", () => {
218 const detail = expectSuccess(decodePullRequestDetailJson(detailJson));
219 expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
220 ["build", "pending"],
221 ["test", "failure"],
222 ["ci/legacy", "success"],
223 ]);
224 });
225
226 it("reads an auto-merge request as armed, its null as off and its absence as neither", () => {
227 const raw = JSON.parse(detailJson) as Record<string, unknown>;
228 const armed = (entry: Record<string, unknown>) =>
229 expectSuccess(decodePullRequestDetailJson(JSON.stringify({ ...raw, ...entry })))
230 .autoMergeEnabled;
231
232 expect(
233 armed({ autoMergeRequest: { enabledBy: { login: "octocat" }, mergeMethod: "SQUASH" } }),
234 ).toBe(true);
235 expect(armed({ autoMergeRequest: null })).toBe(false);
236 // `gh` not answering for the field at all is not GitHub saying the merge is unarmed.
237 expect(armed({})).toBeUndefined();
238 });
239
240 it("shows a re-running check once, as the run that is happening now", () => {
241 // What `statusCheckRollup` reports while a workflow is being re-run: the same check twice,
242 // the finished run and the one that replaced it, with no id to tell them apart.
243 const raw = JSON.parse(detailJson) as Record<string, unknown>;
244 const detail = expectSuccess(
245 decodePullRequestDetailJson(
246 JSON.stringify({
247 ...raw,
248 statusCheckRollup: [
249 {
250 __typename: "CheckRun",
251 name: "Prepare PR size config",
252 workflowName: "PR Size",
253 status: "COMPLETED",
254 conclusion: "SUCCESS",
255 startedAt: "2026-08-11T16:06:20Z",
256 completedAt: "2026-08-11T16:06:25Z",
257 },
258 {
259 __typename: "CheckRun",
260 name: "Prepare PR size config",
261 workflowName: "PR Size",
262 status: "IN_PROGRESS",
263 conclusion: "",
264 startedAt: "2026-08-11T17:01:04Z",
265 completedAt: "0001-01-01T00:00:00Z",
266 },
267 ],
268 }),
269 ),
270 );
271
272 expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
273 ["Prepare PR size config", "pending"],
274 ]);
275 expect(detail.checksState).toBe("pending");
276 });
277
278 it("merges reviews with comments in time order and keeps a bodyless approval", () => {
279 const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
280 // r2 approved without writing anything, which is still the event worth seeing.
281 expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]);
282 expect(detail.comments.at(-1)?.reviewState).toBe("APPROVED");
283 });
284
285 it("keeps every attributed commit author, including an unlinked signature", () => {
286 const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
287 expect(detail.commits[0]?.authors).toEqual([
288 { login: "octocat", name: "Octo Cat", avatarUrl: null },
289 { login: "Pair Author", name: "Pair Author", avatarUrl: null },
290 ]);
291 });
292
293 it("drops the bodyless review GitHub opens to hold line comments", () => {
294 const raw = JSON.parse(detailJson) as Record<string, unknown>;
295 const detail = expectSuccess(
296 decodePullRequestActivityJson(
297 JSON.stringify({
298 ...raw,
299 reviews: [
300 // What a reviewer leaving inline comments produces: a container with a state but
301 // nothing to read. Its comments come from the review threads instead.
302 { id: "r4", body: "", state: "COMMENTED", submittedAt: "2026-07-07T00:00:00Z" },
303 {
304 id: "r5",
305 body: "Looks good.",
306 state: "COMMENTED",
307 submittedAt: "2026-07-08T00:00:00Z",
308 },
309 ],
310 }),
311 ),
312 );
313
314 expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "r5"]);
315 });
316
317 it.each(["APPROVED", "CHANGES_REQUESTED", "DISMISSED"])(
318 "keeps a bodyless %s review, which is the event itself",
319 (state) => {
320 const raw = JSON.parse(detailJson) as Record<string, unknown>;
321 const detail = expectSuccess(
322 decodePullRequestActivityJson(
323 JSON.stringify({
324 ...raw,
325 reviews: [{ id: "r6", body: "", state, submittedAt: "2026-07-07T00:00:00Z" }],
326 }),
327 ),
328 );
329
330 expect(detail.comments.map((comment) => comment.id)).toContain("r6");
331 },
332 );
333
334 it("drops a review that carries neither a body nor a state", () => {
335 const raw = JSON.parse(detailJson) as Record<string, unknown>;
336 const detail = expectSuccess(
337 decodePullRequestActivityJson(
338 JSON.stringify({
339 ...raw,
340 reviews: [{ id: "r3", body: " ", submittedAt: "2026-07-07T00:00:00Z" }],
341 }),
342 ),
343 );
344 expect(detail.comments.map((comment) => comment.id)).toEqual(["c1"]);
345 });
346});
347
348describe("review thread decoding", () => {
349 const threadsJson = (
350 nodes: ReadonlyArray<Record<string, unknown>>,
351 totalCount = nodes.length,
352 pageInfo: Record<string, unknown> = { hasNextPage: false, endCursor: null },
353 ): string =>
354 JSON.stringify({
355 data: { repository: { pullRequest: { reviewThreads: { totalCount, pageInfo, nodes } } } },
356 });
357
358 /** The same query carries the review roster, so it is built alongside the threads. */
359 const reviewJson = (input: {
360 readonly requested?: ReadonlyArray<unknown>;
361 readonly reviewed?: ReadonlyArray<unknown>;
362 }): string =>
363 JSON.stringify({
364 data: {
365 repository: {
366 pullRequest: {
367 reviewThreads: { totalCount: 0, nodes: [] },
368 reviewRequests: {
369 nodes: (input.requested ?? []).map((r) => ({ requestedReviewer: r })),
370 },
371 latestReviews: { nodes: (input.reviewed ?? []).map((a) => ({ author: a })) },
372 },
373 },
374 },
375 });
376
377 it("keeps a reviewer who has already reviewed, app or person, with their avatar", () => {
378 const result = expectSuccess(
379 decodeReviewThreadsJson(
380 reviewJson({
381 requested: [{ login: "julius", name: "Julius", avatarUrl: "https://avatars/j.png" }],
382 // An app that has reviewed is no longer an outstanding request, which is why asking
383 // only for requests reported nobody on a pull request a bot had reviewed.
384 reviewed: [{ login: "macroscopeapp", avatarUrl: "https://avatars/in/900172.png" }],
385 }),
386 ),
387 );
388
389 expect(result.reviewers).toEqual([
390 { login: "julius", name: "Julius", avatarUrl: "https://avatars/j.png" },
391 { login: "macroscopeapp", name: null, avatarUrl: "https://avatars/in/900172.png" },
392 ]);
393 });
394
395 it("carries per-commit line counts from the pull-request connection", () => {
396 const result = expectSuccess(
397 decodeReviewThreadsJson(
398 JSON.stringify({
399 data: {
400 repository: {
401 pullRequest: {
402 reviewThreads: { totalCount: 0, nodes: [] },
403 commits: {
404 nodes: [
405 { commit: { oid: "abc123", additions: 18, deletions: 7 } },
406 { commit: { oid: "def456", additions: 3, deletions: 0 } },
407 ],
408 },
409 },
410 },
411 },
412 }),
413 ),
414 );
415
416 expect([...result.commitStats]).toEqual([
417 ["abc123", { additions: 18, deletions: 7 }],
418 ["def456", { additions: 3, deletions: 0 }],
419 ]);
420 });
421
422 it("decodes the newest commits off the same connection, oldest to newest", () => {
423 const result = expectSuccess(
424 decodeReviewThreadsJson(
425 JSON.stringify({
426 data: {
427 repository: {
428 pullRequest: {
429 reviewThreads: { totalCount: 0, nodes: [] },
430 commits: {
431 nodes: [
432 {
433 commit: {
434 oid: "abc123",
435 messageHeadline: "Ship the timeline",
436 committedDate: "2026-07-05T00:00:00Z",
437 additions: 18,
438 deletions: 7,
439 authors: { nodes: [{ name: "Julius", user: { login: "julius" } }] },
440 },
441 },
442 {
443 commit: {
444 oid: "def456",
445 messageHeadline: "Fix the flaky test",
446 committedDate: "2026-07-06T00:00:00Z",
447 },
448 },
449 ],
450 },
451 },
452 },
453 },
454 }),
455 ),
456 );
457
458 expect(result.commits).toEqual([
459 {
460 oid: "abc123",
461 messageHeadline: "Ship the timeline",
462 committedDate: "2026-07-05T00:00:00Z",
463 authors: [{ login: "julius", name: "Julius", avatarUrl: null }],
464 },
465 {
466 oid: "def456",
467 messageHeadline: "Fix the flaky test",
468 committedDate: "2026-07-06T00:00:00Z",
469 authors: [],
470 },
471 ]);
472 });
473
474 it("lists someone who was asked and then answered only once", () => {
475 const result = expectSuccess(
476 decodeReviewThreadsJson(
477 reviewJson({
478 requested: [{ login: "julius", avatarUrl: "https://avatars/j.png" }],
479 reviewed: [{ login: "julius", avatarUrl: "https://avatars/j.png" }],
480 }),
481 ),
482 );
483
484 expect(result.reviewers).toHaveLength(1);
485 });
486
487 it("skips a team request, which names nobody to show", () => {
488 const result = expectSuccess(decodeReviewThreadsJson(reviewJson({ requested: [null] })));
489
490 expect(result.reviewers).toEqual([]);
491 });
492
493 it("keeps the conversation when a request is from a team, which has no login", () => {
494 // GraphQL answers with an empty object for a union member the query has no fragment for.
495 // Failing on it would take the whole response down, comments included.
496 const result = expectSuccess(
497 decodeReviewThreadsJson(
498 reviewJson({ requested: [{}, { login: "julius", avatarUrl: "https://avatars/j.png" }] }),
499 ),
500 );
501
502 expect(result.reviewers).toEqual([
503 { login: "julius", name: null, avatarUrl: "https://avatars/j.png" },
504 ]);
505 });
506
507 it("carries a resolved thread into the conversation, which was still said", () => {
508 const result = expectSuccess(
509 decodeReviewThreadsJson(
510 threadsJson([
511 {
512 id: "PRRT_a",
513 isResolved: false,
514 path: "apps/server/src/ws.ts",
515 comments: {
516 nodes: [{ id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" }],
517 },
518 },
519 {
520 id: "PRRT_b",
521 isResolved: true,
522 path: "apps/web/src/main.tsx",
523 comments: { nodes: [{ id: "t2", body: "done", createdAt: "2026-07-01T00:00:00Z" }] },
524 },
525 ]),
526 ),
527 );
528 const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
529 expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
530 expect(comments[0]).toMatchObject({
531 id: "t1",
532 kind: "review-comment",
533 path: "apps/server/src/ws.ts",
534 });
535 });
536
537 it("carries every reply, not only the remark each thread opened with", () => {
538 const result = expectSuccess(
539 decodeReviewThreadsJson(
540 threadsJson([
541 {
542 id: "PRRT_c",
543 isResolved: false,
544 path: "apps/server/src/ws.ts",
545 comments: {
546 nodes: [
547 { id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" },
548 { id: "t2", body: "fixed", createdAt: "2026-07-01T01:00:00Z" },
549 ],
550 },
551 },
552 ]),
553 ),
554 );
555 const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
556 expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
557 });
558
559 it("hands back the cursor the next page of threads carries on from", () => {
560 const result = expectSuccess(
561 decodeReviewThreadsJson(
562 threadsJson(
563 [
564 {
565 id: "PRRT_d",
566 path: "apps/server/src/ws.ts",
567 isResolved: false,
568 comments: { nodes: [{ id: "t1", createdAt: "2026-07-01T00:00:00Z" }] },
569 },
570 ],
571 80,
572 { hasNextPage: true, endCursor: "Y3Vyc29yOjE" },
573 ),
574 ),
575 );
576 expect(result.nextCursor).toBe("Y3Vyc29yOjE");
577 });
578
579 it("keeps GitHub's own count of a thread whose comments were not all read", () => {
580 const result = expectSuccess(
581 decodeReviewThreadsJson(
582 threadsJson([
583 {
584 id: "PRRT_e",
585 path: "apps/server/src/ws.ts",
586 isResolved: false,
587 comments: {
588 totalCount: 140,
589 pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjI" },
590 nodes: [{ id: "t1", createdAt: "2026-07-01T00:00:00Z" }],
591 },
592 },
593 ]),
594 ),
595 );
596 expect(result.threads[0]).toMatchObject({
597 commentCount: 140,
598 nextCommentCursor: "Y3Vyc29yOjI",
599 });
600 });
601
602 it("ends a thread's walk on the last page, which still names a cursor", () => {
603 const decoded = expectSuccess(
604 decodeReviewThreadCommentsJson(
605 JSON.stringify({
606 data: {
607 repository: { pullRequest: { id: "PR_1" } },
608 node: {
609 pullRequest: { id: "PR_1" },
610 comments: {
611 pageInfo: { hasNextPage: false, endCursor: "Y3Vyc29yOjk" },
612 nodes: [{ id: "t9", body: "last", createdAt: "2026-07-01T00:00:00Z" }],
613 },
614 },
615 },
616 }),
617 ),
618 );
619 expect(decoded.comments.map((comment) => comment.id)).toEqual(["t9"]);
620 expect(decoded.nextCursor).toBeNull();
621 });
622});
623
624describe("reaction decoding", () => {
625 const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>
626 JSON.stringify({
627 data: {
628 repository: { pullRequest: { id: "PR_1" } },
629 node: {
630 pullRequest: { id: "PR_1" },
631 comments: {
632 pageInfo: { hasNextPage: false, endCursor: null },
633 nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],
634 },
635 },
636 },
637 });
638
639 it("keeps a named group, widens a group whose reactors were cut short, drops an unknown content and an empty group", () => {
640 const decoded = expectSuccess(
641 decodeReviewThreadCommentsJson(
642 commentWithGroups([
643 {
644 content: "THUMBS_UP",
645 viewerHasReacted: true,
646 reactors: { totalCount: 2, nodes: [{ login: "julius" }, { login: "bilal" }] },
647 },
648 // Not one of the eight the contract carries.
649 {
650 content: "PARTY_PARROT",
651 reactors: { totalCount: 1, nodes: [{ login: "hubot" }] },
652 },
653 // Nobody behind it, which GitHub still answers a group for.
654 { content: "HEART", reactors: { totalCount: 0, nodes: [] } },
655 // More reactors than the bounded read named, and no `viewerHasReacted` at all.
656 {
657 content: "ROCKET",
658 reactors: { totalCount: 140, nodes: [{ login: "a" }, { login: "b" }, { login: "c" }] },
659 },
660 ]),
661 ),
662 );
663
664 expect(decoded.comments[0]?.reactions).toEqual([
665 { content: "thumbs-up", count: 2, actors: ["julius", "bilal"], viewerHasReacted: true },
666 { content: "rocket", count: 140, actors: ["a", "b", "c"], viewerHasReacted: false },
667 ]);
668 });
669
670 it("leaves the viewer's own login out of actors, matched case-insensitively, while count still counts them", () => {
671 const decoded = expectSuccess(
672 decodeReviewThreadCommentsJson(
673 JSON.stringify({
674 data: {
675 viewer: { login: "Bilal" },
676 repository: { pullRequest: { id: "PR_1" } },
677 node: {
678 pullRequest: { id: "PR_1" },
679 comments: {
680 pageInfo: { hasNextPage: false, endCursor: null },
681 nodes: [
682 {
683 id: "t1",
684 body: "nice",
685 createdAt: "2026-07-01T00:00:00Z",
686 reactionGroups: [
687 {
688 content: "HEART",
689 viewerHasReacted: true,
690 reactors: {
691 totalCount: 2,
692 nodes: [{ login: "bilal" }, { login: "julius" }],
693 },
694 },
695 ],
696 },
697 ],
698 },
699 },
700 },
701 }),
702 ),
703 );
704
705 expect(decoded.comments[0]?.reactions).toEqual([
706 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
707 ]);
708 });
709});
710
711describe("repository access decoding", () => {
712 const repositoryJson = (viewerPermission?: string | null) =>
713 JSON.stringify({
714 mergeCommitAllowed: true,
715 squashMergeAllowed: false,
716 rebaseMergeAllowed: true,
717 ...(viewerPermission === undefined ? {} : { viewerPermission }),
718 });
719
720 it("reads the three settings gh reports", () => {
721 expect(
722 expectSuccess(decodeRepositoryAccessJson(repositoryJson("ADMIN"))).mergeCapabilities,
723 ).toEqual({ merge: true, squash: false, rebase: true });
724 });
725
726 it("fails rather than defaulting open when a setting is missing", () => {
727 const decoded = decodeRepositoryAccessJson(JSON.stringify({ mergeCommitAllowed: true }));
728 expect(Result.isSuccess(decoded)).toBe(false);
729 });
730
731 it("counts the roles that can push as write, and the ones that cannot as read", () => {
732 for (const permission of ["ADMIN", "MAINTAIN", "WRITE"]) {
733 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(permission))).canWrite).toBe(
734 true,
735 );
736 }
737 for (const permission of ["TRIAGE", "READ", "NONE"]) {
738 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(permission))).canWrite).toBe(
739 false,
740 );
741 }
742 });
743
744 it("withholds write where gh names no permission, which is not a standing it gave", () => {
745 // The one place an unknown answer is not granted: a Merge button a reader cannot use wastes
746 // the press, where a missing one still leaves the pull request open on its host.
747 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson())).canWrite).toBe(false);
748 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(null))).canWrite).toBe(false);
749 });
750});
751
752describe("viewer permission decoding", () => {
753 const viewerJson = (repository: Record<string, unknown>) =>
754 JSON.stringify({ data: { repository } });
755
756 it("reads the repository's role and the pull request's own viewer fields together", () => {
757 expect(
758 expectSuccess(
759 decodeViewerPermissionsJson(
760 viewerJson({
761 viewerPermission: "READ",
762 pullRequest: { viewerCanUpdate: true, viewerDidAuthor: true },
763 }),
764 ),
765 ),
766 ).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });
767 });
768
769 it("says no to a passer-by on a repository they can only read", () => {
770 expect(
771 expectSuccess(
772 decodeViewerPermissionsJson(
773 viewerJson({
774 viewerPermission: "READ",
775 pullRequest: { viewerCanUpdate: false, viewerDidAuthor: false },
776 }),
777 ),
778 ),
779 ).toEqual({ canWrite: false, canUpdate: false, didAuthor: false });
780 });
781
782 it("reads silence as permission, but not as authorship", () => {
783 // A node the viewer cannot see comes back null. Updating is a permission, so an unknown
784 // answer grants it and lets the host refuse; authorship is a fact about who wrote the change,
785 // and claiming it for someone who did not is how an author's own rules get handed out.
786 expect(expectSuccess(decodeViewerPermissionsJson(viewerJson({ pullRequest: null })))).toEqual({
787 canWrite: false,
788 canUpdate: true,
789 didAuthor: false,
790 });
791 });
792});
793
794describe("review thread decoding", () => {
795 const threadsJson = (
796 nodes: ReadonlyArray<Record<string, unknown>>,
797 pullRequest: Record<string, unknown> = {},
798 ) =>
799 JSON.stringify({
800 data: {
801 repository: {
802 pullRequest: {
803 reviewThreads: { totalCount: nodes.length, nodes },
804 author: null,
805 comments: { nodes: [] },
806 reviewRequests: { nodes: [] },
807 latestReviews: { nodes: [] },
808 ...pullRequest,
809 },
810 },
811 },
812 });
813
814 it("carries what the reader may do with the pull request, off the conversation read", () => {
815 // The same response the threads arrive in, so knowing this costs no request of its own.
816 expect(
817 expectSuccess(
818 decodeReviewThreadsJson(
819 threadsJson([], { viewerCanUpdate: false, viewerDidAuthor: false }),
820 ),
821 ).viewer,
822 ).toEqual({ canUpdate: false, didAuthor: false });
823 expect(expectSuccess(decodeReviewThreadsJson(threadsJson([]))).viewer).toEqual({
824 canUpdate: true,
825 didAuthor: false,
826 });
827 });
828
829 const comment = (id: string, body: string) => ({
830 id,
831 author: { login: "bilal", avatarUrl: "https://avatars/b.png" },
832 body,
833 createdAt: "2026-07-01T00:00:00Z",
834 url: `https://github.com/acme/web/pull/1#discussion_r${id}`,
835 });
836
837 it("anchors a thread to its line and side, keeping the whole conversation", () => {
838 const reviewThreads = expectSuccess(
839 decodeReviewThreadsJson(
840 threadsJson([
841 {
842 id: "PRRT_1",
843 isResolved: false,
844 isOutdated: false,
845 path: "src/a.ts",
846 line: 42,
847 diffSide: "LEFT",
848 comments: { totalCount: 2, nodes: [comment("c1", "first"), comment("c2", "second")] },
849 },
850 ]),
851 ),
852 );
853 expect(reviewThreads.threads.map((entry) => entry.thread)).toEqual([
854 {
855 id: "PRRT_1",
856 path: "src/a.ts",
857 line: 42,
858 side: "left",
859 isResolved: false,
860 isOutdated: false,
861 comments: [
862 {
863 id: "c1",
864 author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
865 body: "first",
866 createdAt: "2026-07-01T00:00:00Z",
867 url: "https://github.com/acme/web/pull/1#discussion_rc1",
868 reactions: [],
869 },
870 {
871 id: "c2",
872 author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
873 body: "second",
874 createdAt: "2026-07-01T00:00:00Z",
875 url: "https://github.com/acme/web/pull/1#discussion_rc2",
876 reactions: [],
877 },
878 ],
879 },
880 ]);
881 });
882
883 it("leaves an outdated thread without a line rather than pinning it to a stale one", () => {
884 const reviewThreads = expectSuccess(
885 decodeReviewThreadsJson(
886 threadsJson([
887 {
888 id: "PRRT_2",
889 isResolved: true,
890 isOutdated: true,
891 path: "src/a.ts",
892 // GitHub reports no current line once the thread has fallen off the diff.
893 line: null,
894 diffSide: "RIGHT",
895 comments: { totalCount: 1, nodes: [comment("c3", "stale")] },
896 },
897 ]),
898 ),
899 );
900 expect(reviewThreads.threads[0]?.thread).toMatchObject({
901 line: null,
902 isOutdated: true,
903 isResolved: true,
904 });
905 });
906
907 it("keeps a resolved thread in the conversation as well as against its line", () => {
908 const decoded = expectSuccess(
909 decodeReviewThreadsJson(
910 threadsJson([
911 {
912 id: "PRRT_3",
913 isResolved: true,
914 path: "src/a.ts",
915 line: 7,
916 diffSide: "RIGHT",
917 comments: { totalCount: 1, nodes: [comment("c4", "done")] },
918 },
919 ]),
920 ),
921 );
922 // A resolved conversation is finished work, not unsaid work: the timeline reads it and the
923 // diff pins it to its line, the same as any other.
924 const threads = decoded.threads.map((entry) => entry.thread);
925 expect(reviewThreadConversation(threads).map((comment) => comment.id)).toEqual(["c4"]);
926 expect(threads).toHaveLength(1);
927 });
928
929 it("puts an issue comment's and a review's reactions in reactionsById, and the pull request's own in reactions", () => {
930 const result = expectSuccess(
931 decodeReviewThreadsJson(
932 threadsJson([], {
933 reactionGroups: [
934 {
935 content: "HEART",
936 viewerHasReacted: true,
937 reactors: { totalCount: 1, nodes: [{ login: "bilal" }] },
938 },
939 ],
940 comments: {
941 nodes: [
942 {
943 id: "c1",
944 reactionGroups: [
945 {
946 content: "THUMBS_UP",
947 reactors: { totalCount: 1, nodes: [{ login: "julius" }] },
948 },
949 ],
950 },
951 ],
952 },
953 reviews: {
954 nodes: [
955 {
956 id: "r1",
957 reactionGroups: [
958 { content: "EYES", reactors: { totalCount: 1, nodes: [{ login: "hubot" }] } },
959 ],
960 },
961 ],
962 },
963 }),
964 ),
965 );
966
967 expect(result.reactions).toEqual([
968 { content: "heart", count: 1, actors: ["bilal"], viewerHasReacted: true },
969 ]);
970 expect([...result.reactionsById]).toEqual([
971 ["c1", [{ content: "thumbs-up", count: 1, actors: ["julius"], viewerHasReacted: false }]],
972 ["r1", [{ content: "eyes", count: 1, actors: ["hubot"], viewerHasReacted: false }]],
973 ]);
974 });
975
976 it("leaves the viewer's own login out of the pull request's own reactions, matched case-insensitively, while count still counts them", () => {
977 const result = expectSuccess(
978 decodeReviewThreadsJson(
979 JSON.stringify({
980 data: {
981 viewer: { login: "Bilal" },
982 repository: {
983 pullRequest: {
984 reviewThreads: { totalCount: 0, nodes: [] },
985 reactionGroups: [
986 {
987 content: "HEART",
988 viewerHasReacted: true,
989 reactors: { totalCount: 2, nodes: [{ login: "bilal" }, { login: "julius" }] },
990 },
991 ],
992 },
993 },
994 },
995 }),
996 ),
997 );
998
999 expect(result.reactions).toEqual([
1000 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
1001 ]);
1002 });
1003});
1004
1005describe("decodePullRequestNodeIdJson", () => {
1006 it("reads the pull request's own node id, which a reaction on its description is addressed by", () => {
1007 expect(
1008 expectSuccess(
1009 decodePullRequestNodeIdJson(
1010 JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
1011 ),
1012 ),
1013 ).toBe("PR_kwDOA");
1014 });
1015});
1016
1017describe("REVIEW_THREADS_GRAPHQL_QUERY", () => {
1018 it("caps the initial query after the 104-point rate-limit regression", () => {
1019 const match = REVIEW_THREADS_GRAPHQL_QUERY.match(
1020 /reviewThreads\(first: (\d+)[\s\S]*?comments\(first: (\d+)\)/u,
1021 );
1022
1023 expect(match).not.toBeNull();
1024 if (match === null) throw new Error("expected review-thread connections");
1025 expect(Number(match[1]) * Number(match[2])).toBeLessThanOrEqual(1_000);
1026 });
1027
1028 it("asks for reactionGroups on the pull request itself, its comments, its reviews and each thread's comments", () => {
1029 expect(REVIEW_THREADS_GRAPHQL_QUERY.match(/reactionGroups/g)).toHaveLength(4);
1030 // The reviews connection is new: only reactions were ever wanted off it.
1031 expect(REVIEW_THREADS_GRAPHQL_QUERY).toContain("reviews(first:");
1032 });
1033});
1034
1035describe("reviewer candidate decoding", () => {
1036 const candidatesJson = (input: {
1037 readonly assignable: ReadonlyArray<Record<string, unknown> | null>;
1038 readonly requested?: ReadonlyArray<Record<string, unknown> | null>;
1039 readonly author?: string;
1040 readonly hasNextPage?: boolean;
1041 }) =>
1042 JSON.stringify({
1043 data: {
1044 repository: {
1045 assignableUsers: {
1046 pageInfo: { hasNextPage: input.hasNextPage ?? false },
1047 nodes: input.assignable,
1048 },
1049 pullRequest: {
1050 author: input.author === undefined ? null : { login: input.author },
1051 reviewRequests: {
1052 nodes: (input.requested ?? []).map((requestedReviewer) => ({ requestedReviewer })),
1053 },
1054 },
1055 },
1056 },
1057 });
1058
1059 it("leaves the author out of the people their own pull request can be sent to", () => {
1060 const list = expectSuccess(
1061 decodeReviewerCandidatesJson(
1062 candidatesJson({
1063 assignable: [{ login: "bilal" }, { login: "octocat", name: "The Octocat" }],
1064 author: "bilal",
1065 }),
1066 ),
1067 );
1068 expect(list.candidates).toEqual([
1069 {
1070 id: "octocat",
1071 kind: "user",
1072 login: "octocat",
1073 name: "The Octocat",
1074 avatarUrl: null,
1075 isRequested: false,
1076 },
1077 ]);
1078 expect(list.truncated).toBe(false);
1079 });
1080
1081 it("marks whoever has already been asked, and leaves the rest to be asked", () => {
1082 const list = expectSuccess(
1083 decodeReviewerCandidatesJson(
1084 candidatesJson({
1085 assignable: [{ login: "octocat" }, { login: "hubot" }],
1086 requested: [{ login: "octocat" }],
1087 }),
1088 ),
1089 );
1090 expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([
1091 ["octocat", true],
1092 ["hubot", false],
1093 ]);
1094 });
1095
1096 it("keeps a requested team apart from the people, so the request can be taken back", () => {
1097 // A team is never among the assignable users, and a request that cannot be seen cannot be
1098 // undone — so the ones GitHub reports are carried, marked as the teams they are.
1099 const list = expectSuccess(
1100 decodeReviewerCandidatesJson(
1101 candidatesJson({
1102 assignable: [{ login: "octocat" }],
1103 requested: [{ slug: "reviewers", name: "Reviewers" }],
1104 }),
1105 ),
1106 );
1107 expect(list.candidates).toEqual([
1108 {
1109 id: "reviewers",
1110 kind: "team",
1111 login: "reviewers",
1112 name: "Reviewers",
1113 avatarUrl: null,
1114 isRequested: true,
1115 },
1116 {
1117 id: "octocat",
1118 kind: "user",
1119 login: "octocat",
1120 name: null,
1121 avatarUrl: null,
1122 isRequested: false,
1123 },
1124 ]);
1125 });
1126
1127 it("says so when the repository has more people than the read asked for", () => {
1128 expect(
1129 expectSuccess(
1130 decodeReviewerCandidatesJson(
1131 candidatesJson({ assignable: [{ login: "octocat" }], hasNextPage: true }),
1132 ),
1133 ).truncated,
1134 ).toBe(true);
1135 });
1136});
1137
1138describe("reviewer request payload", () => {
1139 it("sends people and teams in the two lists GitHub keeps them in", () => {
1140 expect(
1141 JSON.parse(
1142 buildReviewerRequestJson([
1143 { id: "octocat", kind: "user" },
1144 { id: "reviewers", kind: "team" },
1145 { id: "hubot", kind: "user" },
1146 ]),
1147 ),
1148 ).toEqual({ reviewers: ["octocat", "hubot"], team_reviewers: ["reviewers"] });
1149 });
1150
1151 it("sends both lists even where one of them is empty, which is what GitHub reads", () => {
1152 expect(JSON.parse(buildReviewerRequestJson([{ id: "octocat", kind: "user" }]))).toEqual({
1153 reviewers: ["octocat"],
1154 team_reviewers: [],
1155 });
1156 });
1157});
1158
1159describe("review submission payload", () => {
1160 it("sends the verdict, the summary and every line comment in one body", () => {
1161 const payload = JSON.parse(
1162 buildReviewSubmissionJson({
1163 verdict: "request-changes",
1164 body: "Two things.",
1165 comments: [
1166 {
1167 path: "src/a.ts",
1168 position: { kind: "added", newLine: 12 },
1169 body: "rename this",
1170 },
1171 {
1172 path: "src/b.ts",
1173 position: { kind: "deleted", oldLine: 3 },
1174 body: "why remove?",
1175 },
1176 ],
1177 }),
1178 ) as Record<string, unknown>;
1179 expect(payload).toEqual({
1180 event: "REQUEST_CHANGES",
1181 body: "Two things.",
1182 comments: [
1183 { path: "src/a.ts", line: 12, side: "RIGHT", body: "rename this" },
1184 { path: "src/b.ts", line: 3, side: "LEFT", body: "why remove?" },
1185 ],
1186 });
1187 });
1188
1189 it("sends an approval with no words and no comments", () => {
1190 expect(
1191 JSON.parse(buildReviewSubmissionJson({ verdict: "approve", body: "", comments: [] })),
1192 ).toEqual({ event: "APPROVE", body: "", comments: [] });
1193 });
1194});
1195
1196describe("decodePullRequestFilesJson", () => {
1197 it("assembles a unified patch the files API does not return", () => {
1198 const result = expectSuccess(
1199 decodePullRequestFilesJson(
1200 JSON.stringify([
1201 { filename: "src/app.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" },
1202 ]),
1203 ),
1204 );
1205
1206 expect(result.patch).toBe(
1207 [
1208 "diff --git a/src/app.ts b/src/app.ts",
1209 "--- a/src/app.ts",
1210 "+++ b/src/app.ts",
1211 "@@ -1 +1 @@",
1212 "-old",
1213 "+new",
1214 "",
1215 ].join("\n"),
1216 );
1217 expect(result.truncated).toBe(false);
1218 expect(result.rawCount).toBe(1);
1219 });
1220
1221 it("points an added file at /dev/null on the left and a removed one on the right", () => {
1222 const result = expectSuccess(
1223 decodePullRequestFilesJson(
1224 JSON.stringify([
1225 { filename: "src/new.ts", status: "added", patch: "@@ -0,0 +1 @@\n+hello" },
1226 { filename: "src/gone.ts", status: "removed", patch: "@@ -1 +0,0 @@\n-bye" },
1227 ]),
1228 ),
1229 );
1230
1231 expect(result.patch).toBe(
1232 [
1233 "diff --git a/src/new.ts b/src/new.ts",
1234 "new file mode 100644",
1235 "--- /dev/null",
1236 "+++ b/src/new.ts",
1237 "@@ -0,0 +1 @@",
1238 "+hello",
1239 "diff --git a/src/gone.ts b/src/gone.ts",
1240 "deleted file mode 100644",
1241 "--- a/src/gone.ts",
1242 "+++ /dev/null",
1243 "@@ -1 +0,0 @@",
1244 "-bye",
1245 "",
1246 ].join("\n"),
1247 );
1248 });
1249
1250 it("names both paths of a rename, counting its hunks against the old one", () => {
1251 const result = expectSuccess(
1252 decodePullRequestFilesJson(
1253 JSON.stringify([
1254 {
1255 filename: "src/new.ts",
1256 status: "renamed",
1257 previous_filename: "src/old.ts",
1258 patch: "@@ -1 +1 @@\n-old\n+new",
1259 },
1260 ]),
1261 ),
1262 );
1263
1264 expect(result.patch).toBe(
1265 [
1266 "diff --git a/src/old.ts b/src/new.ts",
1267 "rename from src/old.ts",
1268 "rename to src/new.ts",
1269 "--- a/src/old.ts",
1270 "+++ b/src/new.ts",
1271 "@@ -1 +1 @@",
1272 "-old",
1273 "+new",
1274 "",
1275 ].join("\n"),
1276 );
1277 });
1278
1279 it("still lists a file GitHub sent no hunks for, and says what was withheld", () => {
1280 const result = expectSuccess(
1281 decodePullRequestFilesJson(
1282 JSON.stringify([
1283 // Binary: it changed, and none of it can be shown.
1284 { filename: "logo.png", status: "modified", additions: 4, deletions: 2 },
1285 {
1286 filename: "src/app.ts",
1287 status: "modified",
1288 additions: 1,
1289 deletions: 1,
1290 patch: "@@ -1 +1 @@\n-old\n+new",
1291 },
1292 ]),
1293 ),
1294 );
1295
1296 // Dropping it would take the file out of the change altogether, not just its contents.
1297 expect(result.patch).toContain("diff --git a/logo.png b/logo.png");
1298 expect(result.patch).toContain("diff --git a/src/app.ts b/src/app.ts");
1299 expect(result.truncated).toBe(true);
1300 expect(result.rawCount).toBe(2);
1301 });
1302
1303 it("does not call a pure rename incomplete, since it has no hunks to withhold", () => {
1304 const result = expectSuccess(
1305 decodePullRequestFilesJson(
1306 JSON.stringify([
1307 {
1308 filename: "src/new.ts",
1309 previous_filename: "src/old.ts",
1310 status: "renamed",
1311 additions: 0,
1312 deletions: 0,
1313 },
1314 ]),
1315 ),
1316 );
1317
1318 expect(result.patch).toContain("rename from src/old.ts");
1319 expect(result.truncated).toBe(false);
1320 });
1321});
1322
1323describe("how far a branch trails its base", () => {
1324 const comparison = (pullRequest: unknown) =>
1325 JSON.stringify({ data: { repository: { pullRequest } } });
1326
1327 it("reads the commit count and whether this viewer may move the branch", () => {
1328 const decoded = expectSuccess(
1329 decodeBaseComparisonJson(
1330 comparison({ viewerCanUpdateBranch: true, baseRef: { compare: { behindBy: 12 } } }),
1331 ),
1332 );
1333 expect(decoded).toEqual({ behindBy: 12, viewerCanUpdate: true });
1334 });
1335
1336 it("reads a current branch as nothing to do", () => {
1337 expect(
1338 expectSuccess(
1339 decodeBaseComparisonJson(
1340 comparison({ viewerCanUpdateBranch: false, baseRef: { compare: { behindBy: 0 } } }),
1341 ),
1342 ),
1343 ).toEqual({ behindBy: 0, viewerCanUpdate: false });
1344 });
1345
1346 it("answers unknown where the head could not be compared", () => {
1347 // A pull request from a fork whose repository is gone, which GitHub answers with a null
1348 // comparison beside a perfectly good pull request.
1349 expect(
1350 expectSuccess(
1351 decodeBaseComparisonJson(comparison({ viewerCanUpdateBranch: true, baseRef: null })),
1352 ).behindBy,
1353 ).toBeNull();
1354 expect(expectSuccess(decodeBaseComparisonJson(comparison(null)))).toEqual({
1355 behindBy: null,
1356 viewerCanUpdate: false,
1357 });
1358 });
1359
1360 it("refuses a body that is not the answer to this question", () => {
1361 expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
1362 });
1363});