@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,857 lines 58.9 KB
Raw
1 import * as Result from "effect/Result";
2 import * as Schema from "effect/Schema";
3 import { describe, expect, it } from "vite-plus/test";
4
5 import {
6 buildReviewSubmission,
7 buildReviewerRequest,
8 pullRequestLookup,
9 referenceSearchQuery,
10 toRepositoryReferences,
11 toPullRequestWatchFingerprint,
12 decodePullRequestFilesJson,
13 decodePullRequestStacksJson,
14 LenientPullRequestList,
15 reviewThreadConversation,
16 toLabelCandidates,
17 toPullRequestActivityPage,
18 toPullRequestCore,
19 toPullRequestFilesViewedPage,
20 toPullRequestRows,
21 toReviewerCandidates,
22 toReviewThreadCommentsPage,
23 toCanWrite,
24 toReviewThreadPage,
25 toViewerPermissions,
26 } from "./gitHubPullRequestJson.ts";
27 import { PullRequestWatchFingerprint } from "./pullRequestBatches.graphql.ts";
28 import {
29 LabelCandidates,
30 PullRequestActivity,
31 PullRequestCore,
32 PullRequestFilesViewed,
33 ReviewerCandidates,
34 ViewerPermissions,
35 } from "./pullRequestReads.graphql.ts";
36 import { ReviewThreadComments, ReviewThreads } from "./pullRequestReviews.graphql.ts";
37
38 const through =
39 <S extends Schema.Codec<unknown, unknown>, A>(schema: S, map: (result: S["Type"]) => A | null) =>
40 (raw: string): Result.Result<A, unknown> => {
41 const decoded = Schema.decodeUnknownResult(schema)(
42 (JSON.parse(raw) as { readonly data: unknown }).data,
43 );
44 if (Result.isFailure(decoded)) return Result.fail(decoded.failure);
45 const mapped = map(decoded.success);
46 return mapped === null ? Result.fail("not found") : Result.succeed(mapped);
47 };
48
49 const user = (login: string, fields: Record<string, unknown> = {}) => ({
50 __typename: "User",
51 login,
52 ...fields,
53 });
54
55 const row = (fields: Record<string, unknown>) => ({
56 number: 1,
57 title: "Add the pull requests page",
58 url: "https://github.com/pingdotgg/t3code/pull/1",
59 author: null,
60 headRefName: "feat/page",
61 baseRefName: "main",
62 state: "OPEN",
63 isDraft: false,
64 mergeable: "UNKNOWN",
65 reviewDecision: null,
66 latestReviews: { nodes: [] },
67 createdAt: "2026-07-01T00:00:00Z",
68 updatedAt: "2026-07-02T00:00:00Z",
69 mergedAt: null,
70 repository: { nameWithOwner: "pingdotgg/t3code" },
71 reviewRequests: { nodes: [] },
72 labels: { nodes: [] },
73 commits: { nodes: [] },
74 ...fields,
75 });
76
77 const listPage = (page: ReturnType<typeof toPullRequestRows>) => ({
78 items: page.rows.map((row) => ({
79 ...row.item,
80 ...(row.repository === null ? {} : { repository: row.repository }),
81 })),
82 rawCount: page.rawCount,
83 });
84 const decodePullRequestListJson = through(LenientPullRequestList.result, (result) =>
85 listPage(toPullRequestRows(result.repository?.pullRequests)),
86 );
87 const decodePullRequestActivityJson = through(
88 PullRequestActivity.result,
89 toPullRequestActivityPage,
90 );
91 const decodePullRequestCoreJson = through(PullRequestCore.result, toPullRequestCore);
92 type Json = Record<string, any>;
93 const LAST_PAGE = { hasNextPage: false, endCursor: null };
94 const nodesIn = (connection: Json | null | undefined): ReadonlyArray<Json> =>
95 connection?.["nodes"] ?? [];
96 const actor = (raw: Json | null | undefined) =>
97 raw === null || raw === undefined ? null : { __typename: "User", avatarUrl: "", ...raw };
98 const reactionGroups = (groups: ReadonlyArray<Json> | undefined) =>
99 (groups ?? []).map(({ reactors, ...group }) => ({
100 viewerHasReacted: false,
101 ...group,
102 reactors: {
103 totalCount: 0,
104 ...reactors,
105 nodes: nodesIn(reactors).map((node) => ({ __typename: "User", ...node })),
106 },
107 }));
108 const remark = ({ author, reactionGroups: groups, ...raw }: Json) => ({
109 body: "",
110 lastEditedAt: null,
111 isMinimized: false,
112 url: "https://github.com/acme/web/pull/1#discussion",
113 pullRequestReview: null,
114 ...raw,
115 author: actor(author),
116 reactionGroups: reactionGroups(groups),
117 });
118 const threadCommentsOf = ({ nodes, ...connection }: Json) => ({
119 totalCount: (nodes ?? []).length,
120 pageInfo: LAST_PAGE,
121 ...connection,
122 nodes: (nodes ?? []).map(remark),
123 });
124 const requestedReviewer = (raw: Json | null) =>
125 raw === null
126 ? null
127 : "login" in raw
128 ? { name: null, ...actor(raw) }
129 : { __typename: "Team", ...raw };
130 const reviewCommit = ({ commit: { authors, ...commit } }: Json) => ({
131 commit: {
132 messageHeadline: "",
133 committedDate: "",
134 ...commit,
135 authors: {
136 nodes: nodesIn(authors).map((author) => ({
137 name: null,
138 avatarUrl: "",
139 user: null,
140 ...author,
141 })),
142 },
143 },
144 });
145 const withReviewDefaults = (raw: string): string => {
146 const { data } = JSON.parse(raw) as { data: Json };
147 const pr = data["repository"]?.["pullRequest"];
148 if (pr?.["reviewThreads"] !== undefined) {
149 const {
150 reviewThreads,
151 author,
152 reactionGroups: groups,
153 comments,
154 reviews,
155 reviewRequests,
156 latestReviews,
157 commits,
158 ...rest
159 } = pr;
160 data["repository"]["pullRequest"] = {
161 viewerCanUpdate: true,
162 viewerDidAuthor: false,
163 reviewDismissals: { pageInfo: LAST_PAGE, nodes: [] },
164 ...rest,
165 author: actor(author),
166 reactionGroups: reactionGroups(groups),
167 comments: { nodes: nodesIn(comments).map(remark) },
168 reviews: { nodes: nodesIn(reviews).map(remark) },
169 reviewRequests: {
170 nodes: nodesIn(reviewRequests).map((node) => ({
171 requestedReviewer: requestedReviewer(node["requestedReviewer"]),
172 })),
173 },
174 latestReviews: {
175 nodes: nodesIn(latestReviews).map((node) => ({
176 state: "COMMENTED",
177 isMinimized: false,
178 ...node,
179 author: actor(node["author"]),
180 })),
181 },
182 commits: { nodes: nodesIn(commits).map(reviewCommit) },
183 reviewThreads: {
184 totalCount: nodesIn(reviewThreads).length,
185 pageInfo: LAST_PAGE,
186 ...reviewThreads,
187 nodes: nodesIn(reviewThreads).map((thread) => ({
188 isResolved: false,
189 isOutdated: false,
190 line: null,
191 diffSide: "RIGHT",
192 ...thread,
193 comments: threadCommentsOf(thread["comments"]),
194 })),
195 },
196 };
197 }
198 if (data["node"] !== undefined && data["node"] !== null) {
199 data["node"] = {
200 __typename: "PullRequestReviewThread",
201 ...data["node"],
202 comments: threadCommentsOf(data["node"]["comments"]),
203 };
204 }
205 data["viewer"] ??= { login: "viewer" };
206 return JSON.stringify({ data });
207 };
208 const decodeReviewThreadsJson = (raw: string) =>
209 through(ReviewThreads.result, toReviewThreadPage)(withReviewDefaults(raw));
210 const decodeReviewThreadCommentsJson = (raw: string) =>
211 through(ReviewThreadComments.result, toReviewThreadCommentsPage)(withReviewDefaults(raw));
212 const decodeViewerPermissionsJson = through(ViewerPermissions.result, toViewerPermissions);
213 const decodeLabelCandidatesJson = through(LabelCandidates.result, toLabelCandidates);
214 const decodeReviewerCandidatesJson = through(ReviewerCandidates.result, toReviewerCandidates);
215 const decodePullRequestFilesViewedJson = through(
216 PullRequestFilesViewed.result,
217 toPullRequestFilesViewedPage,
218 );
219
220 function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
221 return JSON.stringify({
222 data: {
223 repository: {
224 pullRequests: {
225 pageInfo: { hasNextPage: false, endCursor: null },
226 nodes: entries.map(({ reviewRequests, latestReviews, checks, ...entry }) =>
227 row({
228 ...(reviewRequests === undefined
229 ? {}
230 : {
231 reviewRequests: {
232 nodes: (reviewRequests as ReadonlyArray<unknown>).map(
233 (requestedReviewer) => ({
234 requestedReviewer,
235 }),
236 ),
237 },
238 }),
239 ...(latestReviews === undefined
240 ? {}
241 : {
242 latestReviews: {
243 nodes: (latestReviews as ReadonlyArray<Json>).map((review) => ({
244 isMinimized: false,
245 ...review,
246 })),
247 },
248 }),
249 ...(checks === undefined
250 ? {}
251 : { commits: { nodes: [{ commit: { statusCheckRollup: { state: checks } } }] } }),
252 ...entry,
253 }),
254 ),
255 },
256 },
257 },
258 });
259 }
260
261 function expectSuccess<A>(result: Result.Result<A, unknown>): A {
262 expect(Result.isSuccess(result)).toBe(true);
263 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
264 return result.success;
265 }
266
267 describe("pull request list decoding", () => {
268 it("treats a merge timestamp as merged even when the state still says closed", () => {
269 const [entry] = expectSuccess(
270 decodePullRequestListJson(listJson([{ state: "CLOSED", mergedAt: "2026-07-03T00:00:00Z" }])),
271 ).items;
272 expect(entry?.state).toBe("merged");
273 });
274
275 it("takes the verdict from the latest reviews when GitHub summarizes none, as for a bot's approval", () => {
276 const batch = expectSuccess(
277 decodePullRequestListJson(
278 listJson([
279 {
280 reviewDecision: null,
281 latestReviews: [{ author: user("macroscopeapp"), state: "APPROVED" }],
282 },
283 {
284 reviewDecision: "REVIEW_REQUIRED",
285 latestReviews: [
286 { author: user("octocat"), state: "APPROVED" },
287 { author: user("hubot"), state: "CHANGES_REQUESTED" },
288 ],
289 },
290 {
291 reviewDecision: "APPROVED",
292 latestReviews: [{ author: user("hubot"), state: "CHANGES_REQUESTED" }],
293 },
294 {
295 reviewDecision: null,
296 latestReviews: [{ author: user("octocat"), state: "COMMENTED" }],
297 },
298 {
299 reviewDecision: null,
300 latestReviews: [
301 { author: user("octocat"), state: "APPROVED" },
302 { author: user("drive-by"), state: "CHANGES_REQUESTED", isMinimized: true },
303 ],
304 },
305 ]),
306 ),
307 );
308 expect(batch.items.map((entry) => entry.reviewDecision)).toEqual([
309 "approved",
310 "changes-requested",
311 "approved",
312 null,
313 "approved",
314 ]);
315 });
316
317 it("keeps review required when an approval falls short of the branch's required count", () => {
318 const batch = expectSuccess(
319 decodePullRequestListJson(
320 listJson([
321 {
322 reviewDecision: "REVIEW_REQUIRED",
323 latestReviews: [{ author: user("octocat"), state: "APPROVED" }],
324 },
325 ]),
326 ),
327 );
328 expect(batch.items.map((entry) => entry.reviewDecision)).toEqual(["review-required"]);
329 });
330
331 it("skips malformed entries but still counts them, so paging does not stop early", () => {
332 const batch = expectSuccess(
333 decodePullRequestListJson(listJson([{}, { number: "not-a-number" }])),
334 );
335 expect(batch.items).toHaveLength(1);
336 expect(batch.rawCount).toBe(2);
337 });
338 });
339
340 describe("pull request detail decoding", () => {
341 const check = (fields: Record<string, unknown>) =>
342 fields["__typename"] === "StatusContext"
343 ? {
344 context: "",
345 state: "PENDING",
346 targetUrl: null,
347 createdAt: "2026-07-01T00:00:00Z",
348 description: null,
349 ...fields,
350 }
351 : {
352 __typename: "CheckRun",
353 name: "",
354 status: "COMPLETED",
355 conclusion: null,
356 startedAt: null,
357 completedAt: null,
358 detailsUrl: null,
359 checkSuite: { workflowRun: null },
360 ...fields,
361 };
362 const inWorkflow = ({ workflowName, ...fields }: Record<string, unknown>) =>
363 check({
364 ...fields,
365 checkSuite: { workflowRun: { workflow: { name: workflowName } } },
366 });
367
368 const coreJson = (
369 rollup: ReadonlyArray<Record<string, unknown>>,
370 pullRequest: Record<string, unknown> = {},
371 ) =>
372 JSON.stringify({
373 data: {
374 repository: {
375 mergeCommitAllowed: true,
376 squashMergeAllowed: true,
377 rebaseMergeAllowed: true,
378 autoMergeAllowed: true,
379 viewerPermission: "WRITE",
380 pullRequest: {
381 number: 7,
382 title: "Detail",
383 url: "https://github.com/pingdotgg/t3code/pull/7",
384 body: "Body",
385 state: "OPEN",
386 isDraft: false,
387 mergeable: "MERGEABLE",
388 mergeStateStatus: "BLOCKED",
389 reviewDecision: null,
390 additions: 0,
391 deletions: 0,
392 changedFiles: 0,
393 createdAt: "2026-07-01T00:00:00Z",
394 updatedAt: "2026-07-05T00:00:00Z",
395 mergedAt: null,
396 mergeCommit: null,
397 mergedBy: null,
398 closedAt: null,
399 headRefName: "feat/detail",
400 baseRefName: "main",
401 headRefOid: "abc123",
402 isCrossRepository: false,
403 maintainerCanModify: true,
404 headRepositoryOwner: null,
405 headRepository: null,
406 headRef: null,
407 author: null,
408 autoMergeRequest: null,
409 viewerCanUpdate: true,
410 viewerDidAuthor: false,
411 viewerCanUpdateBranch: false,
412 baseRef: null,
413 reviewRequests: { nodes: [] },
414 labels: { nodes: [] },
415 commits: {
416 nodes: [
417 {
418 commit: {
419 statusCheckRollup: {
420 contexts: {
421 nodes: rollup,
422 pageInfo: { hasNextPage: false, endCursor: null },
423 },
424 },
425 },
426 },
427 ],
428 },
429 ...pullRequest,
430 },
431 },
432 },
433 });
434 const detailOf = (
435 rollup: ReadonlyArray<Record<string, unknown>>,
436 pullRequest?: Record<string, unknown>,
437 ) => expectSuccess(decodePullRequestCoreJson(coreJson(rollup, pullRequest)));
438
439 it.each([
440 [{}, true],
441 [{ viewerDidAuthor: false }, false],
442 [{ isCrossRepository: false }, false],
443 [{ state: "CLOSED" }, false],
444 [{ headRepositoryOwner: { __typename: "Organization", login: "team" } }, false],
445 [{ headRepository: null }, false],
446 ])(
447 "reads maintainer edits and lets only the author of an open personal fork change them: %j",
448 (overrides, allowed) => {
449 const detail = detailOf([], {
450 maintainerCanModify: false,
451 isCrossRepository: true,
452 viewerDidAuthor: true,
453 headRepositoryOwner: { __typename: "User", login: "octocat" },
454 headRepository: { nameWithOwner: "octocat/t3code", viewerPermission: "ADMIN" },
455 headRef: { id: "REF_7" },
456 ...overrides,
457 });
458 expect(detail.maintainerCanModify).toBe(false);
459 expect(detail.canEditMaintainerEdits).toBe(allowed);
460 },
461 );
462
463 const detailJson = JSON.stringify({
464 comments: [{ id: "c1", body: "second", createdAt: "2026-07-04T00:00:00Z" }],
465 reviews: [
466 { id: "r1", body: "first", state: "CHANGES_REQUESTED", submittedAt: "2026-07-03T00:00:00Z" },
467 { id: "r2", body: " ", state: "APPROVED", submittedAt: "2026-07-06T00:00:00Z" },
468 ],
469 commits: [
470 {
471 oid: "abc1234",
472 messageHeadline: "Ship the timeline",
473 committedDate: "2026-07-05T00:00:00Z",
474 authors: [
475 { login: "octocat", name: "Octo Cat", email: "octo@example.com" },
476 { name: "Pair Author", email: "pair@example.com" },
477 ],
478 },
479 ],
480 });
481
482 const activityJson = (raw: Record<string, unknown>) =>
483 JSON.stringify({
484 data: {
485 repository: {
486 pullRequest: {
487 author: null,
488 comments: {
489 pageInfo: { hasNextPage: false, endCursor: null },
490 nodes: ((raw["comments"] ?? []) as ReadonlyArray<Record<string, unknown>>).map(
491 (comment) => ({
492 lastEditedAt: null,
493 url: "https://github.com/c",
494 isMinimized: false,
495 author: null,
496 ...comment,
497 }),
498 ),
499 },
500 reviews: {
501 pageInfo: { hasNextPage: false, endCursor: null },
502 nodes: ((raw["reviews"] ?? []) as ReadonlyArray<Record<string, unknown>>).map(
503 (review) => ({
504 lastEditedAt: null,
505 url: "https://github.com/r",
506 isMinimized: false,
507 author: null,
508 submittedAt: null,
509 ...review,
510 }),
511 ),
512 },
513 commits: {
514 nodes: ((raw["commits"] ?? []) as ReadonlyArray<Record<string, unknown>>).map(
515 ({ authors, ...commit }) => ({
516 commit: {
517 id: "commit-id",
518 parents: { totalCount: 1 },
519 ...commit,
520 authors: {
521 nodes: ((authors ?? []) as ReadonlyArray<Record<string, unknown>>).map(
522 ({ login, ...author }) => ({
523 name: null,
524 email: null,
525 ...author,
526 user: login === undefined ? null : { login },
527 }),
528 ),
529 },
530 },
531 }),
532 ),
533 },
534 },
535 },
536 },
537 });
538 const activity = (raw: Record<string, unknown>) =>
539 Result.map(decodePullRequestActivityJson(activityJson(raw)), (page) => ({
540 comments: page.remarks.toSorted((left, right) =>
541 left.createdAt.localeCompare(right.createdAt),
542 ),
543 commits: page.commits ?? [],
544 }));
545
546 it("keeps a workflow waiting for approval out of the passing state", () => {
547 const detail = detailOf([
548 check({ name: "build", status: "COMPLETED", conclusion: "SUCCESS" }),
549 check({ name: "contributor tests", status: "COMPLETED", conclusion: "ACTION_REQUIRED" }),
550 ]);
551
552 expect(detail.checks.map((check) => check.status)).toEqual(["success", "action-required"]);
553 expect(detail.checksState).toBe("pending");
554 });
555
556 it("reads a merged pull request's merge commit and who merged it", () => {
557 expect(
558 detailOf([], {
559 state: "MERGED",
560 mergedAt: "2026-07-05T00:00:00Z",
561 mergeCommit: { oid: "3b2f958603a51d8c42c4ede02eee7b8cb310b2d9" },
562 mergedBy: {
563 __typename: "User",
564 login: "octocat",
565 avatarUrl: "https://avatars.githubusercontent.com/u/1",
566 name: "Octo Cat",
567 },
568 }),
569 ).toMatchObject({
570 state: "merged",
571 mergeCommitSha: "3b2f958603a51d8c42c4ede02eee7b8cb310b2d9",
572 mergedBy: { login: "octocat", name: "Octo Cat" },
573 });
574 });
575
576 it("reads an auto-merge request and strategy, and its null as off", () => {
577 expect(detailOf([], { autoMergeRequest: { mergeMethod: "SQUASH" } })).toMatchObject({
578 autoMergeEnabled: true,
579 autoMergeMethod: "squash",
580 });
581 expect(detailOf([], { autoMergeRequest: null }).autoMergeEnabled).toBe(false);
582 });
583
584 it("reads the newest merge queue removal, and none where the queue was not asked about", () => {
585 const removal = {
586 __typename: "RemovedFromMergeQueueEvent",
587 id: "RMQE_1",
588 createdAt: "2026-07-05T00:00:00Z",
589 reason: "Required status checks failed",
590 };
591 expect(detailOf([], { mergeQueueRemovals: { nodes: [removal] } }).mergeQueueRemoval).toEqual({
592 id: "RMQE_1",
593 removedAt: "2026-07-05T00:00:00Z",
594 reason: "Required status checks failed",
595 });
596 expect(detailOf([], { mergeQueueRemovals: { nodes: [] } }).mergeQueueRemoval).toBeUndefined();
597 expect(detailOf([]).mergeQueueRemoval).toBeUndefined();
598 });
599
600 it("shows a re-running check once, as the run that is happening now", () => {
601 const detail = detailOf([
602 inWorkflow({
603 name: "Prepare PR size config",
604 workflowName: "PR Size",
605 status: "COMPLETED",
606 conclusion: "SUCCESS",
607 startedAt: "2026-08-11T16:06:20Z",
608 completedAt: "2026-08-11T16:06:25Z",
609 }),
610 inWorkflow({
611 name: "Prepare PR size config",
612 workflowName: "PR Size",
613 status: "IN_PROGRESS",
614 conclusion: null,
615 startedAt: "2026-08-11T17:01:04Z",
616 completedAt: "0001-01-01T00:00:00Z",
617 }),
618 ]);
619
620 expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
621 ["Prepare PR size config", "pending"],
622 ]);
623 expect(detail.checksState).toBe("pending");
624 });
625
626 it("keeps a check pending while another run of it on the same commit is still going", () => {
627 const finished = {
628 name: "check",
629 workflowName: "Checks",
630 status: "COMPLETED",
631 conclusion: "SUCCESS",
632 startedAt: "2026-10-08T04:06:10Z",
633 completedAt: "2026-10-08T04:18:58Z",
634 };
635 const running = {
636 ...finished,
637 status: "IN_PROGRESS",
638 conclusion: null,
639 startedAt: "2026-10-08T04:06:13Z",
640 completedAt: "0001-01-01T00:00:00Z",
641 };
642 const queued = { ...running, status: "QUEUED", startedAt: "0001-01-01T00:00:00Z" };
643 const checksOf = (rollup: ReadonlyArray<Record<string, unknown>>) => {
644 const detail = detailOf(rollup.map(inWorkflow));
645 return [detail.checks.map((check) => [check.name, check.status]), detail.checksState];
646 };
647
648 for (const rollup of [
649 [finished, running],
650 [running, finished],
651 [finished, queued],
652 [queued, finished],
653 ]) {
654 expect(checksOf(rollup)).toEqual([[["check", "pending"]], "pending"]);
655 }
656 });
657
658 it("merges reviews with comments in time order and keeps a bodyless approval", () => {
659 const detail = expectSuccess(activity(JSON.parse(detailJson) as Record<string, unknown>));
660 expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]);
661 expect(detail.comments.at(-1)?.reviewState).toBe("APPROVED");
662 });
663
664 it("drops the bodyless review GitHub opens to hold line comments", () => {
665 const raw = JSON.parse(detailJson) as Record<string, unknown>;
666 const detail = expectSuccess(
667 activity({
668 ...raw,
669 reviews: [
670 { id: "r4", body: "", state: "COMMENTED", submittedAt: "2026-07-07T00:00:00Z" },
671 {
672 id: "r5",
673 body: "Looks good.",
674 state: "COMMENTED",
675 submittedAt: "2026-07-08T00:00:00Z",
676 },
677 ],
678 }),
679 );
680
681 expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "r5"]);
682 });
683
684 it("leaves out the comments and reviews a maintainer hid", () => {
685 const detail = expectSuccess(
686 activity({
687 comments: [
688 { id: "c1", body: "kept", createdAt: "2026-07-04T00:00:00Z" },
689 { id: "c2", body: "spam", createdAt: "2026-07-05T00:00:00Z", isMinimized: true },
690 ],
691 reviews: [
692 {
693 id: "r1",
694 body: "spam",
695 state: "CHANGES_REQUESTED",
696 submittedAt: "2026-07-03T00:00:00Z",
697 isMinimized: true,
698 },
699 { id: "r2", body: "", state: "APPROVED", submittedAt: "2026-07-06T00:00:00Z" },
700 ],
701 }),
702 );
703
704 expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "r2"]);
705 });
706
707 it.each(["APPROVED", "CHANGES_REQUESTED", "DISMISSED"])(
708 "keeps a bodyless %s review, which is the event itself",
709 (state) => {
710 const raw = JSON.parse(detailJson) as Record<string, unknown>;
711 const detail = expectSuccess(
712 activity({
713 ...raw,
714 reviews: [{ id: "r6", body: "", state, submittedAt: "2026-07-07T00:00:00Z" }],
715 }),
716 );
717
718 expect(detail.comments.map((comment) => comment.id)).toContain("r6");
719 },
720 );
721 });
722
723 describe("review thread decoding", () => {
724 const threadsJson = (
725 nodes: ReadonlyArray<Record<string, unknown>>,
726 totalCount = nodes.length,
727 pageInfo: Record<string, unknown> = { hasNextPage: false, endCursor: null },
728 ): string =>
729 JSON.stringify({
730 data: { repository: { pullRequest: { reviewThreads: { totalCount, pageInfo, nodes } } } },
731 });
732
733 const reviewJson = (input: {
734 readonly requested?: ReadonlyArray<unknown>;
735 readonly reviewed?: ReadonlyArray<unknown>;
736 }): string =>
737 JSON.stringify({
738 data: {
739 repository: {
740 pullRequest: {
741 reviewThreads: { totalCount: 0, nodes: [] },
742 reviewRequests: {
743 nodes: (input.requested ?? []).map((r) => ({ requestedReviewer: r })),
744 },
745 latestReviews: { nodes: (input.reviewed ?? []).map((a) => ({ author: a })) },
746 },
747 },
748 },
749 });
750
751 it("selects stats only for non-merge activity commits", () => {
752 const result = expectSuccess(
753 decodePullRequestActivityJson(
754 JSON.stringify({
755 data: {
756 repository: {
757 pullRequest: {
758 author: null,
759 comments: { nodes: [], pageInfo: LAST_PAGE },
760 reviews: { nodes: [], pageInfo: LAST_PAGE },
761 commits: {
762 nodes: [1, 2].map((parents) => ({
763 commit: {
764 id: "commit-" + parents,
765 oid: "sha-" + parents,
766 messageHeadline: "Commit",
767 committedDate: "2026-07-05T00:00:00Z",
768 parents: { totalCount: parents },
769 authors: { nodes: [] },
770 },
771 })),
772 },
773 },
774 },
775 },
776 }),
777 ),
778 );
779 expect(result.nonMergeCommitIds).toEqual(["commit-1"]);
780 expect(result.commits?.map((commit) => commit.oid)).toEqual(["sha-1", "sha-2"]);
781 });
782
783 it("decodes the newest commits off the same connection, oldest to newest", () => {
784 const result = expectSuccess(
785 decodeReviewThreadsJson(
786 JSON.stringify({
787 data: {
788 repository: {
789 pullRequest: {
790 reviewThreads: { totalCount: 0, nodes: [] },
791 commits: {
792 nodes: [
793 {
794 commit: {
795 oid: "abc123",
796 messageHeadline: "Ship the timeline",
797 committedDate: "2026-07-05T00:00:00Z",
798 additions: 18,
799 deletions: 7,
800 authors: { nodes: [{ name: "Julius", user: { login: "julius" } }] },
801 },
802 },
803 {
804 commit: {
805 oid: "def456",
806 messageHeadline: "Fix the flaky test",
807 committedDate: "2026-07-06T00:00:00Z",
808 },
809 },
810 ],
811 },
812 },
813 },
814 },
815 }),
816 ),
817 );
818
819 expect(result.commits).toEqual([
820 {
821 oid: "abc123",
822 messageHeadline: "Ship the timeline",
823 committedDate: "2026-07-05T00:00:00Z",
824 authors: [{ login: "julius", name: "Julius", avatarUrl: null }],
825 },
826 {
827 oid: "def456",
828 messageHeadline: "Fix the flaky test",
829 committedDate: "2026-07-06T00:00:00Z",
830 authors: [],
831 },
832 ]);
833 });
834
835 it("lists someone who was asked and then answered only once", () => {
836 const result = expectSuccess(
837 decodeReviewThreadsJson(
838 reviewJson({
839 requested: [{ login: "julius", avatarUrl: "https://avatars/j.png" }],
840 reviewed: [{ login: "julius", avatarUrl: "https://avatars/j.png" }],
841 }),
842 ),
843 );
844
845 expect(result.reviewers).toHaveLength(1);
846 });
847
848 it("lists a requested team by org/slug, apart from a user who shares its slug", () => {
849 const result = expectSuccess(
850 decodeReviewThreadsJson(
851 reviewJson({
852 requested: [
853 {
854 combinedSlug: "pingdotgg/ping-devs",
855 teamName: "Ping Devs",
856 teamAvatarUrl: "https://avatars.githubusercontent.com/t/6692390?s=400&v=4",
857 },
858 ],
859 reviewed: [
860 { __typename: "User", login: "ping-devs", avatarUrl: "https://avatars/u.png" },
861 ],
862 }),
863 ),
864 );
865
866 expect(result.reviewers).toEqual([
867 {
868 login: "pingdotgg/ping-devs",
869 name: "Ping Devs",
870 avatarUrl: "https://avatars.githubusercontent.com/t/6692390?s=400&v=4",
871 },
872 { login: "ping-devs", name: null, avatarUrl: "https://avatars/u.png" },
873 ]);
874 });
875
876 it("keeps the conversation when a reviewer has neither a login nor a team slug", () => {
877 // Unselected GraphQL union members return no selected fields.
878 const result = expectSuccess(
879 decodeReviewThreadsJson(
880 reviewJson({
881 requested: [
882 { __typename: "Mannequin" },
883 { login: "julius", avatarUrl: "https://avatars/j.png" },
884 ],
885 }),
886 ),
887 );
888
889 expect(result.reviewers).toEqual([
890 { login: "julius", name: null, avatarUrl: "https://avatars/j.png" },
891 ]);
892 });
893
894 it("carries a resolved thread into the conversation, which was still said", () => {
895 const result = expectSuccess(
896 decodeReviewThreadsJson(
897 threadsJson([
898 {
899 id: "PRRT_a",
900 isResolved: false,
901 path: "apps/server/src/ws.ts",
902 comments: {
903 nodes: [{ id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" }],
904 },
905 },
906 {
907 id: "PRRT_b",
908 isResolved: true,
909 path: "apps/web/src/main.tsx",
910 comments: { nodes: [{ id: "t2", body: "done", createdAt: "2026-07-01T00:00:00Z" }] },
911 },
912 ]),
913 ),
914 );
915 const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
916 expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
917 expect(comments[0]).toMatchObject({
918 id: "t1",
919 kind: "review-comment",
920 path: "apps/server/src/ws.ts",
921 });
922 });
923
924 it("carries every reply, not only the remark each thread opened with", () => {
925 const result = expectSuccess(
926 decodeReviewThreadsJson(
927 threadsJson([
928 {
929 id: "PRRT_c",
930 isResolved: false,
931 path: "apps/server/src/ws.ts",
932 comments: {
933 nodes: [
934 { id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" },
935 {
936 id: "t2",
937 body: "fixed",
938 createdAt: "2026-07-01T01:00:00Z",
939 pullRequestReview: {
940 url: "https://github.com/acme/web/pull/1#pullrequestreview-9",
941 },
942 },
943 ],
944 },
945 },
946 ]),
947 ),
948 );
949 const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
950 expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
951 // A reply-only review has no text of its own; its link finds it through the reply it posted.
952 expect(result.threads[0]?.thread.comments.map((comment) => comment.reviewUrl)).toEqual([
953 undefined,
954 "https://github.com/acme/web/pull/1#pullrequestreview-9",
955 ]);
956 });
957
958 it("leaves out hidden thread comments, and a thread with none left", () => {
959 const result = expectSuccess(
960 decodeReviewThreadsJson(
961 threadsJson([
962 {
963 id: "PRRT_hidden_root",
964 path: "apps/server/src/ws.ts",
965 comments: {
966 nodes: [
967 { id: "t1", createdAt: "2026-07-01T00:00:00Z", isMinimized: true },
968 { id: "t2", createdAt: "2026-07-01T01:00:00Z" },
969 ],
970 },
971 },
972 {
973 id: "PRRT_all_hidden",
974 path: "apps/web/src/main.tsx",
975 comments: {
976 nodes: [{ id: "t3", createdAt: "2026-07-01T00:00:00Z", isMinimized: true }],
977 },
978 },
979 ]),
980 ),
981 );
982
983 expect(result.threads.map((entry) => [entry.thread.id, entry.commentCount])).toEqual([
984 ["PRRT_hidden_root", 1],
985 ]);
986 expect(result.threads[0]?.thread.comments.map((comment) => comment.id)).toEqual(["t2"]);
987 });
988
989 it("keeps GitHub's own count of a thread whose comments were not all read", () => {
990 const result = expectSuccess(
991 decodeReviewThreadsJson(
992 threadsJson([
993 {
994 id: "PRRT_e",
995 path: "apps/server/src/ws.ts",
996 isResolved: false,
997 comments: {
998 totalCount: 140,
999 pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjI" },
1000 nodes: [{ id: "t1", createdAt: "2026-07-01T00:00:00Z" }],
1001 },
1002 },
1003 ]),
1004 ),
1005 );
1006 expect(result.threads[0]).toMatchObject({
1007 commentCount: 140,
1008 nextCommentCursor: "Y3Vyc29yOjI",
1009 });
1010 });
1011
1012 it("ends a thread's walk on the last page, which still names a cursor, counting what it hid", () => {
1013 const decoded = expectSuccess(
1014 decodeReviewThreadCommentsJson(
1015 JSON.stringify({
1016 data: {
1017 repository: { pullRequest: { id: "PR_1" } },
1018 node: {
1019 pullRequest: { id: "PR_1" },
1020 comments: {
1021 pageInfo: { hasNextPage: false, endCursor: "Y3Vyc29yOjk" },
1022 nodes: [
1023 { id: "t8", body: "spam", createdAt: "2026-07-01T00:00:00Z", isMinimized: true },
1024 { id: "t9", body: "last", createdAt: "2026-07-01T00:00:00Z" },
1025 ],
1026 },
1027 },
1028 },
1029 }),
1030 ),
1031 );
1032 expect(decoded.comments.map((comment) => comment.id)).toEqual(["t9"]);
1033 expect(decoded.hiddenCount).toBe(1);
1034 expect(decoded.nextCursor).toBeNull();
1035 });
1036 });
1037
1038 describe("reaction decoding", () => {
1039 const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>
1040 JSON.stringify({
1041 data: {
1042 repository: { pullRequest: { id: "PR_1" } },
1043 node: {
1044 pullRequest: { id: "PR_1" },
1045 comments: {
1046 pageInfo: { hasNextPage: false, endCursor: null },
1047 nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],
1048 },
1049 },
1050 },
1051 });
1052
1053 it("keeps a named group, widens a group whose reactors were cut short, drops an unknown content and an empty group", () => {
1054 const decoded = expectSuccess(
1055 decodeReviewThreadCommentsJson(
1056 commentWithGroups([
1057 {
1058 content: "THUMBS_UP",
1059 viewerHasReacted: true,
1060 reactors: { totalCount: 2, nodes: [{ login: "julius" }, { login: "bilal" }] },
1061 },
1062 {
1063 content: "PARTY_PARROT",
1064 reactors: { totalCount: 1, nodes: [{ login: "hubot" }] },
1065 },
1066 { content: "HEART", reactors: { totalCount: 0, nodes: [] } },
1067 {
1068 content: "ROCKET",
1069 reactors: { totalCount: 140, nodes: [{ login: "a" }, { login: "b" }, { login: "c" }] },
1070 },
1071 ]),
1072 ),
1073 );
1074
1075 expect(decoded.comments[0]?.reactions).toEqual([
1076 { content: "thumbs-up", count: 2, actors: ["julius", "bilal"], viewerHasReacted: true },
1077 { content: "rocket", count: 140, actors: ["a", "b", "c"], viewerHasReacted: false },
1078 ]);
1079 });
1080 });
1081
1082 describe("repository access decoding", () => {
1083 const repositoryJson = (viewerPermission?: string | null) =>
1084 JSON.stringify({
1085 data: {
1086 repository: {
1087 pullRequest: null,
1088 mergeCommitAllowed: true,
1089 squashMergeAllowed: false,
1090 rebaseMergeAllowed: true,
1091 autoMergeAllowed: true,
1092 viewerPermission: viewerPermission ?? null,
1093 },
1094 },
1095 });
1096
1097 it("fails rather than defaulting open when a setting is missing", () => {
1098 const decoded = decodeViewerPermissionsJson(
1099 JSON.stringify({ data: { repository: { pullRequest: null, mergeCommitAllowed: true } } }),
1100 );
1101 expect(Result.isSuccess(decoded)).toBe(false);
1102 });
1103
1104 it("counts the roles that can push as write, and the ones that cannot as read", () => {
1105 for (const permission of ["ADMIN", "MAINTAIN", "WRITE"]) {
1106 expect(expectSuccess(decodeViewerPermissionsJson(repositoryJson(permission))).canWrite).toBe(
1107 true,
1108 );
1109 }
1110 for (const permission of ["TRIAGE", "READ", "NONE"]) {
1111 expect(expectSuccess(decodeViewerPermissionsJson(repositoryJson(permission))).canWrite).toBe(
1112 false,
1113 );
1114 }
1115 });
1116
1117 it("withholds write where gh names no permission, which is not a standing it gave", () => {
1118 expect(toCanWrite(undefined)).toBe(false);
1119 });
1120
1121 it("grants write and triage to a GitHub App, which GitHub answers with a null permission", () => {
1122 const access = expectSuccess(decodeViewerPermissionsJson(repositoryJson(null)));
1123 expect(access.canWrite).toBe(true);
1124 expect(access.canTriage).toBe(true);
1125 });
1126 });
1127
1128 describe("viewer permission decoding", () => {
1129 const viewerJson = (repository: Record<string, unknown>) =>
1130 JSON.stringify({
1131 data: {
1132 repository: {
1133 mergeCommitAllowed: true,
1134 squashMergeAllowed: false,
1135 rebaseMergeAllowed: true,
1136 autoMergeAllowed: true,
1137 ...repository,
1138 },
1139 },
1140 });
1141
1142 it("says no to a passer-by on a repository they can only read", () => {
1143 expect(
1144 expectSuccess(
1145 decodeViewerPermissionsJson(
1146 viewerJson({
1147 viewerPermission: "READ",
1148 pullRequest: { viewerCanUpdate: false, viewerDidAuthor: false, headRepository: null },
1149 }),
1150 ),
1151 ),
1152 ).toEqual({
1153 mergeCapabilities: { merge: true, squash: false, rebase: true },
1154 autoMergeAllowed: true,
1155 canWrite: false,
1156 canTriage: false,
1157 canUpdate: false,
1158 didAuthor: false,
1159 canDeleteBranch: false,
1160 });
1161 });
1162
1163 it("reads silence as permission, but not as authorship", () => {
1164 expect(
1165 expectSuccess(
1166 decodeViewerPermissionsJson(viewerJson({ viewerPermission: "READ", pullRequest: null })),
1167 ),
1168 ).toEqual({
1169 mergeCapabilities: { merge: true, squash: false, rebase: true },
1170 autoMergeAllowed: true,
1171 canWrite: false,
1172 canTriage: false,
1173 canUpdate: true,
1174 didAuthor: false,
1175 canDeleteBranch: false,
1176 });
1177 });
1178 });
1179
1180 describe("label candidate decoding", () => {
1181 const labelsJson = (input: {
1182 readonly defined: ReadonlyArray<Record<string, unknown>>;
1183 readonly applied?: ReadonlyArray<string>;
1184 readonly hasNextPage?: boolean;
1185 }) =>
1186 JSON.stringify({
1187 data: {
1188 repository: {
1189 labels: {
1190 pageInfo: { hasNextPage: input.hasNextPage ?? false },
1191 nodes: input.defined,
1192 },
1193 pullRequest: { labels: { nodes: (input.applied ?? []).map((name) => ({ name })) } },
1194 },
1195 },
1196 });
1197
1198 it("keeps a worn label the repository no longer defines, so it can be taken off", () => {
1199 const list = expectSuccess(
1200 decodeLabelCandidatesJson(
1201 labelsJson({
1202 defined: [{ name: "bug", color: "d73a4a", description: null }],
1203 applied: ["legacy"],
1204 }),
1205 ),
1206 );
1207 expect(list.candidates.map((label) => [label.name, label.isApplied])).toEqual([
1208 ["legacy", true],
1209 ["bug", false],
1210 ]);
1211 });
1212 });
1213
1214 describe("review thread decoding", () => {
1215 const threadsJson = (
1216 nodes: ReadonlyArray<Record<string, unknown>>,
1217 pullRequest: Record<string, unknown> = {},
1218 ) =>
1219 JSON.stringify({
1220 data: {
1221 repository: {
1222 pullRequest: {
1223 reviewThreads: { totalCount: nodes.length, nodes },
1224 author: null,
1225 comments: { nodes: [] },
1226 reviewRequests: { nodes: [] },
1227 latestReviews: { nodes: [] },
1228 ...pullRequest,
1229 },
1230 },
1231 },
1232 });
1233
1234 it("carries what the reader may do with the pull request, off the conversation read", () => {
1235 expect(
1236 expectSuccess(
1237 decodeReviewThreadsJson(
1238 threadsJson([], { viewerCanUpdate: false, viewerDidAuthor: false }),
1239 ),
1240 ).viewer,
1241 ).toEqual({ canUpdate: false, didAuthor: false });
1242 expect(expectSuccess(decodeReviewThreadsJson(threadsJson([]))).viewer).toEqual({
1243 canUpdate: true,
1244 didAuthor: false,
1245 });
1246 });
1247
1248 const comment = (id: string, body: string) => ({
1249 id,
1250 author: { login: "bilal", avatarUrl: "https://avatars/b.png" },
1251 body,
1252 createdAt: "2026-07-01T00:00:00Z",
1253 url: `https://github.com/acme/web/pull/1#discussion_r${id}`,
1254 });
1255
1256 it("anchors a thread to its line and side, keeping the whole conversation", () => {
1257 const reviewThreads = expectSuccess(
1258 decodeReviewThreadsJson(
1259 threadsJson([
1260 {
1261 id: "PRRT_1",
1262 isResolved: false,
1263 isOutdated: false,
1264 path: "src/a.ts",
1265 line: 42,
1266 diffSide: "LEFT",
1267 comments: {
1268 totalCount: 2,
1269 nodes: [
1270 { ...comment("c1", "first"), lastEditedAt: "2026-07-02T00:00:00Z" },
1271 comment("c2", "second"),
1272 ],
1273 },
1274 },
1275 ]),
1276 ),
1277 );
1278 expect(reviewThreads.threads.map((entry) => entry.thread)).toEqual([
1279 {
1280 id: "PRRT_1",
1281 path: "src/a.ts",
1282 line: 42,
1283 side: "left",
1284 isResolved: false,
1285 isOutdated: false,
1286 comments: [
1287 {
1288 id: "c1",
1289 author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
1290 body: "first",
1291 createdAt: "2026-07-01T00:00:00Z",
1292 editedAt: "2026-07-02T00:00:00Z",
1293 url: "https://github.com/acme/web/pull/1#discussion_rc1",
1294 reactions: [],
1295 },
1296 {
1297 id: "c2",
1298 author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
1299 body: "second",
1300 createdAt: "2026-07-01T00:00:00Z",
1301 editedAt: null,
1302 url: "https://github.com/acme/web/pull/1#discussion_rc2",
1303 reactions: [],
1304 },
1305 ],
1306 },
1307 ]);
1308 expect(
1309 reviewThreadConversation(reviewThreads.threads.map((entry) => entry.thread))[0]?.editedAt,
1310 ).toBe("2026-07-02T00:00:00Z");
1311 });
1312
1313 it("leaves an outdated thread without a line rather than pinning it to a stale one", () => {
1314 const reviewThreads = expectSuccess(
1315 decodeReviewThreadsJson(
1316 threadsJson([
1317 {
1318 id: "PRRT_2",
1319 isResolved: true,
1320 isOutdated: true,
1321 path: "src/a.ts",
1322 line: null,
1323 diffSide: "RIGHT",
1324 comments: { totalCount: 1, nodes: [comment("c3", "stale")] },
1325 },
1326 ]),
1327 ),
1328 );
1329 expect(reviewThreads.threads[0]?.thread).toMatchObject({
1330 line: null,
1331 isOutdated: true,
1332 isResolved: true,
1333 });
1334 });
1335
1336 it("reads edit times for issue comments and reviews without using reaction updates", () => {
1337 const editedAt = "2026-10-02T12:06:00Z";
1338 const result = expectSuccess(
1339 decodeReviewThreadsJson(
1340 threadsJson([], {
1341 comments: {
1342 nodes: [
1343 { id: "edited", lastEditedAt: editedAt },
1344 { id: "reaction-only", lastEditedAt: null, updatedAt: editedAt },
1345 ],
1346 },
1347 reviews: { nodes: [{ id: "review", lastEditedAt: editedAt }] },
1348 }),
1349 ),
1350 );
1351 expect([...result.editedAtById]).toEqual([
1352 ["edited", editedAt],
1353 ["review", editedAt],
1354 ]);
1355 });
1356
1357 it("leaves the viewer's own login out of the pull request's own reactions, matched case-insensitively, while count still counts them", () => {
1358 const result = expectSuccess(
1359 decodeReviewThreadsJson(
1360 JSON.stringify({
1361 data: {
1362 viewer: { login: "Bilal" },
1363 repository: {
1364 pullRequest: {
1365 reviewThreads: { totalCount: 0, nodes: [] },
1366 reactionGroups: [
1367 {
1368 content: "HEART",
1369 viewerHasReacted: true,
1370 reactors: { totalCount: 2, nodes: [{ login: "bilal" }, { login: "julius" }] },
1371 },
1372 ],
1373 },
1374 },
1375 },
1376 }),
1377 ),
1378 );
1379
1380 expect(result.reactions).toEqual([
1381 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
1382 ]);
1383 });
1384 });
1385
1386 describe("ReviewThreads", () => {
1387 it("caps the initial query after the 104-point rate-limit regression", () => {
1388 const match = ReviewThreads.document.match(
1389 /reviewThreads\(first:(\d+)[\s\S]*?\.\.\.ThreadComment[\s\S]*$/u,
1390 );
1391 const comments = ReviewThreads.document.match(/comments\(first:(\d+)\)\{totalCount/u);
1392
1393 expect(match).not.toBeNull();
1394 expect(comments).not.toBeNull();
1395 if (match === null || comments === null) throw new Error("expected review-thread connections");
1396 expect(Number(match[1]) * Number(comments[1])).toBeLessThanOrEqual(1_000);
1397 });
1398 });
1399
1400 describe("reviewer candidate decoding", () => {
1401 const candidatesJson = (input: {
1402 readonly assignable: ReadonlyArray<Record<string, unknown> | null>;
1403 readonly requested?: ReadonlyArray<Record<string, unknown> | null>;
1404 readonly author?: string;
1405 readonly hasNextPage?: boolean;
1406 }) =>
1407 JSON.stringify({
1408 data: {
1409 repository: {
1410 assignableUsers: {
1411 pageInfo: { hasNextPage: input.hasNextPage ?? false },
1412 nodes: input.assignable.map((node) =>
1413 node === null ? null : { name: null, avatarUrl: "", ...node },
1414 ),
1415 },
1416 pullRequest: {
1417 author: input.author === undefined ? null : { __typename: "User", login: input.author },
1418 reviewRequests: {
1419 nodes: (input.requested ?? []).map((requestedReviewer) => ({
1420 requestedReviewer:
1421 requestedReviewer === null
1422 ? null
1423 : "slug" in requestedReviewer
1424 ? {
1425 __typename: "Team",
1426 teamAvatarUrl: null,
1427 ...requestedReviewer,
1428 }
1429 : { __typename: "User", name: null, avatarUrl: "", ...requestedReviewer },
1430 })),
1431 },
1432 },
1433 },
1434 },
1435 });
1436
1437 it("leaves the author out of the people their own pull request can be sent to", () => {
1438 const list = expectSuccess(
1439 decodeReviewerCandidatesJson(
1440 candidatesJson({
1441 assignable: [{ login: "bilal" }, { login: "octocat", name: "The Octocat" }],
1442 author: "bilal",
1443 }),
1444 ),
1445 );
1446 expect(list.candidates).toEqual([
1447 {
1448 id: "octocat",
1449 kind: "user",
1450 login: "octocat",
1451 name: "The Octocat",
1452 avatarUrl: null,
1453 isRequested: false,
1454 },
1455 ]);
1456 expect(list.truncated).toBe(false);
1457 });
1458
1459 it("keeps a requested team apart from the people, so the request can be taken back", () => {
1460 const list = expectSuccess(
1461 decodeReviewerCandidatesJson(
1462 candidatesJson({
1463 assignable: [{ login: "octocat" }],
1464 requested: [{ slug: "reviewers", combinedSlug: "acme/reviewers", teamName: "Reviewers" }],
1465 }),
1466 ),
1467 );
1468 expect(list.candidates).toEqual([
1469 {
1470 id: "reviewers",
1471 kind: "team",
1472 login: "acme/reviewers",
1473 name: "Reviewers",
1474 avatarUrl: null,
1475 isRequested: true,
1476 },
1477 {
1478 id: "octocat",
1479 kind: "user",
1480 login: "octocat",
1481 name: null,
1482 avatarUrl: null,
1483 isRequested: false,
1484 },
1485 ]);
1486 });
1487 });
1488
1489 describe("reviewer request payload", () => {
1490 it("sends people and teams in the two lists GitHub keeps them in", () => {
1491 expect(
1492 buildReviewerRequest([
1493 { id: "octocat", kind: "user" },
1494 { id: "reviewers", kind: "team" },
1495 { id: "hubot", kind: "user" },
1496 ]),
1497 ).toEqual({ reviewers: ["octocat", "hubot"], team_reviewers: ["reviewers"] });
1498 });
1499 });
1500
1501 describe("review submission payload", () => {
1502 it("sends the verdict, the summary and every line comment in one body", () => {
1503 const payload = buildReviewSubmission({
1504 verdict: "request-changes",
1505 body: "Two things.",
1506 comments: [
1507 {
1508 path: "src/a.ts",
1509 position: { kind: "added", newLine: 12 },
1510 body: "rename this",
1511 },
1512 {
1513 path: "src/b.ts",
1514 position: { kind: "deleted", oldLine: 3 },
1515 body: "why remove?",
1516 },
1517 ],
1518 });
1519 expect(payload).toEqual({
1520 event: "REQUEST_CHANGES",
1521 body: "Two things.",
1522 comments: [
1523 { path: "src/a.ts", line: 12, side: "RIGHT", body: "rename this" },
1524 { path: "src/b.ts", line: 3, side: "LEFT", body: "why remove?" },
1525 ],
1526 });
1527 });
1528
1529 it("sends a range from its first line, and a one-line range as one line", () => {
1530 const payload = buildReviewSubmission({
1531 verdict: "comment",
1532 body: "",
1533 comments: [
1534 {
1535 path: "src/a.ts",
1536 startPosition: { kind: "context", oldLine: 4, newLine: 5, side: "right" },
1537 position: { kind: "added", newLine: 9 },
1538 body: "this block",
1539 },
1540 {
1541 path: "src/b.ts",
1542 startPosition: { kind: "added", newLine: 2 },
1543 position: { kind: "added", newLine: 2 },
1544 body: "this line",
1545 },
1546 ],
1547 });
1548 expect(payload.comments).toEqual([
1549 {
1550 path: "src/a.ts",
1551 start_line: 5,
1552 start_side: "RIGHT",
1553 line: 9,
1554 side: "RIGHT",
1555 body: "this block",
1556 },
1557 { path: "src/b.ts", line: 2, side: "RIGHT", body: "this line" },
1558 ]);
1559 });
1560 });
1561
1562 describe("decodePullRequestFilesJson", () => {
1563 it("preserves spaces and literal backslashes in both rename paths", () => {
1564 const result = expectSuccess(
1565 decodePullRequestFilesJson(
1566 JSON.stringify([
1567 {
1568 previous_filename: String.raw` old\name.ts `,
1569 filename: String.raw` new\name.ts `,
1570 status: "renamed",
1571 },
1572 ]),
1573 ),
1574 );
1575
1576 expect(result.patch).toBe(
1577 [
1578 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
1579 "similarity index 100%",
1580 String.raw`rename from " old\\name.ts "`,
1581 String.raw`rename to " new\\name.ts "`,
1582 String.raw`--- "a/ old\\name.ts "`,
1583 String.raw`+++ "b/ new\\name.ts "`,
1584 "",
1585 ].join("\n"),
1586 );
1587 });
1588
1589 it("points an added file at /dev/null on the left and a removed one on the right", () => {
1590 const result = expectSuccess(
1591 decodePullRequestFilesJson(
1592 JSON.stringify([
1593 { filename: "src/new.ts", status: "added", patch: "@@ -0,0 +1 @@\n+hello" },
1594 { filename: "src/gone.ts", status: "removed", patch: "@@ -1 +0,0 @@\n-bye" },
1595 ]),
1596 ),
1597 );
1598
1599 expect(result.patch).toBe(
1600 [
1601 "diff --git a/src/new.ts b/src/new.ts",
1602 "new file mode 100644",
1603 "--- /dev/null",
1604 "+++ b/src/new.ts",
1605 "@@ -0,0 +1 @@",
1606 "+hello",
1607 "diff --git a/src/gone.ts b/src/gone.ts",
1608 "deleted file mode 100644",
1609 "--- a/src/gone.ts",
1610 "+++ /dev/null",
1611 "@@ -1 +0,0 @@",
1612 "-bye",
1613 "",
1614 ].join("\n"),
1615 );
1616 });
1617
1618 it("names both paths of a rename, counting its hunks against the old one", () => {
1619 const result = expectSuccess(
1620 decodePullRequestFilesJson(
1621 JSON.stringify([
1622 {
1623 filename: "src/new.ts",
1624 status: "renamed",
1625 previous_filename: "src/old.ts",
1626 patch: "@@ -1 +1 @@\n-old\n+new",
1627 },
1628 ]),
1629 ),
1630 );
1631
1632 expect(result.patch).toBe(
1633 [
1634 "diff --git a/src/old.ts b/src/new.ts",
1635 "similarity index 0%",
1636 "rename from src/old.ts",
1637 "rename to src/new.ts",
1638 "--- a/src/old.ts",
1639 "+++ b/src/new.ts",
1640 "@@ -1 +1 @@",
1641 "-old",
1642 "+new",
1643 "",
1644 ].join("\n"),
1645 );
1646 });
1647
1648 it("still lists a file GitHub sent no hunks for, and says what was withheld", () => {
1649 const result = expectSuccess(
1650 decodePullRequestFilesJson(
1651 JSON.stringify([
1652 { filename: "logo.png", status: "modified", additions: 4, deletions: 2 },
1653 {
1654 filename: "src/app.ts",
1655 status: "modified",
1656 additions: 1,
1657 deletions: 1,
1658 patch: "@@ -1 +1 @@\n-old\n+new",
1659 },
1660 ]),
1661 ),
1662 );
1663
1664 expect(result.patch).toContain("diff --git a/logo.png b/logo.png");
1665 expect(result.patch).toContain("diff --git a/src/app.ts b/src/app.ts");
1666 expect(result.truncated).toBe(true);
1667 expect(result.rawCount).toBe(2);
1668 });
1669 });
1670
1671 describe("decodePullRequestFilesViewedJson", () => {
1672 const page = (
1673 nodes: ReadonlyArray<unknown>,
1674 pageInfo: { hasNextPage: boolean; endCursor: string | null },
1675 ) =>
1676 JSON.stringify({
1677 data: { repository: { pullRequest: { files: { pageInfo, nodes } } } },
1678 });
1679
1680 it("treats a state it has never heard of as unread rather than failing the page", () => {
1681 const decoded = decodePullRequestFilesViewedJson(
1682 page([{ path: "src/a.ts", viewerViewedState: "SOMETHING_NEW" }], {
1683 hasNextPage: false,
1684 endCursor: null,
1685 }),
1686 );
1687 expect(Result.isSuccess(decoded)).toBe(true);
1688 if (!Result.isSuccess(decoded)) return;
1689 expect(decoded.success).toEqual({
1690 files: [{ path: "src/a.ts", state: "unviewed" }],
1691 nextCursor: null,
1692 });
1693 });
1694 });
1695
1696 describe("host-native stack decoding", () => {
1697 function stack(overrides: Record<string, unknown> = {}) {
1698 return {
1699 id: 42,
1700 number: 3,
1701 node_id: "STK_kwDO",
1702 url: "https://api.github.com/repos/acme/web/stacks/3",
1703 base: { ref: "main", sha: "abc" },
1704 open: true,
1705 created_at: "2026-09-01T00:00:00Z",
1706 pull_requests: [
1707 {
1708 number: 10,
1709 head: { ref: "feat/one" },
1710 state: "closed",
1711 merged_at: "2026-09-02T00:00:00Z",
1712 },
1713 { number: 11, head: { ref: "feat/two" }, state: "open", merged_at: null },
1714 { number: 12, head: { ref: "feat/three" }, state: "closed", merged_at: null },
1715 ],
1716 ...overrides,
1717 };
1718 }
1719
1720 function expectStack(overrides: Record<string, unknown> = {}) {
1721 const decoded = expectSuccess(decodePullRequestStacksJson(JSON.stringify([stack(overrides)])));
1722 if (decoded === null) throw new Error("expected a stack");
1723 return decoded;
1724 }
1725
1726 it("reads the first stack, bottom to top, with merged_at outranking state", () => {
1727 expect(expectStack()).toEqual({
1728 id: "42",
1729 number: 3,
1730 url: "https://api.github.com/repos/acme/web/stacks/3",
1731 base: "main",
1732 layers: [
1733 { number: 10, headBranch: "feat/one", state: "merged" },
1734 { number: 11, headBranch: "feat/two", state: "open" },
1735 { number: 12, headBranch: "feat/three", state: "closed" },
1736 ],
1737 });
1738 });
1739 });
1740
1741 const decodeWatchedResult = Schema.decodeUnknownSync(PullRequestWatchFingerprint.result);
1742 const decodeWatched = (pullRequest: object) =>
1743 decodeWatchedResult({ repository: { pullRequest } }).repository!.pullRequest!;
1744
1745 describe("repository references", () => {
1746 it.each([
1747 [undefined, "repo:o/r sort:updated-desc"],
1748 ["12", "repo:o/r sort:updated-desc"],
1749 ['say "hi"', 'repo:o/r in:title "say \\"hi\\"" sort:updated-desc'],
1750 ])("searches %j as %j", (query, q) => {
1751 expect(referenceSearchQuery("o/r", query)).toBe(q);
1752 });
1753
1754 it("puts the exact number first and maps issue and pull request states", () => {
1755 const result = toRepositoryReferences({
1756 search: {
1757 pageInfo: { hasNextPage: true },
1758 nodes: [
1759 { __typename: "PullRequest", number: 3, title: "Merged", pullRequestState: "MERGED" },
1760 { __typename: "Issue", number: 2, title: "Closed", issueState: "CLOSED" },
1761 null,
1762 ],
1763 },
1764 repository: {
1765 issueOrPullRequest: { __typename: "Issue", number: 1, title: "Exact", issueState: "OPEN" },
1766 },
1767 });
1768 expect(result).toEqual({
1769 items: [
1770 { reference: "#1", kind: "issue", number: 1, title: "Exact", state: "open" },
1771 { reference: "#3", kind: "change-request", number: 3, title: "Merged", state: "merged" },
1772 { reference: "#2", kind: "issue", number: 2, title: "Closed", state: "closed" },
1773 ],
1774 truncated: true,
1775 });
1776 });
1777 });
1778
1779 describe("pull request lookups", () => {
1780 it("refuses what GitHub cannot name, so one bad row cannot fail a whole batch", () => {
1781 expect(pullRequestLookup({ repository: "acme/web", number: 7 })).toEqual({
1782 owner: "acme",
1783 name: "web",
1784 number: 7,
1785 });
1786 expect(pullRequestLookup({ repository: 'acme/web") { x } #', number: 1 })).toBeNull();
1787 expect(pullRequestLookup({ repository: "acme/web", number: 0 })).toBeNull();
1788 expect(pullRequestLookup({ repository: "acme/web", number: 1.5 })).toBeNull();
1789 expect(pullRequestLookup({ repository: "acme/web", number: 2 ** 31 })).toBeNull();
1790 });
1791 });
1792
1793 describe("pull request watch fingerprints", () => {
1794 it("moves status with checks and queue removals, and remarks with comments, not across", () => {
1795 const pullRequest = (input: {
1796 readonly running: number;
1797 readonly failed: number;
1798 readonly commentEditedAt: string | null;
1799 readonly reviews: number;
1800 readonly removals: number;
1801 readonly timelineItems: number;
1802 }) => ({
1803 state: "OPEN",
1804 mergeable: "MERGEABLE",
1805 headRefOid: "abc123",
1806 comments: { totalCount: 1, nodes: [{ lastEditedAt: input.commentEditedAt }] },
1807 reviews: { totalCount: input.reviews, nodes: [] },
1808 reviewThreads: { totalCount: 0 },
1809 mergeQueueRemovals: { totalCount: input.timelineItems, filteredCount: input.removals },
1810 commits: {
1811 nodes: [
1812 {
1813 commit: {
1814 statusCheckRollup: {
1815 contexts: {
1816 checkRunCountsByState: [
1817 { state: "IN_PROGRESS", count: input.running },
1818 { state: "FAILURE", count: input.failed },
1819 { state: "SUCCESS", count: 0 },
1820 ],
1821 statusContextCountsByState: null,
1822 },
1823 },
1824 },
1825 },
1826 ],
1827 },
1828 });
1829 const fingerprint = (input: Parameters<typeof pullRequest>[0]) =>
1830 toPullRequestWatchFingerprint(decodeWatched(pullRequest(input)));
1831 const base = {
1832 running: 2,
1833 failed: 0,
1834 commentEditedAt: null,
1835 reviews: 1,
1836 removals: 0,
1837 timelineItems: 3,
1838 };
1839 const before = fingerprint(base);
1840 const checkFinished = fingerprint({ ...base, running: 1, failed: 1 });
1841 const summaryEdited = fingerprint({ ...base, commentEditedAt: "2026-10-05T23:47:43Z" });
1842 const replied = fingerprint({ ...base, reviews: 2 });
1843
1844 expect(checkFinished.status).not.toBe(before.status);
1845 expect(checkFinished.remarks).toBe(before.remarks);
1846 expect(summaryEdited.remarks).not.toBe(before.remarks);
1847 expect(summaryEdited.status).toBe(before.status);
1848 expect(replied.remarks).not.toBe(before.remarks);
1849 // Queued and dropped between two passes leaves the head and its checks as they were.
1850 const dropped = fingerprint({ ...base, removals: 1, timelineItems: 5 });
1851 expect(dropped.status).not.toBe(before.status);
1852 expect(dropped.remarks).toBe(before.remarks);
1853 // GitHub's totalCount counts every timeline item, whatever itemTypes asks for.
1854 const queued = fingerprint({ ...base, timelineItems: 4 });
1855 expect(queued.status).toBe(before.status);
1856 });
1857 });