Open History to see the last commit
1import { assert, describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as TestClock from "effect/testing/TestClock";
5
6import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
7
8import * as GitLabCli from "./GitLabCli.ts";
9import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
10import { gitLabViewerPermissions, make } from "./GitLabPullRequestProvider.ts";
11
12it.effect.each(["merge", "disable-auto-merge"] as const)(
13 "keeps reads and %s on the selected host when glab prefers another remote",
14 (action) =>
15 Effect.gen(function* () {
16 const selectedHost = "gitlab.example.test:8443";
17 const otherHost = "other.gitlab.example.test";
18 const readHosts: string[] = [];
19 const mergedHosts: string[] = [];
20 const native = yield* GitLabCli.make.pipe(
21 Effect.provide(
22 TestSourceControlHost.layer({
23 process: {
24 run: (input) => {
25 // glab prefers a remote named `gitlab` to `origin`. The checkout's
26 // selected repository must still own every request and mutation.
27 const host = input.env?.GITLAB_HOST ?? otherHost;
28 const path = input.args[1];
29 const mutation =
30 input.args[0] === "mr" || (input.args.includes("POST") && path !== "graphql");
31 if (mutation) mergedHosts.push(host);
32 else readHosts.push(host);
33 const response = mutation
34 ? {}
35 : path === "graphql"
36 ? {
37 data: {
38 project: {
39 mergeRequests: {
40 nodes: [
41 { iid: "7", diffStatsSummary: { additions: 2, deletions: 1 } },
42 ],
43 },
44 mergeRequest: {
45 userPermissions: { adminMergeRequest: true },
46 diffStatsSummary: { fileCount: 1 },
47 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
48 },
49 },
50 },
51 }
52 : path?.includes("merge_requests/")
53 ? {
54 iid: 7,
55 title: "Merge request 7",
56 web_url: `https://${host}/acme/web/-/merge_requests/7`,
57 source_branch: "feature",
58 target_branch: "main",
59 created_at: "2026-07-01T00:00:00Z",
60 updated_at: "2026-07-02T00:00:00Z",
61 user: { can_merge: true },
62 diff_refs: {
63 head_sha: "a".repeat(40),
64 base_sha: "b".repeat(40),
65 start_sha: "b".repeat(40),
66 },
67 }
68 : path === "user"
69 ? { username: "reviewer" }
70 : path?.includes("/labels?") || path?.includes("/users?")
71 ? []
72 : { merge_method: "merge", squash_option: "default_off" };
73 return Effect.succeed(
74 TestSourceControlHost.processOutput(JSON.stringify(response)),
75 );
76 },
77 },
78 }),
79 ),
80 );
81 const cli = yield* GitLabPullRequestCli.make.pipe(
82 Effect.provideService(GitLabCli.GitLabCli, native),
83 );
84 const provider = yield* make.pipe(
85 Effect.provideService(GitLabPullRequestCli.GitLabPullRequestCli, cli),
86 );
87 const reference = {
88 cwd: "/repo",
89 repository: "acme/web",
90 host: selectedHost,
91 number: 7,
92 };
93 const detail = yield* provider.getChangeRequest(reference);
94 expect({ additions: detail.additions, deletions: detail.deletions }).toEqual({
95 additions: 2,
96 deletions: 1,
97 });
98 assert.isDefined(provider.getChangeRequestSummary);
99 expect((yield* provider.getChangeRequestSummary(reference)).additions).toBe(2);
100 assert.isDefined(provider.listChangeRequestStats);
101 expect(
102 yield* provider.listChangeRequestStats({ ...reference, changeRequests: [reference] }),
103 ).toEqual([{ repository: reference.repository, number: 7, additions: 2, deletions: 1 }]);
104 assert.isDefined(provider.getFileStats);
105 expect(yield* provider.getFileStats(reference)).toEqual({
106 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
107 truncated: false,
108 });
109 expect(yield* provider.getViewer(reference)).toBe("reviewer");
110 assert.isDefined(provider.listRepositoryLabels);
111 yield* provider.listRepositoryLabels(reference);
112 assert.isDefined(provider.searchRepositoryAuthors);
113 yield* provider.searchRepositoryAuthors(reference);
114 yield* provider.runAction({ ...reference, action });
115
116 expect(readHosts).toEqual(Array(action === "merge" ? 14 : 13).fill(selectedHost));
117 expect({ url: detail.url, mutatedHosts: mergedHosts }).toEqual({
118 url: `https://${selectedHost}/acme/web/-/merge_requests/7`,
119 mutatedHosts: [selectedHost],
120 });
121 }),
122);
123
124describe("gitLabViewerPermissions", () => {
125 it("offers everything to a viewer GitLab says can merge", () => {
126 expect(
127 gitLabViewerPermissions({
128 viewerCanMerge: true,
129 viewerCanDeleteBranch: true,
130 viewerCanEditLabels: true,
131 }),
132 ).toEqual({
133 actions: [
134 "merge",
135 "ready",
136 "draft",
137 "close",
138 "reopen",
139 "update-branch",
140 "enable-auto-merge",
141 "disable-auto-merge",
142 "revert",
143 "delete-branch",
144 ],
145 comment: true,
146 resolve: true,
147 verdicts: ["comment", "approve", "request-changes"],
148 requestReviewers: true,
149 maintainerEdits: false,
150 labels: true,
151 updateMethods: ["rebase"],
152 });
153 });
154
155 it("keeps merge, now and later, from a viewer GitLab says cannot", () => {
156 expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
157 actions: ["ready", "draft", "close", "reopen"],
158 comment: true,
159 resolve: true,
160 verdicts: ["comment", "approve", "request-changes"],
161 requestReviewers: true,
162 maintainerEdits: false,
163 labels: false,
164 });
165 });
166});
167
168describe("getChangeRequest base freshness", () => {
169 const detail = {
170 number: 7,
171 title: "Merge request 7",
172 url: "https://gitlab.com/acme/web/-/merge_requests/7",
173 author: null,
174 headBranch: "feat/page",
175 baseBranch: "main",
176 state: "open" as const,
177 isDraft: false,
178 mergeability: "mergeable" as const,
179 additions: 0,
180 deletions: 0,
181 createdAt: "2026-07-01T00:00:00Z",
182 updatedAt: "2026-07-02T00:00:00Z",
183 reviewRequestLogins: [],
184 labels: [],
185 body: "",
186 changedFiles: 1,
187 mergedAt: null,
188 closedAt: null,
189 reviewers: [],
190 checks: [],
191 viewerCanMerge: true,
192 reviewerIds: [],
193 reviewerUsers: [],
194 };
195
196 it.effect.each(["getChangeRequestPreview", "getChangeRequestSummary"] as const)(
197 "%s preserves merge request fields without fetching project settings or fork permissions",
198 (operation) =>
199 Effect.gen(function* () {
200 const detailInputs: Array<{ readonly maintainerEdits?: boolean }> = [];
201 const provider = yield* make.pipe(
202 Effect.provide(
203 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
204 getMergeRequestDetail: (input) => {
205 detailInputs.push(input);
206 return Effect.succeed(detail);
207 },
208 getListStates: () => Effect.succeed(new Map()),
209
210 listMergeRequestStats: () => Effect.succeed([]),
211 }),
212 ),
213 );
214 const read = provider[operation];
215 assert.isDefined(read);
216 expect(
217 yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }),
218 ).toEqual(detail);
219 expect(detailInputs.map((input) => input.maintainerEdits)).toEqual([false]);
220 }),
221 );
222
223 const readWith = (
224 divergence: { readonly divergedCommits?: number },
225 stats: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["listMergeRequestStats"] = () =>
226 Effect.succeed([]),
227 ) =>
228 Effect.gen(function* () {
229 const provider = yield* make;
230 return yield* provider.getChangeRequest({
231 cwd: "/w",
232 repository: "acme/web",
233 host: "gitlab.com",
234 number: 7,
235 });
236 }).pipe(
237 Effect.provide(
238 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
239 getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
240 getProjectMergeCapabilities: () =>
241 Effect.succeed({ merge: true, squash: true, rebase: true }),
242 listMergeRequestStats: stats,
243 }),
244 ),
245 );
246
247 it.effect("reads a counted divergence as a branch that has fallen behind", () =>
248 Effect.gen(function* () {
249 const changeRequest = yield* readWith({ divergedCommits: 3 });
250
251 expect(changeRequest.baseComparison).toBe("behind");
252 expect(changeRequest.behindBy).toBe(3);
253 }),
254 );
255
256 it.effect("says nothing at all where GitLab counted nothing", () =>
257 Effect.gen(function* () {
258 const changeRequest = yield* readWith({});
259
260 expect(changeRequest.baseComparison).toBe("unknown");
261 expect(changeRequest.behindBy).toBeUndefined();
262 }),
263 );
264
265 it.effect("fills in the line counts the REST detail leaves out", () =>
266 Effect.gen(function* () {
267 const changeRequest = yield* readWith({}, () =>
268 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
269 );
270
271 expect(changeRequest.additions).toBe(40);
272 expect(changeRequest.deletions).toBe(2);
273 }),
274 );
275
276 it.effect("reports an unauthenticated line count read instead of a detail without counts", () =>
277 Effect.gen(function* () {
278 const result = yield* Effect.result(
279 readWith({}, () =>
280 Effect.fail(
281 new GitLabCli.GitLabCliAuthenticationError({
282 operation: "execute",
283 command: "glab",
284 cwd: "/w",
285 cause: null,
286 }),
287 ),
288 ),
289 );
290
291 expect(result).toMatchObject({
292 _tag: "Failure",
293 failure: { _tag: "PullRequestProviderError", reason: "unauthenticated" },
294 });
295 }),
296 );
297
298 it.effect("gives linked threads line counts without reading the merge settings", () =>
299 Effect.gen(function* () {
300 const summary = yield* Effect.gen(function* () {
301 const provider = yield* make;
302 const read = provider.getChangeRequestSummary;
303 if (read === undefined) return yield* Effect.die("summary read missing");
304 return yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 });
305 }).pipe(
306 Effect.provide(
307 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
308 getMergeRequestDetail: () => Effect.succeed(detail),
309 getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),
310 getListStates: () => Effect.succeed(new Map()),
311 listMergeRequestStats: () =>
312 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
313 }),
314 ),
315 );
316
317 expect(summary.additions).toBe(40);
318 expect(summary.deletions).toBe(2);
319 }),
320 );
321});
322
323describe("merge request reads", () => {
324 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
325 const detail = {
326 number: 7,
327 title: "Merge request 7",
328 url: "https://gitlab.com/acme/web/-/merge_requests/7",
329 author: null,
330 headBranch: "feat/page",
331 baseBranch: "main",
332 state: "open" as const,
333 isDraft: false,
334 mergeability: "mergeable" as const,
335 additions: 0,
336 deletions: 0,
337 createdAt: "2026-07-01T00:00:00Z",
338 updatedAt: "2026-07-02T00:00:00Z",
339 reviewRequestLogins: [],
340 labels: [],
341 body: "",
342 changedFiles: 1,
343 mergedAt: null,
344 closedAt: null,
345 reviewers: [],
346 checks: [],
347 viewerCanMerge: true,
348 reviewerIds: [],
349 reviewerUsers: [],
350 };
351
352 const countingProvider = Effect.gen(function* () {
353 const calls = { detail: 0, mergeCapabilities: 0 };
354 const host = { viewerCanMerge: true };
355 const provider = yield* make.pipe(
356 Effect.provide(
357 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
358 listMergeRequestStats: () => Effect.succeed([]),
359 getListStates: () => Effect.succeed(new Map()),
360 getMergeRequestDetail: (input) =>
361 Effect.sync(() => {
362 calls.detail += 1;
363 return { ...detail, number: input.number, viewerCanMerge: host.viewerCanMerge };
364 }),
365 getProjectMergeCapabilities: () =>
366 Effect.sync(() => {
367 calls.mergeCapabilities += 1;
368 return { merge: true, squash: true, rebase: true };
369 }),
370 runMergeRequestAction: () => Effect.void,
371 setLabels: () => Effect.void,
372 }),
373 ),
374 );
375 const checks = provider.getChangeRequestChecks;
376 const forget = provider.forgetChangeRequestReads;
377 if (checks === undefined || forget === undefined) {
378 return yield* Effect.die("GitLab answers checks and forgets its reads");
379 }
380 return { provider, checks, forget, calls, host };
381 });
382
383 it.effect("asks for a project's merge methods once across its merge requests", () =>
384 Effect.gen(function* () {
385 const { provider, calls } = yield* countingProvider;
386
387 yield* provider.getChangeRequest(reference);
388 yield* provider.getChangeRequest(reference);
389 yield* provider.getChangeRequest({ ...reference, number: 8 });
390
391 expect(calls.mergeCapabilities).toBe(1);
392 }),
393 );
394
395 it.effect("answers checks from the merge request the detail just read", () =>
396 Effect.gen(function* () {
397 const { provider, checks, calls } = yield* countingProvider;
398
399 yield* provider.getChangeRequest(reference);
400 yield* checks(reference);
401
402 expect(calls.detail).toBe(1);
403
404 const summary = provider.getChangeRequestSummary;
405 assert.isDefined(summary);
406 yield* summary(reference);
407 expect(calls.detail).toBe(2);
408 }),
409 );
410
411 it.effect.each([
412 {
413 write: "runAction",
414 run: (provider: Effect.Success<typeof make>) =>
415 provider.runAction({ ...reference, action: "ready" }),
416 },
417 {
418 write: "setLabels",
419 run: (provider: Effect.Success<typeof make>) =>
420 provider.setLabels?.({ ...reference, labels: ["bug"], applied: true }) ?? Effect.void,
421 },
422 ])("reads a merge request again after $write", ({ run }) =>
423 Effect.gen(function* () {
424 const { provider, checks, calls } = yield* countingProvider;
425
426 yield* provider.getChangeRequest(reference);
427 yield* run(provider);
428 yield* checks(reference);
429
430 expect(calls.detail).toBe(2);
431 }),
432 );
433
434 it.effect.each([{ cwd: "/other" }, { host: "other.gitlab.test" }])(
435 "does not share reads with %j",
436 (other) =>
437 Effect.gen(function* () {
438 const { provider, calls } = yield* countingProvider;
439
440 yield* provider.getChangeRequest(reference);
441 yield* provider.getChangeRequest({ ...reference, ...other });
442 yield* provider.getChangeRequest(reference);
443 yield* provider.getChangeRequest({ ...reference, ...other });
444
445 expect(calls).toEqual({ detail: 2, mergeCapabilities: 2 });
446 }),
447 );
448
449 it.effect("reads a merge request again once a minute has passed", () =>
450 Effect.gen(function* () {
451 const { provider, calls } = yield* countingProvider;
452
453 yield* provider.getChangeRequest(reference);
454 yield* TestClock.adjust("61 seconds");
455 yield* provider.getChangeRequest(reference);
456
457 expect(calls.detail).toBe(2);
458 }),
459 );
460
461 it.effect("answers viewer permissions from the host, not the page's read", () =>
462 Effect.gen(function* () {
463 const { provider, host } = yield* countingProvider;
464
465 host.viewerCanMerge = false;
466 yield* provider.getChangeRequest(reference);
467 host.viewerCanMerge = true;
468 const granted = yield* provider.getViewerPermissions(reference);
469 host.viewerCanMerge = false;
470 const revoked = yield* provider.getViewerPermissions(reference);
471
472 expect(granted.actions).toContain("merge");
473 expect(revoked.actions).not.toContain("merge");
474 }),
475 );
476
477 it.effect("reads a merge request again once its reads are forgotten", () =>
478 Effect.gen(function* () {
479 const { provider, checks, forget, calls } = yield* countingProvider;
480 const other = { ...reference, repository: "acme/api" };
481
482 yield* provider.getChangeRequest(reference);
483 yield* provider.getChangeRequest(other);
484 yield* forget({ repository: "ACME/web", number: 7 });
485 yield* checks(reference);
486 yield* checks(other);
487 expect(calls.detail).toBe(3);
488
489 yield* forget({ repository: "acme/web" });
490 yield* checks(reference);
491 yield* forget();
492 yield* checks(other);
493 expect(calls.detail).toBe(5);
494 }),
495 );
496});
497
498describe("optional activity reads", () => {
499 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
500 const comment = {
501 id: "42",
502 kind: "issue-comment" as const,
503 author: null,
504 body: "Keep this comment",
505 createdAt: "2026-07-01T00:00:00Z",
506 url: null,
507 path: null,
508 reviewState: null,
509 };
510 const commit = {
511 oid: "abc",
512 messageHeadline: "Keep this commit",
513 committedDate: "2026-07-01T00:00:00Z",
514 };
515 const webUrl = "https://git.acme.dev/acme/web/-/merge_requests/7";
516 const currentRefs = { baseSha: "base2", startSha: "start2", headSha: "head2" };
517 const reads = {
518 getMergeRequestDetail: () =>
519 Effect.succeed({
520 number: 7,
521 title: "Merge request 7",
522 url: webUrl,
523 author: null,
524 headBranch: "feat/page",
525 baseBranch: "main",
526 state: "open" as const,
527 isDraft: false,
528 mergeability: "mergeable" as const,
529 additions: 0,
530 deletions: 0,
531 createdAt: "2026-07-01T00:00:00Z",
532 updatedAt: "2026-07-02T00:00:00Z",
533 reviewRequestLogins: [],
534 labels: [],
535 body: "",
536 changedFiles: 1,
537 mergedAt: null,
538 closedAt: null,
539 reviewers: [],
540 checks: [],
541 viewerCanMerge: true,
542 reviewerIds: [],
543 reviewerUsers: [],
544 diffRefs: currentRefs,
545 }),
546 listNotes: () => Effect.succeed({ comments: [comment], truncated: false }),
547 listCommits: () => Effect.succeed([commit]),
548 listDiscussions: () =>
549 Effect.succeed({
550 threads: [],
551 diffRefsByThreadId: new Map(),
552 overviewFindingIds: [],
553 truncated: false,
554 }),
555 listReactions: () =>
556 Effect.succeed({
557 reactions: [],
558 reactionsByNoteId: new Map(),
559 editedAtByNoteId: new Map(),
560 botLogins: new Set<string>(),
561 }),
562 };
563 const context = {
564 operation: "execute" as const,
565 command: "glab" as const,
566 cwd: "/w",
567 cause: null,
568 };
569
570 it.effect.each([
571 {
572 operation: "listNotes",
573 error: new GitLabCli.GitLabCliAuthenticationError(context),
574 reason: "unauthenticated",
575 },
576 {
577 operation: "listCommits",
578 error: new GitLabCli.GitLabCliUnavailableError(context),
579 reason: "missing-tool",
580 },
581 ] as const)(
582 "reports $reason instead of successful partial activity",
583 ({ operation, error, reason }) =>
584 Effect.gen(function* () {
585 const provider = yield* make.pipe(
586 Effect.provide(
587 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
588 ...reads,
589 [operation]: () => Effect.fail(error),
590 }),
591 ),
592 );
593
594 expect(yield* Effect.result(provider.getChangeRequestActivity(reference))).toMatchObject({
595 _tag: "Failure",
596 failure: {
597 _tag: "PullRequestProviderError",
598 provider: "gitlab",
599 operation: "getChangeRequestActivity",
600 reason,
601 detail: error.detail,
602 cause: error,
603 },
604 });
605 }),
606 );
607
608 it.effect(
609 "turns an open overview discussion into a finding and a thread apart from file threads",
610 () =>
611 Effect.gen(function* () {
612 const finding = { ...comment, id: "10", body: "Mention the flag in the README" };
613 const reply = { ...comment, id: "11", body: "Will do" };
614 const thread = {
615 side: "right",
616 isResolved: false,
617 isOutdated: false,
618 comments: [],
619 } as const;
620 const provider = yield* make.pipe(
621 Effect.provide(
622 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
623 ...reads,
624 listNotes: () =>
625 Effect.succeed({ comments: [comment, finding, reply], truncated: false }),
626 listDiscussions: () =>
627 Effect.succeed({
628 threads: [
629 { ...thread, id: "overview", path: null, line: null },
630 { ...thread, id: "file", path: "src/a.ts", line: 3 },
631 ],
632 diffRefsByThreadId: new Map(),
633 overviewFindingIds: ["10"],
634 truncated: false,
635 }),
636 }),
637 ),
638 );
639
640 const { comments, reviewThreads, overviewThreads } =
641 yield* provider.getChangeRequestActivity(reference);
642
643 // Clients that require a thread path must never receive one without it.
644 expect(reviewThreads.map(({ id }) => id)).toEqual(["file"]);
645 expect(overviewThreads?.map(({ id }) => id)).toEqual(["overview"]);
646
647 expect(comments.map((item) => [item.id, item.kind])).toEqual([
648 ["42", "issue-comment"],
649 ["10", "review-comment"],
650 ["11", "issue-comment"],
651 ]);
652 }),
653 );
654
655 it.effect("dates edited comments in the conversation and in threads", () =>
656 Effect.gen(function* () {
657 const editedAt = "2026-07-02T00:00:00Z";
658 const provider = yield* make.pipe(
659 Effect.provide(
660 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
661 ...reads,
662 listDiscussions: () =>
663 Effect.succeed({
664 threads: [
665 {
666 id: "d1",
667 path: "src/a.ts",
668 line: 1,
669 side: "right" as const,
670 isResolved: false,
671 isOutdated: false,
672 comments: [comment],
673 },
674 ],
675 diffRefsByThreadId: new Map(),
676 overviewFindingIds: [],
677 truncated: false,
678 }),
679 listReactions: () =>
680 Effect.succeed({
681 reactions: [],
682 reactionsByNoteId: new Map(),
683 editedAtByNoteId: new Map([[comment.id, editedAt]]),
684 botLogins: new Set<string>(),
685 }),
686 }),
687 ),
688 );
689
690 const activity = yield* provider.getChangeRequestActivity(reference);
691
692 expect(activity.comments[0]?.editedAt).toBe(editedAt);
693 expect(activity.reviewThreads[0]?.comments[0]?.editedAt).toBe(editedAt);
694 }),
695 );
696
697 it.effect("links comments and thread comments to their note on the merge request page", () =>
698 Effect.gen(function* () {
699 const provider = yield* make.pipe(
700 Effect.provide(
701 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
702 ...reads,
703 listDiscussions: () =>
704 Effect.succeed({
705 threads: [
706 {
707 id: "d1",
708 path: "src/a.ts",
709 line: 1,
710 side: "right" as const,
711 isResolved: false,
712 isOutdated: false,
713 comments: [comment],
714 },
715 ],
716 diffRefsByThreadId: new Map(),
717 overviewFindingIds: [],
718 truncated: false,
719 }),
720 }),
721 ),
722 );
723
724 const activity = yield* provider.getChangeRequestActivity(reference);
725
726 expect(activity.comments[0]?.url).toBe(`${webUrl}#note_42`);
727 expect(activity.reviewThreads[0]?.comments[0]?.url).toBe(`${webUrl}#note_42`);
728 }),
729 );
730
731 it.effect("marks a thread outdated once the merge request's diff moves past it", () =>
732 Effect.gen(function* () {
733 let detailReads = 0;
734 const thread = (id: string) => ({
735 id,
736 path: "src/a.ts",
737 line: 3,
738 side: "right" as const,
739 isResolved: false,
740 isOutdated: false,
741 comments: [],
742 });
743 const provider = yield* make.pipe(
744 Effect.provide(
745 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
746 ...reads,
747 getMergeRequestDetail: () =>
748 Effect.map(reads.getMergeRequestDetail(), (detail) => ({
749 ...detail,
750 diffRefs: ++detailReads === 1 ? { ...currentRefs, headSha: "head1" } : currentRefs,
751 })),
752 listDiscussions: () =>
753 Effect.succeed({
754 threads: [thread("current"), thread("moved"), thread("unplaced")],
755 diffRefsByThreadId: new Map([
756 ["current", currentRefs],
757 ["moved", { ...currentRefs, headSha: "head1" }],
758 ]),
759 overviewFindingIds: [],
760 truncated: false,
761 }),
762 }),
763 ),
764 );
765
766 const checks = provider.getChangeRequestChecks;
767 if (!checks) throw new Error("missing getChangeRequestChecks");
768 yield* checks(reference);
769 const { reviewThreads } = yield* provider.getChangeRequestActivity(reference);
770 expect(reviewThreads.map(({ id, isOutdated }) => [id, isOutdated])).toEqual([
771 ["current", false],
772 ["moved", true],
773 ["unplaced", false],
774 ]);
775 }),
776 );
777
778 it.effect("keeps comments and commits when optional discussions, reactions and links fail", () =>
779 Effect.gen(function* () {
780 const provider = yield* make.pipe(
781 Effect.provide(
782 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
783 ...reads,
784 listDiscussions: () =>
785 Effect.fail(
786 new GitLabPullRequestCli.GitLabMergeRequestReadError({
787 command: "glab",
788 cwd: "/w",
789 operation: "listDiscussions",
790 cause: null,
791 }),
792 ),
793 listReactions: () => Effect.fail(new GitLabCli.GitLabCliCommandError(context)),
794 getMergeRequestDetail: () => Effect.fail(new GitLabCli.GitLabCliCommandError(context)),
795 }),
796 ),
797 );
798
799 expect(yield* provider.getChangeRequestActivity(reference)).toEqual({
800 comments: [{ ...comment, reactions: [] }],
801 commentCount: 1,
802 commentsTruncated: true,
803 reviewThreads: [],
804 overviewThreads: [],
805 reactions: [],
806 commits: [commit],
807 });
808 }),
809 );
810
811 it.effect("flags comments by bot authors as bots, in the conversation and in threads", () =>
812 Effect.gen(function* () {
813 const bot = { login: "project_1_bot_abc", name: "Review bot", avatarUrl: null };
814 const human = { login: "julius", name: null, avatarUrl: null };
815 const provider = yield* make.pipe(
816 Effect.provide(
817 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
818 ...reads,
819 listNotes: () =>
820 Effect.succeed({
821 comments: [
822 { ...comment, author: bot },
823 { ...comment, id: "43", author: human },
824 ],
825 truncated: false,
826 }),
827 listDiscussions: () =>
828 Effect.succeed({
829 threads: [
830 {
831 id: "d1",
832 path: "a.ts",
833 line: 1,
834 side: "right" as const,
835 isResolved: false,
836 isOutdated: false,
837 comments: [
838 { id: "44", author: bot, body: "x", createdAt: comment.createdAt, url: null },
839 ],
840 },
841 ],
842 diffRefsByThreadId: new Map(),
843 overviewFindingIds: [],
844 truncated: false,
845 }),
846 listReactions: () =>
847 Effect.succeed({
848 reactions: [],
849 reactionsByNoteId: new Map(),
850 editedAtByNoteId: new Map(),
851 botLogins: new Set([bot.login.toUpperCase()]),
852 }),
853 }),
854 ),
855 );
856
857 const activity = yield* provider.getChangeRequestActivity(reference);
858 expect(activity.comments.map((entry) => entry.author?.isBot)).toEqual([true, undefined]);
859 expect(activity.reviewThreads[0]?.comments[0]?.author?.isBot).toBe(true);
860 }),
861 );
862});
863
864describe("review decisions", () => {
865 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
866 const item = {
867 number: 7,
868 title: "Merge request 7",
869 url: "https://gitlab.com/acme/web/-/merge_requests/7",
870 author: null,
871 headBranch: "feat/page",
872 baseBranch: "main",
873 state: "open" as const,
874 isDraft: false,
875 mergeability: "mergeable" as const,
876 additions: 0,
877 deletions: 0,
878 createdAt: "2026-07-01T00:00:00Z",
879 updatedAt: "2026-07-02T00:00:00Z",
880 reviewRequestLogins: [],
881 labels: [],
882 };
883 const detail = {
884 ...item,
885 body: "",
886 changedFiles: 1,
887 mergedAt: null,
888 closedAt: null,
889 reviewers: [],
890 checks: [],
891 viewerCanMerge: true,
892 reviewerIds: [],
893 reviewerUsers: [],
894 };
895 const providerWith = (
896 getListStates: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getListStates"],
897 overrides: Partial<GitLabPullRequestCli.GitLabPullRequestCli["Service"]> = {},
898 ) =>
899 make.pipe(
900 Effect.provide(
901 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
902 supportsGraphqlList: () => Effect.succeed(false),
903 listMergeRequests: () =>
904 Effect.succeed({
905 items: [item, { ...item, number: 8 }],
906 truncated: false,
907 cursorAdvance: 2,
908 }),
909 ...overrides,
910 getMergeRequestDetail: () => Effect.succeed(detail),
911 getListStates,
912 listMergeRequestStats: () =>
913 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
914 }),
915 ),
916 );
917 const listing = {
918 cwd: "/w",
919 repository: "acme/web",
920 host: "gitlab.com",
921 state: "open" as const,
922 involvement: "all" as const,
923 viewer: "julius",
924 limit: 2,
925 };
926
927 it.effect(
928 "puts GitLab's approval and pipeline state on listed and summarized merge requests",
929 () =>
930 Effect.gen(function* () {
931 const provider = yield* providerWith((input) => {
932 expect(input.host).toBe(reference.host);
933 return Effect.succeed(
934 new Map([
935 [7, { reviewDecision: "approved" as const, checksState: "failing" as const }],
936 [8, { reviewDecision: null, checksState: null }],
937 ]),
938 );
939 });
940 const listed = yield* provider.listChangeRequests(listing);
941 assert.isDefined(provider.getChangeRequestSummary);
942 const summary = yield* provider.getChangeRequestSummary(reference);
943
944 expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
945 "approved",
946 null,
947 ]);
948 expect(listed.items.map(({ checksState }) => checksState)).toEqual(["failing", null]);
949 expect(summary.reviewDecision).toBe("approved");
950 expect(summary.checksState).toBe("failing");
951 expect(summary.additions).toBe(40);
952 expect(summary.deletions).toBe(2);
953 }),
954 );
955
956 it.effect(
957 "lists through GraphQL where the host takes it, using the states that read carried",
958 () =>
959 Effect.gen(function* () {
960 const graphqlFlags: Array<boolean | undefined> = [];
961 let versionReads = 0;
962 const providerReading = (
963 supportsGraphqlList: Effect.Effect<
964 boolean,
965 GitLabPullRequestCli.GitLabPullRequestCliError
966 >,
967 ) =>
968 providerWith(() => Effect.die("a GraphQL page carries its own states"), {
969 supportsGraphqlList: () => {
970 versionReads += 1;
971 return supportsGraphqlList;
972 },
973 listMergeRequests: (input) => {
974 graphqlFlags.push(input.graphql);
975 return Effect.succeed({
976 items: [item],
977 truncated: true,
978 cursorAdvance: 1,
979 resumeAfter: "eyJpZCI6IjcifQ",
980 listStates: new Map([
981 [7, { reviewDecision: "changes-requested" as const, checksState: null }],
982 ]),
983 });
984 },
985 });
986 const listedWith = (
987 supportsGraphqlList: Effect.Effect<
988 boolean,
989 GitLabPullRequestCli.GitLabPullRequestCliError
990 >,
991 ) =>
992 providerReading(supportsGraphqlList).pipe(
993 Effect.flatMap((provider) => provider.listChangeRequests(listing)),
994 );
995
996 const listed = yield* listedWith(Effect.succeed(true));
997 expect(listed).toMatchObject({ resumeAfter: "eyJpZCI6IjcifQ", truncated: true });
998 expect(listed).not.toHaveProperty("listStates");
999 expect(listed.items[0]?.reviewDecision).toBe("changes-requested");
1000
1001 // An unreadable version leaves the list on REST rather than failing it, and stays known.
1002 const unreadable = yield* providerReading(
1003 Effect.fail(
1004 new GitLabPullRequestCli.GitLabMergeRequestReadError({
1005 command: "glab",
1006 cwd: "/w",
1007 operation: "supportsGraphqlList",
1008 cause: null,
1009 }),
1010 ),
1011 );
1012 versionReads = 0;
1013 yield* unreadable.listChangeRequests(listing);
1014 yield* unreadable.listChangeRequests(listing);
1015 expect(graphqlFlags).toEqual([true, false, false]);
1016 expect(versionReads).toBe(1);
1017 }),
1018 );
1019
1020 it.effect.each([
1021 {
1022 failure: "a failed read",
1023 error: new GitLabPullRequestCli.GitLabMergeRequestReadError({
1024 command: "glab",
1025 cwd: "/w",
1026 operation: "getListStates",
1027 cause: null,
1028 }),
1029 },
1030 {
1031 failure: "a rate limit",
1032 error: new GitLabCli.GitLabCliRateLimitError({
1033 operation: "execute",
1034 command: "glab",
1035 cwd: "/w",
1036 cause: null,
1037 }),
1038 },
1039 ])("keeps rows and summaries with an unknown decision after $failure", ({ error }) =>
1040 Effect.gen(function* () {
1041 const provider = yield* providerWith(() => Effect.fail(error));
1042 const listed = yield* provider.listChangeRequests(listing);
1043 assert.isDefined(provider.getChangeRequestSummary);
1044 const summary = yield* provider.getChangeRequestSummary(reference);
1045
1046 expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
1047 undefined,
1048 undefined,
1049 ]);
1050 expect(summary.reviewDecision).toBeUndefined();
1051 }),
1052 );
1053});