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