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

gitHubPullRequestJson.test.ts

1,339 lines43.5 KB

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 );
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;
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 node: {
608 comments: {
609 pageInfo: { hasNextPage: false, endCursor: "Y3Vyc29yOjk" },
610 nodes: [{ id: "t9", body: "last", createdAt: "2026-07-01T00:00:00Z" }],
611 },
612 },
613 },
614 }),
615 ),
616 );
617 expect(decoded.comments.map((comment) => comment.id)).toEqual(["t9"]);
618 expect(decoded.nextCursor).toBeNull();
619 });
620});
621​
622describe("reaction decoding", () => {
623 const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>
624 JSON.stringify({
625 data: {
626 node: {
627 comments: {
628 pageInfo: { hasNextPage: false, endCursor: null },
629 nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],
630 },
631 },
632 },
633 });
634​
635 it("keeps a named group, widens a group whose reactors were cut short, drops an unknown content and an empty group", () => {
636 const decoded = expectSuccess(
637 decodeReviewThreadCommentsJson(
638 commentWithGroups([
639 {
640 content: "THUMBS_UP",
641 viewerHasReacted: true,
642 reactors: { totalCount: 2, nodes: [{ login: "julius" }, { login: "bilal" }] },
643 },
644 // Not one of the eight the contract carries.
645 {
646 content: "PARTY_PARROT",
647 reactors: { totalCount: 1, nodes: [{ login: "hubot" }] },
648 },
649 // Nobody behind it, which GitHub still answers a group for.
650 { content: "HEART", reactors: { totalCount: 0, nodes: [] } },
651 // More reactors than the bounded read named, and no `viewerHasReacted` at all.
652 {
653 content: "ROCKET",
654 reactors: { totalCount: 140, nodes: [{ login: "a" }, { login: "b" }, { login: "c" }] },
655 },
656 ]),
657 ),
658 );
659​
660 expect(decoded.comments[0]?.reactions).toEqual([
661 { content: "thumbs-up", count: 2, actors: ["julius", "bilal"], viewerHasReacted: true },
662 { content: "rocket", count: 140, actors: ["a", "b", "c"], viewerHasReacted: false },
663 ]);
664 });
665​
666 it("leaves the viewer's own login out of actors, matched case-insensitively, while count still counts them", () => {
667 const decoded = expectSuccess(
668 decodeReviewThreadCommentsJson(
669 JSON.stringify({
670 data: {
671 viewer: { login: "Bilal" },
672 node: {
673 comments: {
674 pageInfo: { hasNextPage: false, endCursor: null },
675 nodes: [
676 {
677 id: "t1",
678 body: "nice",
679 createdAt: "2026-07-01T00:00:00Z",
680 reactionGroups: [
681 {
682 content: "HEART",
683 viewerHasReacted: true,
684 reactors: {
685 totalCount: 2,
686 nodes: [{ login: "bilal" }, { login: "julius" }],
687 },
688 },
689 ],
690 },
691 ],
692 },
693 },
694 },
695 }),
696 ),
697 );
698​
699 expect(decoded.comments[0]?.reactions).toEqual([
700 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
701 ]);
702 });
703});
704​
705describe("repository access decoding", () => {
706 const repositoryJson = (viewerPermission?: string | null) =>
707 JSON.stringify({
708 mergeCommitAllowed: true,
709 squashMergeAllowed: false,
710 rebaseMergeAllowed: true,
711 ...(viewerPermission === undefined ? {} : { viewerPermission }),
712 });
713​
714 it("reads the three settings gh reports", () => {
715 expect(
716 expectSuccess(decodeRepositoryAccessJson(repositoryJson("ADMIN"))).mergeCapabilities,
717 ).toEqual({ merge: true, squash: false, rebase: true });
718 });
719​
720 it("fails rather than defaulting open when a setting is missing", () => {
721 const decoded = decodeRepositoryAccessJson(JSON.stringify({ mergeCommitAllowed: true }));
722 expect(Result.isSuccess(decoded)).toBe(false);
723 });
724​
725 it("counts the roles that can push as write, and the ones that cannot as read", () => {
726 for (const permission of ["ADMIN", "MAINTAIN", "WRITE"]) {
727 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(permission))).canWrite).toBe(
728 true,
729 );
730 }
731 for (const permission of ["TRIAGE", "READ", "NONE"]) {
732 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(permission))).canWrite).toBe(
733 false,
734 );
735 }
736 });
737​
738 it("withholds write where gh names no permission, which is not a standing it gave", () => {
739 // The one place an unknown answer is not granted: a Merge button a reader cannot use wastes
740 // the press, where a missing one still leaves the pull request open on its host.
741 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson())).canWrite).toBe(false);
742 expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(null))).canWrite).toBe(false);
743 });
744});
745​
746describe("viewer permission decoding", () => {
747 const viewerJson = (repository: Record<string, unknown>) =>
748 JSON.stringify({ data: { repository } });
749​
750 it("reads the repository's role and the pull request's own viewer fields together", () => {
751 expect(
752 expectSuccess(
753 decodeViewerPermissionsJson(
754 viewerJson({
755 viewerPermission: "READ",
756 pullRequest: { viewerCanUpdate: true, viewerDidAuthor: true },
757 }),
758 ),
759 ),
760 ).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });
761 });
762​
763 it("says no to a passer-by on a repository they can only read", () => {
764 expect(
765 expectSuccess(
766 decodeViewerPermissionsJson(
767 viewerJson({
768 viewerPermission: "READ",
769 pullRequest: { viewerCanUpdate: false, viewerDidAuthor: false },
770 }),
771 ),
772 ),
773 ).toEqual({ canWrite: false, canUpdate: false, didAuthor: false });
774 });
775​
776 it("reads silence as permission, but not as authorship", () => {
777 // A node the viewer cannot see comes back null. Updating is a permission, so an unknown
778 // answer grants it and lets the host refuse; authorship is a fact about who wrote the change,
779 // and claiming it for someone who did not is how an author's own rules get handed out.
780 expect(expectSuccess(decodeViewerPermissionsJson(viewerJson({ pullRequest: null })))).toEqual({
781 canWrite: false,
782 canUpdate: true,
783 didAuthor: false,
784 });
785 });
786});
787​
788describe("review thread decoding", () => {
789 const threadsJson = (
790 nodes: ReadonlyArray<Record<string, unknown>>,
791 pullRequest: Record<string, unknown> = {},
792 ) =>
793 JSON.stringify({
794 data: {
795 repository: {
796 pullRequest: {
797 reviewThreads: { totalCount: nodes.length, nodes },
798 author: null,
799 comments: { nodes: [] },
800 reviewRequests: { nodes: [] },
801 latestReviews: { nodes: [] },
802 ...pullRequest,
803 },
804 },
805 },
806 });
807​
808 it("carries what the reader may do with the pull request, off the conversation read", () => {
809 // The same response the threads arrive in, so knowing this costs no request of its own.
810 expect(
811 expectSuccess(
812 decodeReviewThreadsJson(
813 threadsJson([], { viewerCanUpdate: false, viewerDidAuthor: false }),
814 ),
815 ).viewer,
816 ).toEqual({ canUpdate: false, didAuthor: false });
817 expect(expectSuccess(decodeReviewThreadsJson(threadsJson([]))).viewer).toEqual({
818 canUpdate: true,
819 didAuthor: false,
820 });
821 });
822​
823 const comment = (id: string, body: string) => ({
824 id,
825 author: { login: "bilal", avatarUrl: "https://avatars/b.png" },
826 body,
827 createdAt: "2026-07-01T00:00:00Z",
828 url: `https://github.com/acme/web/pull/1#discussion_r${id}`,
829 });
830​
831 it("anchors a thread to its line and side, keeping the whole conversation", () => {
832 const reviewThreads = expectSuccess(
833 decodeReviewThreadsJson(
834 threadsJson([
835 {
836 id: "PRRT_1",
837 isResolved: false,
838 isOutdated: false,
839 path: "src/a.ts",
840 line: 42,
841 diffSide: "LEFT",
842 comments: { totalCount: 2, nodes: [comment("c1", "first"), comment("c2", "second")] },
843 },
844 ]),
845 ),
846 );
847 expect(reviewThreads.threads.map((entry) => entry.thread)).toEqual([
848 {
849 id: "PRRT_1",
850 path: "src/a.ts",
851 line: 42,
852 side: "left",
853 isResolved: false,
854 isOutdated: false,
855 comments: [
856 {
857 id: "c1",
858 author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
859 body: "first",
860 createdAt: "2026-07-01T00:00:00Z",
861 url: "https://github.com/acme/web/pull/1#discussion_rc1",
862 reactions: [],
863 },
864 {
865 id: "c2",
866 author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
867 body: "second",
868 createdAt: "2026-07-01T00:00:00Z",
869 url: "https://github.com/acme/web/pull/1#discussion_rc2",
870 reactions: [],
871 },
872 ],
873 },
874 ]);
875 });
876​
877 it("leaves an outdated thread without a line rather than pinning it to a stale one", () => {
878 const reviewThreads = expectSuccess(
879 decodeReviewThreadsJson(
880 threadsJson([
881 {
882 id: "PRRT_2",
883 isResolved: true,
884 isOutdated: true,
885 path: "src/a.ts",
886 // GitHub reports no current line once the thread has fallen off the diff.
887 line: null,
888 diffSide: "RIGHT",
889 comments: { totalCount: 1, nodes: [comment("c3", "stale")] },
890 },
891 ]),
892 ),
893 );
894 expect(reviewThreads.threads[0]?.thread).toMatchObject({
895 line: null,
896 isOutdated: true,
897 isResolved: true,
898 });
899 });
900​
901 it("keeps a resolved thread in the conversation as well as against its line", () => {
902 const decoded = expectSuccess(
903 decodeReviewThreadsJson(
904 threadsJson([
905 {
906 id: "PRRT_3",
907 isResolved: true,
908 path: "src/a.ts",
909 line: 7,
910 diffSide: "RIGHT",
911 comments: { totalCount: 1, nodes: [comment("c4", "done")] },
912 },
913 ]),
914 ),
915 );
916 // A resolved conversation is finished work, not unsaid work: the timeline reads it and the
917 // diff pins it to its line, the same as any other.
918 const threads = decoded.threads.map((entry) => entry.thread);
919 expect(reviewThreadConversation(threads).map((comment) => comment.id)).toEqual(["c4"]);
920 expect(threads).toHaveLength(1);
921 });
922​
923 it("puts an issue comment's and a review's reactions in reactionsById, and the pull request's own in reactions", () => {
924 const result = expectSuccess(
925 decodeReviewThreadsJson(
926 threadsJson([], {
927 reactionGroups: [
928 {
929 content: "HEART",
930 viewerHasReacted: true,
931 reactors: { totalCount: 1, nodes: [{ login: "bilal" }] },
932 },
933 ],
934 comments: {
935 nodes: [
936 {
937 id: "c1",
938 reactionGroups: [
939 {
940 content: "THUMBS_UP",
941 reactors: { totalCount: 1, nodes: [{ login: "julius" }] },
942 },
943 ],
944 },
945 ],
946 },
947 reviews: {
948 nodes: [
949 {
950 id: "r1",
951 reactionGroups: [
952 { content: "EYES", reactors: { totalCount: 1, nodes: [{ login: "hubot" }] } },
953 ],
954 },
955 ],
956 },
957 }),
958 ),
959 );
960​
961 expect(result.reactions).toEqual([
962 { content: "heart", count: 1, actors: ["bilal"], viewerHasReacted: true },
963 ]);
964 expect([...result.reactionsById]).toEqual([
965 ["c1", [{ content: "thumbs-up", count: 1, actors: ["julius"], viewerHasReacted: false }]],
966 ["r1", [{ content: "eyes", count: 1, actors: ["hubot"], viewerHasReacted: false }]],
967 ]);
968 });
969​
970 it("leaves the viewer's own login out of the pull request's own reactions, matched case-insensitively, while count still counts them", () => {
971 const result = expectSuccess(
972 decodeReviewThreadsJson(
973 JSON.stringify({
974 data: {
975 viewer: { login: "Bilal" },
976 repository: {
977 pullRequest: {
978 reviewThreads: { totalCount: 0, nodes: [] },
979 reactionGroups: [
980 {
981 content: "HEART",
982 viewerHasReacted: true,
983 reactors: { totalCount: 2, nodes: [{ login: "bilal" }, { login: "julius" }] },
984 },
985 ],
986 },
987 },
988 },
989 }),
990 ),
991 );
992​
993 expect(result.reactions).toEqual([
994 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
995 ]);
996 });
997});
998​
999describe("decodePullRequestNodeIdJson", () => {
1000 it("reads the pull request's own node id, which a reaction on its description is addressed by", () => {
1001 expect(
1002 expectSuccess(
1003 decodePullRequestNodeIdJson(
1004 JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
1005 ),
1006 ),
1007 ).toBe("PR_kwDOA");
1008 });
1009});
1010​
1011describe("REVIEW_THREADS_GRAPHQL_QUERY", () => {
1012 it("asks for reactionGroups on the pull request itself, its comments, its reviews and each thread's comments", () => {
1013 expect(REVIEW_THREADS_GRAPHQL_QUERY.match(/reactionGroups/g)).toHaveLength(4);
1014 // The reviews connection is new: only reactions were ever wanted off it.
1015 expect(REVIEW_THREADS_GRAPHQL_QUERY).toContain("reviews(first:");
1016 });
1017});
1018​
1019describe("reviewer candidate decoding", () => {
1020 const candidatesJson = (input: {
1021 readonly assignable: ReadonlyArray<Record<string, unknown> | null>;
1022 readonly requested?: ReadonlyArray<Record<string, unknown> | null>;
1023 readonly author?: string;
1024 readonly hasNextPage?: boolean;
1025 }) =>
1026 JSON.stringify({
1027 data: {
1028 repository: {
1029 assignableUsers: {
1030 pageInfo: { hasNextPage: input.hasNextPage ?? false },
1031 nodes: input.assignable,
1032 },
1033 pullRequest: {
1034 author: input.author === undefined ? null : { login: input.author },
1035 reviewRequests: {
1036 nodes: (input.requested ?? []).map((requestedReviewer) => ({ requestedReviewer })),
1037 },
1038 },
1039 },
1040 },
1041 });
1042​
1043 it("leaves the author out of the people their own pull request can be sent to", () => {
1044 const list = expectSuccess(
1045 decodeReviewerCandidatesJson(
1046 candidatesJson({
1047 assignable: [{ login: "bilal" }, { login: "octocat", name: "The Octocat" }],
1048 author: "bilal",
1049 }),
1050 ),
1051 );
1052 expect(list.candidates).toEqual([
1054 id: "octocat",
1055 kind: "user",
1056 login: "octocat",
1057 name: "The Octocat",
1058 avatarUrl: null,
1059 isRequested: false,
1060 },
1061 ]);
1062 expect(list.truncated).toBe(false);
1063 });
1064​
1065 it("marks whoever has already been asked, and leaves the rest to be asked", () => {
1066 const list = expectSuccess(
1067 decodeReviewerCandidatesJson(
1068 candidatesJson({
1069 assignable: [{ login: "octocat" }, { login: "hubot" }],
1070 requested: [{ login: "octocat" }],
1071 }),
1072 ),
1073 );
1074 expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([
1075 ["octocat", true],
1076 ["hubot", false],
1077 ]);
1078 });
1079​
1080 it("keeps a requested team apart from the people, so the request can be taken back", () => {
1081 // A team is never among the assignable users, and a request that cannot be seen cannot be
1082 // undone — so the ones GitHub reports are carried, marked as the teams they are.
1083 const list = expectSuccess(
1084 decodeReviewerCandidatesJson(
1085 candidatesJson({
1086 assignable: [{ login: "octocat" }],
1087 requested: [{ slug: "reviewers", name: "Reviewers" }],
1088 }),
1089 ),
1090 );
1091 expect(list.candidates).toEqual([
1093 id: "reviewers",
1094 kind: "team",
1095 login: "reviewers",
1096 name: "Reviewers",
1097 avatarUrl: null,
1098 isRequested: true,
1099 },
1101 id: "octocat",
1102 kind: "user",
1103 login: "octocat",
1104 name: null,
1105 avatarUrl: null,
1106 isRequested: false,
1107 },
1108 ]);
1109 });
1110​
1111 it("says so when the repository has more people than the read asked for", () => {
1112 expect(
1113 expectSuccess(
1114 decodeReviewerCandidatesJson(
1115 candidatesJson({ assignable: [{ login: "octocat" }], hasNextPage: true }),
1116 ),
1117 ).truncated,
1118 ).toBe(true);
1119 });
1120});
1121​
1122describe("reviewer request payload", () => {
1123 it("sends people and teams in the two lists GitHub keeps them in", () => {
1124 expect(
1125 JSON.parse(
1126 buildReviewerRequestJson([
1127 { id: "octocat", kind: "user" },
1128 { id: "reviewers", kind: "team" },
1129 { id: "hubot", kind: "user" },
1130 ]),
1131 ),
1132 ).toEqual({ reviewers: ["octocat", "hubot"], team_reviewers: ["reviewers"] });
1133 });
1134​
1135 it("sends both lists even where one of them is empty, which is what GitHub reads", () => {
1136 expect(JSON.parse(buildReviewerRequestJson([{ id: "octocat", kind: "user" }]))).toEqual({
1137 reviewers: ["octocat"],
1138 team_reviewers: [],
1139 });
1140 });
1141});
1142​
1143describe("review submission payload", () => {
1144 it("sends the verdict, the summary and every line comment in one body", () => {
1145 const payload = JSON.parse(
1146 buildReviewSubmissionJson({
1147 verdict: "request-changes",
1148 body: "Two things.",
1149 comments: [
1150 { path: "src/a.ts", line: 12, side: "right", body: "rename this" },
1151 { path: "src/b.ts", line: 3, side: "left", body: "why remove?" },
1152 ],
1153 }),
1154 ) as Record<string, unknown>;
1155 expect(payload).toEqual({
1156 event: "REQUEST_CHANGES",
1157 body: "Two things.",
1158 comments: [
1159 { path: "src/a.ts", line: 12, side: "RIGHT", body: "rename this" },
1160 { path: "src/b.ts", line: 3, side: "LEFT", body: "why remove?" },
1161 ],
1162 });
1163 });
1164​
1165 it("sends an approval with no words and no comments", () => {
1166 expect(
1167 JSON.parse(buildReviewSubmissionJson({ verdict: "approve", body: "", comments: [] })),
1168 ).toEqual({ event: "APPROVE", body: "", comments: [] });
1169 });
1170});
1171​
1172describe("decodePullRequestFilesJson", () => {
1173 it("assembles a unified patch the files API does not return", () => {
1174 const result = expectSuccess(
1175 decodePullRequestFilesJson(
1176 JSON.stringify([
1177 { filename: "src/app.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" },
1178 ]),
1179 ),
1180 );
1181​
1182 expect(result.patch).toBe(
1184 "diff --git a/src/app.ts b/src/app.ts",
1185 "--- a/src/app.ts",
1186 "+++ b/src/app.ts",
1187 "@@ -1 +1 @@",
1188 "-old",
1189 "+new",
1190 "",
1191 ].join("\n"),
1192 );
1193 expect(result.truncated).toBe(false);
1194 expect(result.rawCount).toBe(1);
1195 });
1196​
1197 it("points an added file at /dev/null on the left and a removed one on the right", () => {
1198 const result = expectSuccess(
1199 decodePullRequestFilesJson(
1200 JSON.stringify([
1201 { filename: "src/new.ts", status: "added", patch: "@@ -0,0 +1 @@\n+hello" },
1202 { filename: "src/gone.ts", status: "removed", patch: "@@ -1 +0,0 @@\n-bye" },
1203 ]),
1204 ),
1205 );
1206​
1207 expect(result.patch).toBe(
1209 "diff --git a/src/new.ts b/src/new.ts",
1210 "new file mode 100644",
1211 "--- /dev/null",
1212 "+++ b/src/new.ts",
1213 "@@ -0,0 +1 @@",
1214 "+hello",
1215 "diff --git a/src/gone.ts b/src/gone.ts",
1216 "deleted file mode 100644",
1217 "--- a/src/gone.ts",
1218 "+++ /dev/null",
1219 "@@ -1 +0,0 @@",
1220 "-bye",
1221 "",
1222 ].join("\n"),
1223 );
1224 });
1225​
1226 it("names both paths of a rename, counting its hunks against the old one", () => {
1227 const result = expectSuccess(
1228 decodePullRequestFilesJson(
1229 JSON.stringify([
1231 filename: "src/new.ts",
1232 status: "renamed",
1233 previous_filename: "src/old.ts",
1234 patch: "@@ -1 +1 @@\n-old\n+new",
1235 },
1236 ]),
1237 ),
1238 );
1239​
1240 expect(result.patch).toBe(
1242 "diff --git a/src/old.ts b/src/new.ts",
1243 "rename from src/old.ts",
1244 "rename to src/new.ts",
1245 "--- a/src/old.ts",
1246 "+++ b/src/new.ts",
1247 "@@ -1 +1 @@",
1248 "-old",
1249 "+new",
1250 "",
1251 ].join("\n"),
1252 );
1253 });
1254​
1255 it("still lists a file GitHub sent no hunks for, and says what was withheld", () => {
1256 const result = expectSuccess(
1257 decodePullRequestFilesJson(
1258 JSON.stringify([
1259 // Binary: it changed, and none of it can be shown.
1260 { filename: "logo.png", status: "modified", additions: 4, deletions: 2 },
1262 filename: "src/app.ts",
1263 status: "modified",
1264 additions: 1,
1265 deletions: 1,
1266 patch: "@@ -1 +1 @@\n-old\n+new",
1267 },
1268 ]),
1269 ),
1270 );
1271​
1272 // Dropping it would take the file out of the change altogether, not just its contents.
1273 expect(result.patch).toContain("diff --git a/logo.png b/logo.png");
1274 expect(result.patch).toContain("diff --git a/src/app.ts b/src/app.ts");
1275 expect(result.truncated).toBe(true);
1276 expect(result.rawCount).toBe(2);
1277 });
1278​
1279 it("does not call a pure rename incomplete, since it has no hunks to withhold", () => {
1280 const result = expectSuccess(
1281 decodePullRequestFilesJson(
1282 JSON.stringify([
1284 filename: "src/new.ts",
1285 previous_filename: "src/old.ts",
1286 status: "renamed",
1287 additions: 0,
1288 deletions: 0,
1289 },
1290 ]),
1291 ),
1292 );
1293​
1294 expect(result.patch).toContain("rename from src/old.ts");
1295 expect(result.truncated).toBe(false);
1296 });
1297});
1298​
1299describe("how far a branch trails its base", () => {
1300 const comparison = (pullRequest: unknown) =>
1301 JSON.stringify({ data: { repository: { pullRequest } } });
1302​
1303 it("reads the commit count and whether this viewer may move the branch", () => {
1304 const decoded = expectSuccess(
1305 decodeBaseComparisonJson(
1306 comparison({ viewerCanUpdateBranch: true, baseRef: { compare: { behindBy: 12 } } }),
1307 ),
1308 );
1309 expect(decoded).toEqual({ behindBy: 12, viewerCanUpdate: true });
1310 });
1311​
1312 it("reads a current branch as nothing to do", () => {
1313 expect(
1314 expectSuccess(
1315 decodeBaseComparisonJson(
1316 comparison({ viewerCanUpdateBranch: false, baseRef: { compare: { behindBy: 0 } } }),
1317 ),
1318 ),
1319 ).toEqual({ behindBy: 0, viewerCanUpdate: false });
1320 });
1321​
1322 it("answers unknown where the head could not be compared", () => {
1323 // A pull request from a fork whose repository is gone, which GitHub answers with a null
1324 // comparison beside a perfectly good pull request.
1325 expect(
1326 expectSuccess(
1327 decodeBaseComparisonJson(comparison({ viewerCanUpdateBranch: true, baseRef: null })),
1328 ).behindBy,
1329 ).toBeNull();
1330 expect(expectSuccess(decodeBaseComparisonJson(comparison(null)))).toEqual({
1331 behindBy: null,
1332 viewerCanUpdate: false,
1333 });
1334 });
1335​
1336 it("refuses a body that is not the answer to this question", () => {
1337 expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
1338 });
1339});