@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,382 lines 43.8 KB
Raw
1 import * as Result from "effect/Result";
2 import { describe, expect, it } from "vite-plus/test";
3
4 import {
5 decodeAwardEmojiJson,
6 decodeRepositoryBlobsJson,
7 decodeCommitsJson,
8 decodeGraphqlListSupportJson,
9 decodeMergeRequestGraphqlListJson,
10 decodeMergeMessagesJson,
11 decodeMergeRequestDetailJson,
12 decodeMergeRequestDiffsJson,
13 decodeMergeRequestListJson,
14 decodeMergeRequestFileStatsJson,
15 decodeMergeRequestStatsJson,
16 decodeMergeRequestWatchFingerprintJson,
17 decodeReferenceCandidatesJson,
18 decodeNotesJson,
19 decodeOwnAwardIdJson,
20 decodeListStatesJson,
21 decodeTriggerJobChecksJson,
22 decodePipelineStageChecksJson,
23 } from "./gitLabMergeRequestJson.ts";
24
25 function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
26 return JSON.stringify(
27 entries.map((entry) => ({
28 iid: 1,
29 title: "Add the merge requests page",
30 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
31 source_branch: "feat/page",
32 target_branch: "main",
33 created_at: "2026-07-01T00:00:00Z",
34 updated_at: "2026-07-02T00:00:00Z",
35 ...entry,
36 })),
37 );
38 }
39
40 function detailJson(entry: Record<string, unknown>): string {
41 return JSON.stringify({
42 iid: 1,
43 title: "Add the merge requests page",
44 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
45 source_branch: "feat/page",
46 target_branch: "main",
47 created_at: "2026-07-01T00:00:00Z",
48 updated_at: "2026-07-02T00:00:00Z",
49 ...entry,
50 });
51 }
52
53 function expectSuccess<A>(result: Result.Result<A, unknown>): A {
54 expect(Result.isSuccess(result)).toBe(true);
55 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
56 return result.success;
57 }
58
59 describe("decodeMergeRequestListJson", () => {
60 it("reads a merge request as a change request", () => {
61 const batch = expectSuccess(
62 decodeMergeRequestListJson(
63 listJson([
64 {
65 iid: 42,
66 author: { username: "bilal", name: "Bilal" },
67 state: "opened",
68 merge_status: "can_be_merged",
69 draft: false,
70 reviewers: [{ username: "julius" }],
71 labels: ["backend", " "],
72 },
73 {
74 iid: 43,
75 labels: [
76 { name: "bug", color: "#E24329", description: "Something is broken" },
77 { name: " ", color: "#000000" },
78 ],
79 },
80 ]),
81 ),
82 );
83
84 expect(batch.items).toHaveLength(2);
85 expect(batch.items[0]).toMatchObject({
86 number: 42,
87 author: { login: "bilal", name: "Bilal" },
88 headBranch: "feat/page",
89 baseBranch: "main",
90 state: "open",
91 isDraft: false,
92 mergeability: "mergeable",
93 reviewRequestLogins: ["julius"],
94 labels: [{ name: "backend", color: null }],
95 });
96 expect(batch.items[1]?.labels).toEqual([
97 { name: "bug", color: "#E24329", description: "Something is broken" },
98 ]);
99 });
100
101 it("treats a merged timestamp as merged whatever the state says", () => {
102 const batch = expectSuccess(
103 decodeMergeRequestListJson(
104 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
105 ),
106 );
107
108 expect(batch.items[0]?.state).toBe("merged");
109 });
110
111 it("reads the legacy draft flag", () => {
112 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
113
114 expect(batch.items[0]?.isDraft).toBe(true);
115 });
116
117 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
118 const batch = expectSuccess(
119 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
120 );
121
122 expect(batch.items[0]?.mergeability).toBe("conflicting");
123 });
124
125 it("skips a malformed row but still counts it, so paging does not stop early", () => {
126 const batch = expectSuccess(
127 decodeMergeRequestListJson(
128 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
129 ),
130 );
131
132 expect(batch.items).toHaveLength(1);
133 expect(batch.rawIndexes).toEqual([1]);
134 expect(batch.rawCount).toBe(2);
135 });
136 });
137
138 describe("decodeMergeRequestDetailJson", () => {
139 it("preserves a required rebase while CI is running or successful", () => {
140 for (const status of ["running", "success"]) {
141 const detail = expectSuccess(
142 decodeMergeRequestDetailJson(
143 detailJson({
144 merge_status: "can_be_merged",
145 detailed_merge_status: "need_rebase",
146 has_conflicts: false,
147 head_pipeline: { status },
148 }),
149 ),
150 );
151 expect(detail.rebaseRequired).toBe(true);
152 expect(detail.mergeability).toBe("mergeable");
153 }
154 });
155
156 it("distinguishes a cleared rebase blocker from an inconclusive merge check", () => {
157 expect(
158 expectSuccess(
159 decodeMergeRequestDetailJson(detailJson({ detailed_merge_status: "mergeable" })),
160 ).rebaseRequired,
161 ).toBe(false);
162 for (const detailed_merge_status of [undefined, "checking", "ci_still_running"]) {
163 expect(
164 expectSuccess(decodeMergeRequestDetailJson(detailJson({ detailed_merge_status })))
165 .rebaseRequired,
166 ).toBeUndefined();
167 }
168 });
169
170 it("reads the description, file count and pipeline", () => {
171 const detail = expectSuccess(
172 decodeMergeRequestDetailJson(
173 detailJson({
174 description: "Ships the page.",
175 changes_count: "3",
176 reviewers: [{ username: "julius", name: "Julius" }],
177 head_pipeline: {
178 status: "success",
179 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
180 source: "merge_request_event",
181 },
182 }),
183 ),
184 );
185
186 expect(detail.body).toBe("Ships the page.");
187 expect(detail.changedFiles).toBe(3);
188 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
189 expect(detail.checks).toEqual([
190 {
191 name: "Pipeline",
192 status: "success",
193 description: "merge_request_event",
194 url: "https://gitlab.com/acme/web/-/pipelines/9",
195 },
196 ]);
197 });
198
199 it.each(["canceled", "canceling"])("maps a %s pipeline to cancelled", (status) => {
200 const detail = expectSuccess(
201 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
202 );
203
204 expect(detail.checks[0]?.status).toBe("cancelled");
205 });
206
207 it("reads an uncounted change set as its floor", () => {
208 const detail = expectSuccess(
209 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
210 );
211
212 expect(detail.changedFiles).toBe(1000);
213 });
214
215 it("reads the head commit, and says nothing where GitLab omitted it", () => {
216 const headSha = (entry: Record<string, unknown>) =>
217 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
218 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
219
220 expect(headSha({ sha })).toBe(sha);
221 expect(headSha({ sha, diff_refs: null })).toBe(sha);
222 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
223 expect(headSha({})).toBeUndefined();
224 expect(headSha({ sha: null })).toBeUndefined();
225 expect(headSha({ sha: " " })).toBeUndefined();
226 });
227
228 it("reads the diff refs threads are placed against", () => {
229 const diffRefs = (entry: Record<string, unknown>) =>
230 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).diffRefs;
231
232 expect(diffRefs({ diff_refs: { base_sha: "b", start_sha: "s", head_sha: "h" } })).toEqual({
233 baseSha: "b",
234 startSha: "s",
235 headSha: "h",
236 });
237 expect(diffRefs({ diff_refs: null })).toBeUndefined();
238 expect(
239 diffRefs({ diff_refs: { base_sha: null, start_sha: "s", head_sha: "h" } }),
240 ).toBeUndefined();
241 });
242
243 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
244 const armed = (entry: Record<string, unknown>) =>
245 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
246
247 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
248 expect(armed({ auto_merge_enabled: true })).toBe(true);
249 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
250 expect(armed({})).toBeUndefined();
251 });
252
253 it("keeps the squash choice stored with auto-merge", () => {
254 expect(
255 expectSuccess(
256 decodeMergeRequestDetailJson(
257 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
258 ),
259 ),
260 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
261
262 expect(
263 expectSuccess(
264 decodeMergeRequestDetailJson(
265 detailJson({
266 auto_merge_enabled: true,
267 squash: true,
268 squash_on_merge: false,
269 }),
270 ),
271 ).autoMergeMethod,
272 ).toBeUndefined();
273 });
274
275 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
276 const behind = (entry: Record<string, unknown>) =>
277 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
278
279 expect(behind({ diverged_commits_count: 3 })).toBe(3);
280 expect(behind({ diverged_commits_count: 0 })).toBe(0);
281 expect(behind({})).toBeUndefined();
282 expect(behind({ diverged_commits_count: null })).toBeUndefined();
283 });
284
285 it.each(["scheduled", " SCHEDULED "])("keeps a delayed pipeline pending: %s", (status) => {
286 const detail = expectSuccess(
287 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
288 );
289
290 expect(detail.checks[0]?.status).toBe("pending");
291 });
292
293 it("maps a pipeline waiting on a person to neutral, not failure", () => {
294 const detail = expectSuccess(
295 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
296 );
297
298 expect(detail.checks[0]?.status).toBe("neutral");
299 });
300 });
301
302 describe("decodePipelineStageChecksJson", () => {
303 function stagesJson(
304 stages: ReadonlyArray<Record<string, unknown> | null> | null,
305 hasNextPage = false,
306 ): string {
307 return JSON.stringify({
308 data: {
309 project: {
310 mergeRequest: {
311 headPipeline:
312 stages === null
313 ? null
314 : {
315 path: "/fork/web/-/pipelines/9",
316 stages: { nodes: stages, pageInfo: { hasNextPage } },
317 },
318 },
319 },
320 },
321 });
322 }
323
324 it("shows every job under its stage", () => {
325 const checks = expectSuccess(
326 decodePipelineStageChecksJson(
327 stagesJson([
328 {
329 name: "build",
330 status: "success",
331 jobs: {
332 nodes: [
333 { name: "compile", status: "FAILED", retried: true, webPath: "/acme/web/-/jobs/1" },
334 {
335 name: "compile",
336 status: "SUCCESS",
337 detailedStatus: { label: "passed" },
338 webPath: "/acme/web/-/jobs/2",
339 },
340 ],
341 },
342 },
343 {
344 name: "test",
345 status: "failed",
346 jobs: {
347 nodes: [
348 {
349 name: "unit",
350 status: "FAILED",
351 allowFailure: false,
352 webPath: "/acme/web/-/jobs/3",
353 },
354 {
355 name: "lint",
356 status: "FAILED",
357 allowFailure: true,
358 webPath: "/acme/web/-/jobs/4",
359 },
360 { name: "slow", status: "CANCELED", webPath: "/acme/web/-/jobs/5" },
361 { name: "e2e", status: "RUNNING", webPath: "/acme/web/-/jobs/6" },
362 ],
363 },
364 },
365 {
366 name: "deploy",
367 status: "manual",
368 jobs: { nodes: [{ name: "release", status: "MANUAL", webPath: "/acme/web/-/jobs/7" }] },
369 },
370 ]),
371 "https://gitlab.example.com",
372 ),
373 );
374
375 expect(checks?.map((check) => [check.name, check.status, check.url])).toEqual([
376 ["build / compile", "success", "https://gitlab.example.com/acme/web/-/jobs/2"],
377 ["test / unit", "failure", "https://gitlab.example.com/acme/web/-/jobs/3"],
378 ["test / lint", "neutral", "https://gitlab.example.com/acme/web/-/jobs/4"],
379 ["test / slow", "cancelled", "https://gitlab.example.com/acme/web/-/jobs/5"],
380 ["test / e2e", "pending", "https://gitlab.example.com/acme/web/-/jobs/6"],
381 ["deploy / release", "neutral", "https://gitlab.example.com/acme/web/-/jobs/7"],
382 ]);
383 expect(checks?.[0]?.description).toBe("passed");
384 });
385
386 it.each([
387 ["no jobs", undefined],
388 ["an empty job list", { nodes: [] }],
389 [
390 "more jobs than one page",
391 { nodes: [{ name: "unit", status: "FAILED" }], pageInfo: { hasNextPage: true } },
392 ],
393 ["a job GitLab could not resolve", { nodes: [{ name: "unit", status: "FAILED" }, null] }],
394 [
395 "a job without a name",
396 {
397 nodes: [
398 { name: "unit", status: "FAILED" },
399 { name: null, status: "FAILED" },
400 ],
401 },
402 ],
403 ])("keeps a stage whole where its jobs come back with %s", (_, jobs) => {
404 expect(
405 expectSuccess(
406 decodePipelineStageChecksJson(
407 stagesJson([
408 {
409 name: "test",
410 status: "failed",
411 detailedStatus: { label: "failed", detailsPath: "/fork/web/-/pipelines/9#test" },
412 ...(jobs === undefined ? {} : { jobs }),
413 },
414 ]),
415 "https://gitlab.com",
416 ),
417 ),
418 ).toEqual([
419 {
420 name: "test",
421 status: "failure",
422 description: "failed",
423 url: "https://gitlab.com/fork/web/-/pipelines/9#test",
424 },
425 ]);
426 });
427
428 it("answers nothing where there are no stages to show", () => {
429 expect(
430 expectSuccess(decodePipelineStageChecksJson(stagesJson(null), "https://gitlab.com")),
431 ).toBe(null);
432 expect(expectSuccess(decodePipelineStageChecksJson(stagesJson([]), "https://gitlab.com"))).toBe(
433 null,
434 );
435 // A stage past the first page could be the failed one.
436 expect(
437 expectSuccess(
438 decodePipelineStageChecksJson(
439 stagesJson([{ name: "build", status: "success" }], true),
440 "https://gitlab.com",
441 ),
442 ),
443 ).toBe(null);
444 // A stage GitLab failed to resolve comes back null beside an error, and could be the failed one.
445 expect(
446 expectSuccess(
447 decodePipelineStageChecksJson(
448 stagesJson([{ name: "build", status: "success" }, null]),
449 "https://gitlab.com",
450 ),
451 ),
452 ).toBe(null);
453 expect(
454 expectSuccess(
455 decodePipelineStageChecksJson(
456 stagesJson([
457 { name: "build", status: "success" },
458 { name: null, status: "failed" },
459 ]),
460 "https://gitlab.com",
461 ),
462 ),
463 ).toBe(null);
464 expect(
465 expectSuccess(
466 decodePipelineStageChecksJson(
467 JSON.stringify({
468 ...JSON.parse(stagesJson([{ name: "build", status: "success" }])),
469 errors: [{ message: "boom" }],
470 }),
471 "https://gitlab.com",
472 ),
473 ),
474 ).toBe(null);
475 // GitLab answers an error it hit with no data at all.
476 expect(
477 expectSuccess(
478 decodePipelineStageChecksJson(
479 JSON.stringify({ errors: [{ message: "boom" }] }),
480 "https://gitlab.com",
481 ),
482 ),
483 ).toBe(null);
484 });
485 });
486
487 describe("decodeNotesJson", () => {
488 it("keeps comments and drops GitLab's own activity notes", () => {
489 const notes = expectSuccess(
490 decodeNotesJson(
491 JSON.stringify([
492 {
493 id: 1,
494 body: "assigned to @bilal",
495 system: true,
496 created_at: "2026-07-01T00:00:00Z",
497 },
498 {
499 id: 2,
500 body: "Looks good.",
501 author: { username: "julius" },
502 created_at: "2026-07-02T00:00:00Z",
503 },
504 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
505 ]),
506 ),
507 );
508
509 expect(notes.comments).toHaveLength(1);
510 expect(notes.comments[0]).toMatchObject({
511 id: "2",
512 kind: "issue-comment",
513 body: "Looks good.",
514 });
515 expect(notes.rawCount).toBe(3);
516 });
517
518 it("reads a line note as a review comment on its file", () => {
519 const notes = expectSuccess(
520 decodeNotesJson(
521 JSON.stringify([
522 {
523 id: 7,
524 type: "DiffNote",
525 body: "Rename this.",
526 created_at: "2026-07-02T00:00:00Z",
527 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
528 },
529 ]),
530 ),
531 );
532
533 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
534 });
535
536 it("falls back to the old path for a note on a deleted line", () => {
537 const notes = expectSuccess(
538 decodeNotesJson(
539 JSON.stringify([
540 {
541 id: 8,
542 type: "DiffNote",
543 body: "Gone.",
544 created_at: "2026-07-02T00:00:00Z",
545 position: { new_path: null, old_path: "src/old.ts" },
546 },
547 ]),
548 ),
549 );
550
551 expect(notes.comments[0]?.path).toBe("src/old.ts");
552 });
553 });
554
555 describe("decodeCommitsJson", () => {
556 it("falls back to the creation timestamp when there is no commit date", () => {
557 const commits = expectSuccess(
558 decodeCommitsJson(
559 JSON.stringify([
560 {
561 id: "aaa",
562 created_at: "2026-07-01T00:00:00+08:00",
563 author_name: "Ada Lovelace",
564 author_email: "ada@example.com",
565 },
566 ]),
567 ),
568 );
569
570 expect(commits[0]).toMatchObject({
571 oid: "aaa",
572 committedDate: "2026-07-01T00:00:00+08:00",
573 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
574 });
575 });
576 });
577
578 describe("decodeMergeRequestDiffsJson", () => {
579 it("quotes literal backslashes without interpreting them as escapes", () => {
580 const result = expectSuccess(
581 decodeMergeRequestDiffsJson(
582 JSON.stringify([
583 {
584 old_path: String.raw`src\notes.ts`,
585 new_path: String.raw`src\notes.ts`,
586 diff: "@@ -1 +1 @@\n-old\n+new",
587 },
588 ]),
589 ),
590 );
591
592 expect(result.patch).toBe(
593 [
594 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
595 String.raw`--- "a/src\\notes.ts"`,
596 String.raw`+++ "b/src\\notes.ts"`,
597 "@@ -1 +1 @@",
598 "-old",
599 "+new",
600 "",
601 ].join("\n"),
602 );
603 });
604
605 it("preserves spaces and literal backslashes in both rename paths", () => {
606 const result = expectSuccess(
607 decodeMergeRequestDiffsJson(
608 JSON.stringify([
609 {
610 old_path: String.raw` old\name.ts `,
611 new_path: String.raw` new\name.ts `,
612 renamed_file: true,
613 diff: "",
614 },
615 ]),
616 ),
617 );
618
619 expect(result.patch).toBe(
620 [
621 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
622 "similarity index 100%",
623 String.raw`rename from " old\\name.ts "`,
624 String.raw`rename to " new\\name.ts "`,
625 String.raw`--- "a/ old\\name.ts "`,
626 String.raw`+++ "b/ new\\name.ts "`,
627 ].join("\n"),
628 );
629 });
630
631 it("assembles a unified patch GitLab does not return", () => {
632 const result = expectSuccess(
633 decodeMergeRequestDiffsJson(
634 JSON.stringify([
635 {
636 old_path: "src/app.ts",
637 new_path: "src/app.ts",
638 diff: "@@ -1 +1 @@\n-old\n+new\n",
639 },
640 ]),
641 ),
642 );
643
644 expect(result.patch).toBe(
645 [
646 "diff --git a/src/app.ts b/src/app.ts",
647 "--- a/src/app.ts",
648 "+++ b/src/app.ts",
649 "@@ -1 +1 @@",
650 "-old",
651 "+new",
652 "",
653 ].join("\n"),
654 );
655 expect(result.truncated).toBe(false);
656 });
657
658 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
659 const result = expectSuccess(
660 decodeMergeRequestDiffsJson(
661 JSON.stringify([
662 {
663 old_path: "src/new.ts",
664 new_path: "src/new.ts",
665 new_file: true,
666 b_mode: "100755",
667 diff: "@@ -0,0 +1 @@\n+hello\n",
668 },
669 {
670 old_path: "src/gone.ts",
671 new_path: "src/gone.ts",
672 deleted_file: true,
673 diff: "@@ -1 +0,0 @@\n-bye\n",
674 },
675 ]),
676 ),
677 );
678
679 expect(result.patch).toContain("new file mode 100755");
680 expect(result.patch).toContain("--- /dev/null");
681 expect(result.patch).toContain("deleted file mode 100644");
682 expect(result.patch).toContain("+++ /dev/null");
683 });
684
685 it("reports truncation for a file GitLab refused to inline", () => {
686 const result = expectSuccess(
687 decodeMergeRequestDiffsJson(
688 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
689 ),
690 );
691
692 expect(result.truncated).toBe(true);
693 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
694 expect(result.withheldPaths).toEqual(["big.bin"]);
695 });
696
697 it("reports how many files GitLab returned, so the caller can page", () => {
698 const result = expectSuccess(
699 decodeMergeRequestDiffsJson(
700 JSON.stringify(
701 Array.from({ length: 3 }, (_, index) => ({
702 old_path: `src/${index}.ts`,
703 new_path: `src/${index}.ts`,
704 diff: "@@ -1 +1 @@\n-a\n+b\n",
705 })),
706 ),
707 ),
708 );
709
710 expect(result.rawCount).toBe(3);
711 expect(result.truncated).toBe(false);
712 expect(result.patch).toContain("src/2.ts");
713 });
714 });
715
716 describe("decodeTriggerJobChecksJson", () => {
717 it("reads a downstream failure GitLab was told to allow as neutral, not failure", () => {
718 const result = expectSuccess(
719 decodeTriggerJobChecksJson(
720 JSON.stringify([
721 { name: "e2e", allow_failure: true, downstream_pipeline: { status: "failed" } },
722 { name: "deploy", allow_failure: false, downstream_pipeline: { status: "running" } },
723 { name: 7 },
724 ]),
725 ),
726 );
727
728 expect(result.checks.map((check) => [check.name, check.status])).toEqual([
729 ["e2e", "neutral"],
730 ["deploy", "pending"],
731 ]);
732 expect(result.rawCount).toBe(3);
733 });
734 });
735
736 describe("merge request viewer fields", () => {
737 it("leaves merging permitted where GitLab answered without the field", () => {
738 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
739 expect(
740 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
741 ).toBe(true);
742 });
743 });
744
745 describe("decodeAwardEmojiJson", () => {
746 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, ignores an award outside the eight, and collects bot note authors", () => {
747 const result = expectSuccess(
748 decodeAwardEmojiJson(
749 JSON.stringify({
750 data: {
751 currentUser: { username: "bilal" },
752 project: {
753 mergeRequest: {
754 awardEmoji: {
755 nodes: [
756 { name: "thumbsup", user: { username: "bilal" } },
757 { name: "thumbsup", user: { username: "julius" } },
758 ],
759 },
760 notes: {
761 pageInfo: { hasNextPage: false, endCursor: null },
762 nodes: [
763 {
764 id: "gid://gitlab/DiffNote/42",
765 author: { username: "julius", bot: false },
766 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
767 },
768 {
769 id: "gid://gitlab/Note/7",
770 author: { username: "project_278964_bot_89f97e2c", bot: true },
771 awardEmoji: {
772 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
773 },
774 },
775 ],
776 },
777 },
778 },
779 },
780 }),
781 ),
782 );
783
784 expect(result.reactions).toEqual([
785 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
786 ]);
787 expect([...result.reactionsByNoteId]).toEqual([
788 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
789 ]);
790 expect([...result.botLogins]).toEqual(["project_278964_bot_89f97e2c"]);
791 expect(result.nextCursor).toBeNull();
792 });
793
794 it("dates a note's edit only when someone edited its text, not when its thread was resolved", () => {
795 const result = expectSuccess(
796 decodeAwardEmojiJson(
797 JSON.stringify({
798 data: {
799 currentUser: { username: "bilal" },
800 project: {
801 mergeRequest: {
802 awardEmoji: { nodes: [] },
803 notes: {
804 pageInfo: { hasNextPage: false, endCursor: null },
805 nodes: [
806 {
807 id: "gid://gitlab/Note/1",
808 lastEditedAt: "2026-07-02T00:00:00Z",
809 lastEditedBy: { username: "julius" },
810 resolved: false,
811 },
812 {
813 id: "gid://gitlab/Note/2",
814 lastEditedAt: "2026-07-01T00:00:00Z",
815 lastEditedBy: null,
816 resolved: false,
817 },
818 {
819 id: "gid://gitlab/DiscussionNote/3",
820 lastEditedAt: "2026-07-03T00:00:00Z",
821 lastEditedBy: { username: "julius" },
822 resolved: true,
823 },
824 ],
825 },
826 },
827 },
828 },
829 }),
830 ),
831 );
832
833 expect([...result.editedAtByNoteId]).toEqual([["1", "2026-07-02T00:00:00Z"]]);
834 });
835
836 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
837 const result = expectSuccess(
838 decodeAwardEmojiJson(
839 JSON.stringify({
840 data: {
841 currentUser: { username: "Bilal" },
842 project: {
843 mergeRequest: {
844 awardEmoji: {
845 nodes: [
846 { name: "heart", user: { username: "bilal" } },
847 { name: "heart", user: { username: "julius" } },
848 ],
849 },
850 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
851 },
852 },
853 },
854 }),
855 ),
856 );
857
858 expect(result.reactions).toEqual([
859 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
860 ]);
861 });
862 });
863
864 describe("decodeOwnAwardIdJson", () => {
865 const awards = JSON.stringify([
866 { id: 101, name: "thumbsup", user: { username: "julius" } },
867 { id: 102, name: "thumbsup", user: { username: "bilal" } },
868 ]);
869
870 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
871 expect(
872 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
873 ).toEqual({ id: 102, empty: false });
874 });
875 });
876
877 describe("decodeRepositoryBlobsJson", () => {
878 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
879 const blobs = expectSuccess(result);
880 expect(blobs).not.toBe(null);
881 if (blobs === null) throw new Error("expected an answered blobs query");
882 return blobs;
883 }
884
885 it("leaves out a node missing either half, which names no version", () => {
886 const blobs = expectBlobs(
887 decodeRepositoryBlobsJson(
888 JSON.stringify({
889 data: {
890 project: {
891 repository: {
892 blobs: {
893 nodes: [
894 { path: "src/a.ts", oid: null },
895 { path: null, oid: "bbb222" },
896 null,
897 { path: "src/c.ts", oid: "ccc333" },
898 ],
899 },
900 },
901 },
902 },
903 }),
904 ),
905 );
906
907 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
908 });
909
910 it("keys a blob by the path the host spelled, spaces and all", () => {
911 const blobs = expectBlobs(
912 decodeRepositoryBlobsJson(
913 JSON.stringify({
914 data: {
915 project: {
916 repository: {
917 blobs: {
918 nodes: [
919 { path: " leading.ts", oid: "aaa111" },
920 { path: "trailing.ts ", oid: "bbb222" },
921 { path: " ", oid: "ccc333" },
922 { path: "", oid: "ddd444" },
923 ],
924 },
925 },
926 },
927 },
928 }),
929 ),
930 );
931
932 expect([...blobs]).toEqual([
933 [" leading.ts", "aaa111"],
934 ["trailing.ts ", "bbb222"],
935 [" ", "ccc333"],
936 ]);
937 });
938
939 it("tells a project the reader cannot see from a revision with none of the files", () => {
940 expect(
941 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
942 ).toBe(null);
943 expect(
944 expectSuccess(
945 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
946 ),
947 ).toBe(null);
948 expect(
949 expectSuccess(
950 decodeRepositoryBlobsJson(
951 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
952 ),
953 ),
954 ).toEqual(new Map());
955 });
956 });
957
958 describe("decodeListStatesJson", () => {
959 const statesOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
960 expectSuccess(
961 decodeListStatesJson(
962 JSON.stringify({
963 data: {
964 metadata: enterprise === null ? null : { enterprise },
965 project: { mergeRequests: { nodes } },
966 },
967 }),
968 ),
969 );
970 const approvedBy = (...usernames: ReadonlyArray<string>) => ({
971 nodes: usernames.map((username) => ({ username })),
972 });
973 const reviewers = (...reviewStates: ReadonlyArray<string>) => ({
974 nodes: reviewStates.map((reviewState) => ({ mergeRequestInteraction: { reviewState } })),
975 });
976
977 it.each([
978 {
979 reading: "an approval short of Enterprise approval rules",
980 enterprise: true,
981 approval: { approved: false, approvedBy: approvedBy("GitLabDuo") },
982 decision: "review-required",
983 },
984 {
985 reading: "Enterprise approval rules no one has approved against",
986 enterprise: true,
987 approval: { approved: false, approvedBy: approvedBy() },
988 decision: "review-required",
989 },
990 {
991 reading: "Enterprise approval rules met",
992 enterprise: true,
993 approval: { approved: true, approvedBy: approvedBy("julius") },
994 decision: "approved",
995 },
996 {
997 reading: "Enterprise without approval rules or approvals",
998 enterprise: true,
999 approval: { approved: true, approvedBy: approvedBy() },
1000 decision: null,
1001 },
1002 {
1003 reading: "Community Edition with an approval",
1004 enterprise: false,
1005 approval: { approved: true, approvedBy: approvedBy("julius") },
1006 decision: "approved",
1007 },
1008 {
1009 reading: "Community Edition without approvals",
1010 enterprise: false,
1011 approval: { approved: false, approvedBy: approvedBy() },
1012 decision: null,
1013 },
1014 {
1015 reading: "a reviewer requesting changes after another approved",
1016 enterprise: true,
1017 approval: {
1018 approved: true,
1019 approvedBy: approvedBy("julius"),
1020 reviewers: reviewers("APPROVED", "REQUESTED_CHANGES"),
1021 },
1022 decision: "changes-requested",
1023 },
1024 {
1025 reading: "a Community Edition reviewer requesting changes",
1026 enterprise: false,
1027 approval: {
1028 approved: false,
1029 approvedBy: approvedBy(),
1030 reviewers: reviewers("REQUESTED_CHANGES"),
1031 },
1032 decision: "changes-requested",
1033 },
1034 {
1035 reading: "reviewers who have not asked for changes",
1036 enterprise: false,
1037 approval: {
1038 approved: true,
1039 approvedBy: approvedBy("julius"),
1040 reviewers: reviewers("UNREVIEWED", "REVIEWED"),
1041 },
1042 decision: "approved",
1043 },
1044 ])("reads $reading as $decision", ({ enterprise, approval, decision }) => {
1045 expect([...statesOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([
1046 [7, { reviewDecision: decision, checksState: null }],
1047 ]);
1048 });
1049
1050 it.each([
1051 { pipeline: { status: "SUCCESS" }, checksState: "passing" },
1052 { pipeline: { status: "FAILED" }, checksState: "failing" },
1053 { pipeline: { status: "CANCELED" }, checksState: "failing" },
1054 { pipeline: { status: "RUNNING" }, checksState: "pending" },
1055 { pipeline: { status: "WAITING_FOR_RESOURCE" }, checksState: "pending" },
1056 { pipeline: { status: "MANUAL" }, checksState: null },
1057 { pipeline: { status: "SKIPPED" }, checksState: null },
1058 { pipeline: null, checksState: null },
1059 ])(
1060 "reads a $pipeline.status head pipeline as $checksState checks",
1061 ({ pipeline, checksState }) => {
1062 expect([
1063 ...statesOf(false, [
1064 { iid: "7", approved: false, approvedBy: approvedBy(), headPipeline: pipeline },
1065 ]),
1066 ]).toEqual([[7, { reviewDecision: null, checksState }]]);
1067 },
1068 );
1069
1070 it("leaves out a merge request it cannot key, and a project the reader cannot see", () => {
1071 expect([...statesOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
1072 expect(
1073 expectSuccess(decodeListStatesJson(JSON.stringify({ data: { project: null } }))),
1074 ).toEqual(new Map());
1075 });
1076
1077 it("keeps the checks of a merge request whose approval it cannot judge", () => {
1078 expect([
1079 ...statesOf(null, [
1080 {
1081 iid: "7",
1082 approved: false,
1083 approvedBy: approvedBy(),
1084 headPipeline: { status: "FAILED" },
1085 },
1086 ]),
1087 ...statesOf(true, [
1088 { iid: "8", approved: null, approvedBy: approvedBy("julius") },
1089 { iid: "9", approved: true, approvedBy: null },
1090 ]),
1091 ]).toEqual([
1092 [7, { checksState: "failing" }],
1093 [8, { checksState: null }],
1094 [9, { checksState: null }],
1095 ]);
1096 });
1097 });
1098
1099 describe("decodeReferenceCandidatesJson", () => {
1100 it("prefixes merge requests with ! and skips malformed entries", () => {
1101 const raw = JSON.stringify([
1102 { iid: 5, title: "Ship it", state: "merged" },
1103 { iid: 6, title: "Draft", state: "opened" },
1104 { iid: 7, title: "Locked", state: "locked" },
1105 { title: "No iid", state: "opened" },
1106 ]);
1107 const decoded = decodeReferenceCandidatesJson(raw, "change-request");
1108 expect(Result.isSuccess(decoded) && decoded.success).toEqual({
1109 items: [
1110 { reference: "!5", kind: "change-request", number: 5, title: "Ship it", state: "merged" },
1111 { reference: "!6", kind: "change-request", number: 6, title: "Draft", state: "open" },
1112 { reference: "!7", kind: "change-request", number: 7, title: "Locked", state: "closed" },
1113 ],
1114 rawCount: 4,
1115 });
1116 const issues = decodeReferenceCandidatesJson(raw, "issue");
1117 expect(Result.isSuccess(issues) && issues.success.items[0]?.reference).toBe("#5");
1118 });
1119 });
1120
1121 describe("decodeMergeRequestStatsJson", () => {
1122 it("keys the counts by merge request number", () => {
1123 const stats = expectSuccess(
1124 decodeMergeRequestStatsJson(
1125 JSON.stringify({
1126 data: {
1127 project: {
1128 mergeRequests: {
1129 nodes: [
1130 { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },
1131 { iid: "8", diffStatsSummary: null },
1132 ],
1133 },
1134 },
1135 },
1136 }),
1137 ),
1138 );
1139
1140 // A merge request without a summary is left out rather than shown as zero lines changed.
1141 expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);
1142 });
1143
1144 it("answers nothing for a project the token cannot see", () => {
1145 const stats = expectSuccess(
1146 decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),
1147 );
1148
1149 expect(stats.size).toBe(0);
1150 });
1151
1152 it("reports a file list shorter than the summary as truncated", () => {
1153 const read = (fileCount: number) =>
1154 expectSuccess(
1155 decodeMergeRequestFileStatsJson(
1156 JSON.stringify({
1157 data: {
1158 project: {
1159 mergeRequest: {
1160 diffStatsSummary: { fileCount },
1161 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
1162 },
1163 },
1164 },
1165 }),
1166 ),
1167 );
1168
1169 expect(read(1)).toEqual({
1170 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
1171 truncated: false,
1172 });
1173 expect(read(2).truncated).toBe(true);
1174 });
1175 });
1176
1177 describe("decodeMergeRequestGraphqlListJson", () => {
1178 it("reads a row and its review state in one page, counting rows it cannot read", () => {
1179 const page = expectSuccess(
1180 decodeMergeRequestGraphqlListJson(
1181 JSON.stringify({
1182 data: {
1183 metadata: { enterprise: false },
1184 project: {
1185 mergeRequests: {
1186 pageInfo: { hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" },
1187 nodes: [
1188 {
1189 iid: "7",
1190 title: "Add the merge requests page",
1191 webUrl: "https://gitlab.com/acme/web/-/merge_requests/7",
1192 state: "opened",
1193 draft: true,
1194 createdAt: "2026-07-01T00:00:00Z",
1195 updatedAt: "2026-07-02T00:00:00Z",
1196 sourceBranch: "feat/page",
1197 targetBranch: "main",
1198 conflicts: true,
1199 mergeStatusEnum: "CHECKING",
1200 author: { username: "bilal", name: "Bilal", avatarUrl: null },
1201 labels: { nodes: [{ title: "bug", color: "#E24329", description: null }] },
1202 approved: false,
1203 approvedBy: { nodes: [] },
1204 reviewers: {
1205 nodes: [
1206 {
1207 username: "julius",
1208 mergeRequestInteraction: { reviewState: "REQUESTED_CHANGES" },
1209 },
1210 ],
1211 },
1212 headPipeline: { status: "FAILED" },
1213 },
1214 { iid: "8" },
1215 ],
1216 },
1217 },
1218 },
1219 }),
1220 ),
1221 );
1222
1223 expect(page.items).toEqual([
1224 expect.objectContaining({
1225 number: 7,
1226 state: "open",
1227 isDraft: true,
1228 mergeability: "conflicting",
1229 reviewRequestLogins: ["julius"],
1230 labels: [{ name: "bug", color: "#E24329", description: null }],
1231 }),
1232 ]);
1233 expect([...page.states]).toEqual([
1234 [7, { reviewDecision: "changes-requested", checksState: "failing" }],
1235 ]);
1236 expect(page).toMatchObject({ rawCount: 2, hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" });
1237 });
1238 it("fails on a project the reader cannot see, rather than reading it as empty", () => {
1239 expect(
1240 Result.isFailure(
1241 decodeMergeRequestGraphqlListJson(
1242 JSON.stringify({ data: { metadata: { enterprise: true }, project: null } }),
1243 ),
1244 ),
1245 ).toBe(true);
1246 });
1247 });
1248
1249 describe("decodeGraphqlListSupportJson", () => {
1250 it.each([
1251 { version: "17.8.4", supported: false },
1252 { version: "17.9.0", supported: true },
1253 { version: "19.6.0-pre", supported: true },
1254 { version: null, supported: false },
1255 ])("reads GitLab $version as supported: $supported", ({ version, supported }) => {
1256 expect(
1257 expectSuccess(
1258 decodeGraphqlListSupportJson(JSON.stringify({ data: { metadata: { version } } })),
1259 ),
1260 ).toBe(supported);
1261 });
1262 });
1263
1264 describe("decodeMergeMessagesJson", () => {
1265 it("fails a partial response instead of reading errored fields as absent templates", () => {
1266 const decoded = decodeMergeMessagesJson(
1267 JSON.stringify({
1268 errors: [{ message: "Internal server error", path: ["project", "mergeRequest"] }],
1269 data: {
1270 project: { mergeRequest: { title: "Add thing", defaultMergeCommitMessage: null } },
1271 },
1272 }),
1273 );
1274
1275 expect(Result.isFailure(decoded)).toBe(true);
1276 });
1277 });
1278
1279 describe("decodeMergeRequestWatchFingerprintJson", () => {
1280 const pipeline = (status: string, downstream: string, failed = 0, moreBridges = false) => ({
1281 id: "gid://gitlab/Ci::Pipeline/9",
1282 status,
1283 succeeded: { count: 3 },
1284 failed: { count: failed },
1285 stopped: { count: 0 },
1286 jobs: {
1287 pageInfo: { hasNextPage: moreBridges },
1288 nodes: [
1289 {
1290 name: "deploy",
1291 status,
1292 downstreamPipeline: { id: "gid://gitlab/Ci::Pipeline/10", status: downstream },
1293 },
1294 ],
1295 },
1296 });
1297 const edit = (at: string, resolved = false) => ({
1298 lastEditedAt: at,
1299 lastEditedBy: { username: "reviewer" },
1300 resolved,
1301 });
1302 const read = (overrides: Record<string, unknown>) =>
1303 expectSuccess(
1304 decodeMergeRequestWatchFingerprintJson(
1305 JSON.stringify({
1306 data: {
1307 project: {
1308 mergeRequest: {
1309 state: "opened",
1310 mergeStatusEnum: "CAN_BE_MERGED",
1311 detailedMergeStatus: "MERGEABLE",
1312 conflicts: false,
1313 diffHeadSha: "a".repeat(40),
1314 userPermissions: { updateMergeRequest: true },
1315 headPipeline: pipeline("RUNNING", "RUNNING"),
1316 userNotesCount: 2,
1317 notes: {
1318 nodes: [
1319 edit("2026-07-02T00:00:00Z"),
1320 { lastEditedAt: null, lastEditedBy: null, resolved: null },
1321 edit("2026-07-01T00:00:00Z"),
1322 ],
1323 },
1324 ...overrides,
1325 },
1326 },
1327 },
1328 }),
1329 ),
1330 );
1331
1332 // A remarks change makes the watch reread every comment, so pipeline progress must not touch it.
1333 it("moves pipeline progress into status and comment edits into remarks", () => {
1334 const base = read({});
1335 const passed = read({ headPipeline: pipeline("SUCCESS", "RUNNING") });
1336 const downstreamPassed = read({ headPipeline: pipeline("SUCCESS", "SUCCESS") });
1337 const jobFailed = read({ headPipeline: pipeline("RUNNING", "RUNNING", 1) });
1338 const edited = read({ notes: { nodes: [edit("2026-07-03T00:00:00Z")] } });
1339 // Resolving a thread restamps its notes without an edit, so it must not reread comments.
1340 const resolved = read({
1341 notes: { nodes: [edit("2026-07-02T00:00:00Z"), edit("2026-07-03T00:00:00Z", true)] },
1342 });
1343
1344 expect(base?.remarks).toBe("2 2026-07-02T00:00:00Z");
1345 expect(passed?.status).not.toBe(base?.status);
1346 expect(downstreamPassed?.status).not.toBe(passed?.status);
1347 expect(jobFailed?.status).not.toBe(base?.status);
1348 expect(passed?.remarks).toBe(base?.remarks);
1349 expect(edited?.status).toBe(base?.status);
1350 expect(edited?.remarks).not.toBe(base?.remarks);
1351 expect(resolved?.remarks).toBe(base?.remarks);
1352 expect(read({ userNotesCount: 3 })?.remarks).not.toBe(base?.remarks);
1353 // A target branch moving on leaves merge_status at can_be_merged on fast-forward projects.
1354 expect(read({ detailedMergeStatus: "NEED_REBASE" })?.status).not.toBe(base?.status);
1355 });
1356
1357 // Only the REST read asks GitLab to recheck mergeability, and only for viewers who can update.
1358 it("covers the detail read once merge status has settled or no read could settle it", () => {
1359 expect(read({})?.coversDetail).toBe(true);
1360 // A capped job count or a second bridge page can hide a job settling.
1361 expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 1001) })?.coversDetail).toBe(false);
1362 expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 0, true) })?.coversDetail).toBe(
1363 false,
1364 );
1365 expect(read({ mergeStatusEnum: "UNCHECKED" })?.coversDetail).toBe(false);
1366 expect(read({ mergeStatusEnum: "CHECKING", conflicts: true })?.coversDetail).toBe(true);
1367 expect(
1368 read({ mergeStatusEnum: "UNCHECKED", userPermissions: { updateMergeRequest: false } })
1369 ?.coversDetail,
1370 ).toBe(true);
1371 });
1372
1373 it("answers null when GitLab returned no merge request", () => {
1374 expect(
1375 expectSuccess(
1376 decodeMergeRequestWatchFingerprintJson(
1377 JSON.stringify({ data: { project: { mergeRequest: null } } }),
1378 ),
1379 ),
1380 ).toBeNull();
1381 });
1382 });