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

GitLabPullRequestProvider.test.ts

1,411 lines49.6 KB

1import { assert, describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as TestClock from "effect/testing/TestClock";
6​
7import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8​
9import * as GitLabCli from "./GitLabCli.ts";
10import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
11import { gitLabViewerPermissions, make } from "./GitLabPullRequestProvider.ts";
12​
13it.effect.each(["merge", "disable-auto-merge"] as const)(
14 "keeps reads and %s on the selected host when glab prefers another remote",
15 (action) =>
16 Effect.gen(function* () {
17 const selectedHost = "gitlab.example.test:8443";
18 const otherHost = "other.gitlab.example.test";
19 const readHosts: string[] = [];
20 const mergedHosts: string[] = [];
21 const native = yield* GitLabCli.make.pipe(
22 Effect.provide(
23 TestSourceControlHost.layer({
24 process: {
25 run: (input) => {
26 // glab prefers a remote named `gitlab` to `origin`. The checkout's
27 // selected repository must still own every request and mutation.
28 const host = input.env?.GITLAB_HOST ?? otherHost;
29 const path = input.args[1];
30 const mutation =
31 input.args[0] === "mr" || (input.args.includes("POST") && path !== "graphql");
32 if (mutation) mergedHosts.push(host);
33 else readHosts.push(host);
34 const response = mutation
35 ? {}
36 : path === "graphql"
37 ? {
38 data: {
39 project: {
40 mergeRequests: {
41 nodes: [
42 { iid: "7", diffStatsSummary: { additions: 2, deletions: 1 } },
43 ],
44 },
45 mergeRequest: {
46 userPermissions: { adminMergeRequest: true },
47 diffStatsSummary: { fileCount: 1 },
48 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
49 },
50 },
51 },
52 }
53 : path?.includes("merge_requests/")
54 ? {
55 iid: 7,
56 title: "Merge request 7",
57 web_url: `https://${host}/acme/web/-/merge_requests/7`,
58 source_branch: "feature",
59 target_branch: "main",
60 created_at: "2026-07-01T00:00:00Z",
61 updated_at: "2026-07-02T00:00:00Z",
62 user: { can_merge: true },
63 diff_refs: {
64 head_sha: "a".repeat(40),
65 base_sha: "b".repeat(40),
66 start_sha: "b".repeat(40),
67 },
68 }
69 : path === "user"
70 ? { username: "reviewer" }
71 : path?.includes("/labels?") || path?.includes("/users?")
72 ? []
73 : { merge_method: "merge", squash_option: "default_off" };
74 return Effect.succeed(
75 TestSourceControlHost.processOutput(JSON.stringify(response)),
76 );
77 },
78 },
79 }).pipe(Layer.merge(FileSystem.layerNoop({}))),
80 ),
81 );
82 const cli = yield* GitLabPullRequestCli.make.pipe(
83 Effect.provideService(GitLabCli.GitLabCli, native),
84 );
85 const provider = yield* make.pipe(
86 Effect.provideService(GitLabPullRequestCli.GitLabPullRequestCli, cli),
87 );
88 const reference = {
89 cwd: "/repo",
90 repository: "acme/web",
91 host: selectedHost,
92 number: 7,
93 };
94 const detail = yield* provider.getChangeRequest(reference);
95 expect({ additions: detail.additions, deletions: detail.deletions }).toEqual({
96 additions: 2,
97 deletions: 1,
98 });
99 assert.isDefined(provider.getChangeRequestSummary);
100 expect((yield* provider.getChangeRequestSummary(reference)).additions).toBe(2);
101 assert.isDefined(provider.listChangeRequestStats);
102 expect(
103 yield* provider.listChangeRequestStats({ ...reference, changeRequests: [reference] }),
104 ).toEqual([{ repository: reference.repository, number: 7, additions: 2, deletions: 1 }]);
105 assert.isDefined(provider.getFileStats);
106 expect(yield* provider.getFileStats(reference)).toEqual({
107 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
108 truncated: false,
109 });
110 expect(yield* provider.getViewer(reference)).toBe("reviewer");
111 assert.isDefined(provider.listRepositoryLabels);
112 yield* provider.listRepositoryLabels(reference);
113 assert.isDefined(provider.searchRepositoryAuthors);
114 yield* provider.searchRepositoryAuthors(reference);
115 yield* provider.runAction({ ...reference, action });
116​
117 expect(readHosts).toEqual(Array(action === "merge" ? 14 : 13).fill(selectedHost));
118 expect({ url: detail.url, mutatedHosts: mergedHosts }).toEqual({
119 url: `https://${selectedHost}/acme/web/-/merge_requests/7`,
120 mutatedHosts: [selectedHost],
121 });
122 }),
123);
124​
125it.effect(
126 "reads and retries concrete GitLab jobs on their project and refreshes cached checks",
127 () =>
128 Effect.gen(function* () {
129 const reference = {
130 cwd: "/repo",
131 repository: "target/web",
132 host: "gitlab.example.test:8443",
133 number: 7,
134 };
135 const root = `https://${reference.host}/gitlab`;
136 const job = { name: "test / unit", url: `${root}/fork/team/web/-/jobs/11` };
137 const external = { name: "test / external", url: `${root}/fork/team/web/-/jobs/15` };
138 const long = { name: "large log", url: `${root}/target/web/-/jobs/12`, nativeId: "42/12" };
139 const rejected = { name: "denied", url: `${root}/target/web/-/jobs/13`, nativeId: "42/13" };
140 const limited = { name: "limited", url: `${root}/target/web/-/jobs/14`, nativeId: "42/14" };
141 const empty = { name: "empty log", url: `${root}/target/web/-/jobs/16`, nativeId: "42/16" };
142 const unsupported = [
143 { name: "stage", url: `${root}/target/web/-/pipelines/9` },
144 { name: "external", url: "https://other.example.test/target/web/-/jobs/11" },
145 { name: "other port", url: "https://gitlab.example.test/target/web/-/jobs/11" },
146 { name: "malformed", url: `${root}/target/%zz/-/jobs/15` },
147 { name: "invalid identity", url: job.url, nativeId: "42/11/retry" },
148 { name: "no URL", url: null },
149 ];
150 const commands: Array<{
151 readonly host: string | undefined;
152 readonly args: ReadonlyArray<string>;
153 }> = [];
154 let status = "FAILED";
155 let jobId = 11;
156 const cli = yield* GitLabPullRequestCli.make.pipe(
157 Effect.provide(
158 Layer.mock(GitLabCli.GitLabCli)({
159 execute: (input) => {
160 const path = input.args[1] ?? "";
161 if (path.includes("/jobs/")) {
162 commands.push({ host: input.host, args: input.args });
163 const context = {
164 operation: "execute" as const,
165 command: "glab" as const,
166 cwd: input.cwd,
167 cause: null,
168 };
169 if (path.includes("/jobs/14/")) {
170 return Effect.fail(new GitLabCli.GitLabCliRateLimitError(context));
171 }
172 if (path.includes("/jobs/13/")) {
173 return Effect.fail(new GitLabCli.GitLabCliCommandError(context));
174 }
175 if (path.includes("/jobs/16/")) {
176 return Effect.succeed(TestSourceControlHost.processOutput(""));
177 }
178 if (path.endsWith("/retry")) {
179 status = "PENDING";
180 jobId = 21;
181 return Effect.succeed(
182 TestSourceControlHost.processOutput('{"id":21,"status":"pending"}'),
183 );
184 }
185 return Effect.succeed({
186 ...TestSourceControlHost.processOutput("first\nsecond\nthird\n"),
187 stdoutTruncated: path.includes("/jobs/12/"),
188 });
189 }
190 if (path === "graphql") {
191 return Effect.succeed(
192 TestSourceControlHost.processOutput(
193 JSON.stringify({
194 data: {
195 project: {
196 mergeRequest: input.stdin?.includes("stages(first")
197 ? {
198 headPipeline: {
199 path: "/gitlab/fork/team/web/-/pipelines/9",
200 project: { id: "gid://gitlab/Project/42" },
201 stages: {
202 nodes: [
203 {
204 name: "test",
205 status,
206 jobs: {
207 nodes: [
208 {
209 id: `gid://gitlab/Ci::Build/${jobId}`,
210 name: "unit",
211 status,
212 webPath: `/gitlab/fork/team/web/-/jobs/${jobId}`,
213 },
214 {
215 id: "gid://gitlab/GenericCommitStatus/15",
216 name: "external",
217 status: "FAILED",
218 webPath: "/gitlab/fork/team/web/-/jobs/15",
219 },
220 ],
221 },
222 },
223 ],
224 },
225 },
226 }
227 : { userPermissions: { adminMergeRequest: false } },
228 },
229 },
230 }),
231 ),
232 );
233 }
234 return Effect.succeed(
235 TestSourceControlHost.processOutput(
236 JSON.stringify({
237 iid: 7,
238 title: "Merge request",
239 web_url: `${root}/target/web/-/merge_requests/7`,
240 source_branch: "feature",
241 target_branch: "main",
242 state: "opened",
243 created_at: "2026-07-01T00:00:00Z",
244 updated_at: "2026-07-02T00:00:00Z",
245 head_pipeline: {
246 id: 9,
247 project_id: 42,
248 status: status.toLowerCase(),
249 web_url: `${root}/fork/team/web/-/pipelines/9`,
250 },
251 }),
252 ),
253 );
254 },
255 }),
256 ),
257 );
258 const provider = yield* make.pipe(
259 Effect.provideService(GitLabPullRequestCli.GitLabPullRequestCli, cli),
260 );
261 assert.isDefined(provider.getCheckLogs);
262 assert.isDefined(provider.rerunChecks);
263 assert.isDefined(provider.getChangeRequestChecks);
264 const { checks } = yield* provider.getChangeRequestChecks(reference);
265 expect(checks).toMatchObject([
266 { ...job, status: "failure", nativeId: "42/11" },
267 { ...external, status: "failure" },
268 ]);
269 const [nativeJob, externalStatus] = checks;
270 assert.isDefined(nativeJob);
271 assert.isDefined(externalStatus);
272 expect(externalStatus).not.toHaveProperty("nativeId");
273 const unavailable = [externalStatus, ...unsupported];
274​
275 const logs = yield* provider.getCheckLogs({
276 ...reference,
277 checks: [nativeJob, long, rejected, empty, ...unavailable],
278 tailLines: 2,
279 });
280 expect(logs.slice(0, 4)).toMatchObject([
281 { ...job, log: "second\nthird", truncated: true, detail: null },
282 {
283 name: long.name,
284 url: long.url,
285 log: "second\nthird",
286 truncated: true,
287 detail: expect.stringContaining("too large"),
288 },
289 {
290 name: rejected.name,
291 url: rejected.url,
292 log: null,
293 truncated: false,
294 detail: expect.stringContaining("failed"),
295 },
296 {
297 name: empty.name,
298 url: empty.url,
299 log: null,
300 truncated: false,
301 detail: "GitLab returned an empty log for this job.",
302 },
303 ]);
304 expect(logs.every((log) => !("nativeId" in log))).toBe(true);
305 expect(logs.slice(4)).toEqual(
306 unavailable.map(({ name, url }) => ({
307 name,
308 url,
309 log: null,
310 truncated: false,
311 detail: expect.any(String),
312 })),
313 );
314​
315 const reruns = yield* provider.rerunChecks({
316 ...reference,
317 checks: [nativeJob, { ...nativeJob, url: `${job.url}#trace` }, rejected, ...unavailable],
318 });
319 expect(reruns.map((item) => item.rerun)).toEqual([
320 true,
321 true,
322 false,
323 ...unavailable.map(() => false),
324 ]);
325 expect(commands.filter(({ args }) => args.includes("POST")).map(({ args }) => args)).toEqual([
326 ["api", "projects/42/jobs/11/retry", "--method", "POST"],
327 ["api", "projects/42/jobs/13/retry", "--method", "POST"],
328 ]);
329 expect(
330 commands
331 .filter(({ args }) => !args.includes("POST"))
332 .map(({ args }) => args[1])
333 .sort(),
334 ).toEqual([
335 "projects/42/jobs/11/trace",
336 "projects/42/jobs/12/trace",
337 "projects/42/jobs/13/trace",
338 "projects/42/jobs/16/trace",
339 ]);
340 expect(commands.every((command) => command.host === reference.host)).toBe(true);
341 expect((yield* provider.getChangeRequestChecks(reference)).checks).toMatchObject([
342 { ...job, url: `${root}/fork/team/web/-/jobs/21`, status: "pending", nativeId: "42/21" },
343 { ...external, status: "failure" },
344 ]);
345​
346 expect(
347 yield* Effect.result(
348 provider.getCheckLogs({ ...reference, checks: [limited], tailLines: 2 }),
349 ),
350 ).toMatchObject({ _tag: "Failure", failure: { reason: "rate-limited" } });
351 expect(
352 yield* Effect.result(provider.rerunChecks({ ...reference, checks: [limited] })),
353 ).toMatchObject({ _tag: "Failure", failure: { reason: "rate-limited" } });
354 }),
355);
356​
357it.effect.each(
358 (["stages", "bridges"] as const).flatMap((read) => [
359 { read, errorClass: GitLabCli.GitLabCliRateLimitError, reason: "rate-limited" },
360 { read, errorClass: GitLabCli.GitLabCliAuthenticationError, reason: "unauthenticated" },
361 { read, errorClass: GitLabCli.GitLabCliUnavailableError, reason: "missing-tool" },
362 ]),
363)(
364 "propagates $reason from the $read check read without caching it",
365 ({ read, errorClass, reason }) =>
366 Effect.gen(function* () {
367 const reference = {
368 cwd: "/repo",
369 repository: "acme/web",
370 host: "gitlab.example.test:8443",
371 number: 7,
372 };
373 const context = {
374 operation: "execute" as const,
375 command: "glab" as const,
376 cwd: reference.cwd,
377 cause: null,
378 };
379 const failure = new errorClass(context);
380 const bridgeHosts: Array<string | undefined> = [];
381 let unavailable = true;
382 let stageReads = 0;
383 const cli = yield* GitLabPullRequestCli.make.pipe(
384 Effect.provide(
385 Layer.mock(GitLabCli.GitLabCli)({
386 execute: (input) => {
387 const path = input.args[1] ?? "";
388 if (path === "graphql" && input.stdin?.includes("stages(first")) {
389 stageReads++;
390 if (unavailable) {
391 return Effect.fail(
392 read === "stages" ? failure : new GitLabCli.GitLabCliCommandError(context),
393 );
394 }
395 return Effect.succeed(
396 TestSourceControlHost.processOutput(
397 JSON.stringify({
398 data: {
399 project: {
400 mergeRequest: {
401 headPipeline: {
402 project: { id: "gid://gitlab/Project/42" },
403 stages: {
404 nodes: [
405 {
406 name: "test",
407 status: "failed",
408 jobs: {
409 nodes: [
410 {
411 id: "gid://gitlab/Ci::Build/11",
412 name: "unit",
413 status: "FAILED",
414 },
415 ],
416 },
417 },
418 ],
419 },
420 },
421 },
422 },
423 },
424 }),
425 ),
426 );
427 }
428 if (path.includes("/bridges?")) {
429 bridgeHosts.push(input.host);
430 return read === "bridges"
431 ? Effect.fail(failure)
432 : Effect.succeed(TestSourceControlHost.processOutput("[]"));
433 }
434 return Effect.succeed(
435 TestSourceControlHost.processOutput(
436 JSON.stringify(
437 path === "graphql"
438 ? {
439 data: {
440 project: {
441 mergeRequest: { userPermissions: { adminMergeRequest: false } },
442 },
443 },
444 }
445 : {
446 iid: 7,
447 title: "Merge request",
448 web_url: `https://${reference.host}/acme/web/-/merge_requests/7`,
449 source_branch: "feature",
450 target_branch: "main",
451 state: "opened",
452 created_at: "2026-07-01T00:00:00Z",
453 updated_at: "2026-07-02T00:00:00Z",
454 head_pipeline: { id: 9, project_id: 42, status: "failed" },
455 },
456 ),
457 ),
458 );
459 },
460 }),
461 ),
462 );
463 const provider = yield* make.pipe(
464 Effect.provideService(GitLabPullRequestCli.GitLabPullRequestCli, cli),
465 );
466 assert.isDefined(provider.getChangeRequestChecks);
467 expect(yield* Effect.result(provider.getChangeRequestChecks(reference))).toMatchObject({
468 _tag: "Failure",
469 failure: { reason },
470 });
471 expect(bridgeHosts).toEqual(read === "bridges" ? [reference.host] : []);
472​
473 // A failed lookup must not be cached as a successful, aggregate-only check read.
474 unavailable = false;
475 expect((yield* provider.getChangeRequestChecks(reference)).checks).toMatchObject([
476 { name: "test / unit", nativeId: "42/11", status: "failure" },
477 ]);
478 expect(stageReads).toBe(2);
479 }),
480);
481​
482describe("gitLabViewerPermissions", () => {
483 it("offers everything to a viewer GitLab says can merge", () => {
484 expect(
485 gitLabViewerPermissions({
486 viewerCanMerge: true,
487 viewerCanDeleteBranch: true,
488 viewerCanEditLabels: true,
489 }),
490 ).toEqual({
491 actions: [
492 "merge",
493 "ready",
494 "draft",
495 "close",
496 "reopen",
497 "update-branch",
498 "enable-auto-merge",
499 "disable-auto-merge",
500 "revert",
501 "delete-branch",
502 ],
503 comment: true,
504 resolve: true,
505 verdicts: ["comment", "approve", "request-changes"],
506 requestReviewers: true,
507 maintainerEdits: false,
508 labels: true,
509 updateMethods: ["rebase"],
510 });
511 });
512​
513 it("keeps merge, now and later, from a viewer GitLab says cannot", () => {
514 expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
515 actions: ["ready", "draft", "close", "reopen"],
516 comment: true,
517 resolve: true,
518 verdicts: ["comment", "approve", "request-changes"],
519 requestReviewers: true,
520 maintainerEdits: false,
521 labels: false,
522 });
523 });
524});
525​
526describe("getChangeRequest base freshness", () => {
527 const detail = {
528 number: 7,
529 title: "Merge request 7",
530 url: "https://gitlab.com/acme/web/-/merge_requests/7",
531 author: null,
532 headBranch: "feat/page",
533 baseBranch: "main",
534 state: "open" as const,
535 isDraft: false,
536 mergeability: "mergeable" as const,
537 additions: 0,
538 deletions: 0,
539 createdAt: "2026-07-01T00:00:00Z",
540 updatedAt: "2026-07-02T00:00:00Z",
541 reviewRequestLogins: [],
542 labels: [],
543 body: "",
544 changedFiles: 1,
545 mergedAt: null,
546 closedAt: null,
547 reviewers: [],
548 checks: [],
549 viewerCanMerge: true,
550 reviewerIds: [],
551 reviewerUsers: [],
552 };
553​
554 it.effect.each(["getChangeRequestPreview", "getChangeRequestSummary"] as const)(
555 "%s preserves merge request fields without fetching project settings or fork permissions",
556 (operation) =>
557 Effect.gen(function* () {
558 const detailInputs: Array<{ readonly maintainerEdits?: boolean }> = [];
559 const provider = yield* make.pipe(
560 Effect.provide(
561 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
562 getMergeRequestDetail: (input) => {
563 detailInputs.push(input);
564 return Effect.succeed(detail);
565 },
566 getListStates: () => Effect.succeed(new Map()),
567​
568 listMergeRequestStats: () => Effect.succeed([]),
569 }),
570 ),
571 );
572 const read = provider[operation];
573 assert.isDefined(read);
574 expect(
575 yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }),
576 ).toEqual(detail);
577 expect(detailInputs.map((input) => input.maintainerEdits)).toEqual([false]);
578 }),
579 );
580​
581 const readWith = (
582 divergence: { readonly divergedCommits?: number },
583 stats: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["listMergeRequestStats"] = () =>
584 Effect.succeed([]),
585 ) =>
586 Effect.gen(function* () {
587 const provider = yield* make;
588 return yield* provider.getChangeRequest({
589 cwd: "/w",
590 repository: "acme/web",
591 host: "gitlab.com",
592 number: 7,
593 });
594 }).pipe(
595 Effect.provide(
596 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
597 getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
598 getProjectMergeCapabilities: () =>
599 Effect.succeed({ merge: true, squash: true, rebase: true }),
600 listMergeRequestStats: stats,
601 }),
602 ),
603 );
604​
605 it.effect("reads a counted divergence as a branch that has fallen behind", () =>
606 Effect.gen(function* () {
607 const changeRequest = yield* readWith({ divergedCommits: 3 });
608​
609 expect(changeRequest.baseComparison).toBe("behind");
610 expect(changeRequest.behindBy).toBe(3);
611 }),
612 );
613​
614 it.effect("says nothing at all where GitLab counted nothing", () =>
615 Effect.gen(function* () {
616 const changeRequest = yield* readWith({});
617​
618 expect(changeRequest.baseComparison).toBe("unknown");
619 expect(changeRequest.behindBy).toBeUndefined();
620 }),
621 );
622​
623 it.effect("fills in the line counts the REST detail leaves out", () =>
624 Effect.gen(function* () {
625 const changeRequest = yield* readWith({}, () =>
626 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
627 );
628​
629 expect(changeRequest.additions).toBe(40);
630 expect(changeRequest.deletions).toBe(2);
631 }),
632 );
633​
634 it.effect("reports an unauthenticated line count read instead of a detail without counts", () =>
635 Effect.gen(function* () {
636 const result = yield* Effect.result(
637 readWith({}, () =>
638 Effect.fail(
639 new GitLabCli.GitLabCliAuthenticationError({
640 operation: "execute",
641 command: "glab",
642 cwd: "/w",
643 cause: null,
644 }),
645 ),
646 ),
647 );
648​
649 expect(result).toMatchObject({
650 _tag: "Failure",
651 failure: { _tag: "PullRequestProviderError", reason: "unauthenticated" },
652 });
653 }),
654 );
655​
656 it.effect("gives linked threads line counts without reading the merge settings", () =>
657 Effect.gen(function* () {
658 const summary = yield* Effect.gen(function* () {
659 const provider = yield* make;
660 const read = provider.getChangeRequestSummary;
661 if (read === undefined) return yield* Effect.die("summary read missing");
662 return yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 });
663 }).pipe(
664 Effect.provide(
665 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
666 getMergeRequestDetail: () => Effect.succeed(detail),
667 getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),
668 getListStates: () => Effect.succeed(new Map()),
669 listMergeRequestStats: () =>
670 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
671 }),
672 ),
673 );
674​
675 expect(summary.additions).toBe(40);
676 expect(summary.deletions).toBe(2);
677 }),
678 );
679});
680​
681describe("merge request reads", () => {
682 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
683 const detail = {
684 number: 7,
685 title: "Merge request 7",
686 url: "https://gitlab.com/acme/web/-/merge_requests/7",
687 author: null,
688 headBranch: "feat/page",
689 baseBranch: "main",
690 state: "open" as const,
691 isDraft: false,
692 mergeability: "mergeable" as const,
693 additions: 0,
694 deletions: 0,
695 createdAt: "2026-07-01T00:00:00Z",
696 updatedAt: "2026-07-02T00:00:00Z",
697 reviewRequestLogins: [],
698 labels: [],
699 body: "",
700 changedFiles: 1,
701 mergedAt: null,
702 closedAt: null,
703 reviewers: [],
704 checks: [],
705 viewerCanMerge: true,
706 reviewerIds: [],
707 reviewerUsers: [],
708 };
709​
710 const countingProvider = Effect.gen(function* () {
711 const calls = { detail: 0, mergeCapabilities: 0 };
712 const host = { viewerCanMerge: true };
713 const provider = yield* make.pipe(
714 Effect.provide(
715 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
716 listMergeRequestStats: () => Effect.succeed([]),
717 getListStates: () => Effect.succeed(new Map()),
718 getMergeRequestDetail: (input) =>
719 Effect.sync(() => {
720 calls.detail += 1;
721 return { ...detail, number: input.number, viewerCanMerge: host.viewerCanMerge };
722 }),
723 getProjectMergeCapabilities: () =>
724 Effect.sync(() => {
725 calls.mergeCapabilities += 1;
726 return { merge: true, squash: true, rebase: true };
727 }),
728 runMergeRequestAction: () => Effect.void,
729 setLabels: () => Effect.void,
730 }),
731 ),
732 );
733 const checks = provider.getChangeRequestChecks;
734 const forget = provider.forgetChangeRequestReads;
735 if (checks === undefined || forget === undefined) {
736 return yield* Effect.die("GitLab answers checks and forgets its reads");
737 }
738 return { provider, checks, forget, calls, host };
739 });
740​
741 it.effect("asks for a project's merge methods once across its merge requests", () =>
742 Effect.gen(function* () {
743 const { provider, calls } = yield* countingProvider;
744​
745 yield* provider.getChangeRequest(reference);
746 yield* provider.getChangeRequest(reference);
747 yield* provider.getChangeRequest({ ...reference, number: 8 });
748​
749 expect(calls.mergeCapabilities).toBe(1);
750 }),
751 );
752​
753 it.effect("answers checks from the merge request the detail just read", () =>
754 Effect.gen(function* () {
755 const { provider, checks, calls } = yield* countingProvider;
756​
757 yield* provider.getChangeRequest(reference);
758 yield* checks(reference);
759​
760 expect(calls.detail).toBe(1);
761​
762 const summary = provider.getChangeRequestSummary;
763 assert.isDefined(summary);
764 yield* summary(reference);
765 expect(calls.detail).toBe(2);
766 }),
767 );
768​
769 it.effect.each([
770 {
771 write: "runAction",
772 run: (provider: Effect.Success<typeof make>) =>
773 provider.runAction({ ...reference, action: "ready" }),
774 },
775 {
776 write: "setLabels",
777 run: (provider: Effect.Success<typeof make>) =>
778 provider.setLabels?.({ ...reference, labels: ["bug"], applied: true }) ?? Effect.void,
779 },
780 ])("reads a merge request again after $write", ({ run }) =>
781 Effect.gen(function* () {
782 const { provider, checks, calls } = yield* countingProvider;
783​
784 yield* provider.getChangeRequest(reference);
785 yield* run(provider);
786 yield* checks(reference);
787​
788 expect(calls.detail).toBe(2);
789 }),
790 );
791​
792 it.effect.each([{ cwd: "/other" }, { host: "other.gitlab.test" }])(
793 "does not share reads with %j",
794 (other) =>
795 Effect.gen(function* () {
796 const { provider, calls } = yield* countingProvider;
797​
798 yield* provider.getChangeRequest(reference);
799 yield* provider.getChangeRequest({ ...reference, ...other });
800 yield* provider.getChangeRequest(reference);
801 yield* provider.getChangeRequest({ ...reference, ...other });
802​
803 expect(calls).toEqual({ detail: 2, mergeCapabilities: 2 });
804 }),
805 );
806​
807 it.effect("reads a merge request again once a minute has passed", () =>
808 Effect.gen(function* () {
809 const { provider, calls } = yield* countingProvider;
810​
811 yield* provider.getChangeRequest(reference);
812 yield* TestClock.adjust("61 seconds");
813 yield* provider.getChangeRequest(reference);
814​
815 expect(calls.detail).toBe(2);
816 }),
817 );
818​
819 it.effect("answers viewer permissions from the host, not the page's read", () =>
820 Effect.gen(function* () {
821 const { provider, host } = yield* countingProvider;
822​
823 host.viewerCanMerge = false;
824 yield* provider.getChangeRequest(reference);
825 host.viewerCanMerge = true;
826 const granted = yield* provider.getViewerPermissions(reference);
827 host.viewerCanMerge = false;
828 const revoked = yield* provider.getViewerPermissions(reference);
829​
830 expect(granted.actions).toContain("merge");
831 expect(revoked.actions).not.toContain("merge");
832 }),
833 );
834​
835 it.effect("reads a merge request again once its reads are forgotten", () =>
836 Effect.gen(function* () {
837 const { provider, checks, forget, calls } = yield* countingProvider;
838 const other = { ...reference, repository: "acme/api" };
839​
840 yield* provider.getChangeRequest(reference);
841 yield* provider.getChangeRequest(other);
842 yield* forget({ repository: "ACME/web", number: 7 });
843 yield* checks(reference);
844 yield* checks(other);
845 expect(calls.detail).toBe(3);
846​
847 yield* forget({ repository: "acme/web" });
848 yield* checks(reference);
849 yield* forget();
850 yield* checks(other);
851 expect(calls.detail).toBe(5);
852 }),
853 );
854});
855​
856describe("optional activity reads", () => {
857 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
858 const comment = {
859 id: "42",
860 kind: "issue-comment" as const,
861 author: null,
862 body: "Keep this comment",
863 createdAt: "2026-07-01T00:00:00Z",
864 url: null,
865 path: null,
866 reviewState: null,
867 };
868 const commit = {
869 oid: "abc",
870 messageHeadline: "Keep this commit",
871 committedDate: "2026-07-01T00:00:00Z",
872 };
873 const webUrl = "https://git.acme.dev/acme/web/-/merge_requests/7";
874 const currentRefs = { baseSha: "base2", startSha: "start2", headSha: "head2" };
875 const reads = {
876 getMergeRequestDetail: () =>
877 Effect.succeed({
878 number: 7,
879 title: "Merge request 7",
880 url: webUrl,
881 author: null,
882 headBranch: "feat/page",
883 baseBranch: "main",
884 state: "open" as const,
885 isDraft: false,
886 mergeability: "mergeable" as const,
887 additions: 0,
888 deletions: 0,
889 createdAt: "2026-07-01T00:00:00Z",
890 updatedAt: "2026-07-02T00:00:00Z",
891 reviewRequestLogins: [],
892 labels: [],
893 body: "",
894 changedFiles: 1,
895 mergedAt: null,
896 closedAt: null,
897 reviewers: [],
898 checks: [],
899 viewerCanMerge: true,
900 reviewerIds: [],
901 reviewerUsers: [],
902 diffRefs: currentRefs,
903 }),
904 listNotes: () => Effect.succeed({ comments: [comment], truncated: false }),
905 listCommits: () => Effect.succeed([commit]),
906 listDiscussions: () =>
907 Effect.succeed({
908 threads: [],
909 diffRefsByThreadId: new Map(),
910 overviewFindingIds: [],
911 truncated: false,
912 }),
913 listReactions: () =>
914 Effect.succeed({
915 reactions: [],
916 reactionsByNoteId: new Map(),
917 editedAtByNoteId: new Map(),
918 botLogins: new Set<string>(),
919 }),
920 };
921 const context = {
922 operation: "execute" as const,
923 command: "glab" as const,
924 cwd: "/w",
925 cause: null,
926 };
927​
928 it.effect.each([
929 {
930 operation: "listNotes",
931 error: new GitLabCli.GitLabCliAuthenticationError(context),
932 reason: "unauthenticated",
933 },
934 {
935 operation: "listCommits",
936 error: new GitLabCli.GitLabCliUnavailableError(context),
937 reason: "missing-tool",
938 },
939 ] as const)(
940 "reports $reason instead of successful partial activity",
941 ({ operation, error, reason }) =>
942 Effect.gen(function* () {
943 const provider = yield* make.pipe(
944 Effect.provide(
945 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
946 ...reads,
947 [operation]: () => Effect.fail(error),
948 }),
949 ),
950 );
951​
952 expect(yield* Effect.result(provider.getChangeRequestActivity(reference))).toMatchObject({
953 _tag: "Failure",
954 failure: {
955 _tag: "PullRequestProviderError",
956 provider: "gitlab",
957 operation: "getChangeRequestActivity",
958 reason,
959 detail: error.detail,
960 cause: error,
961 },
962 });
963 }),
964 );
965​
966 it.effect(
967 "turns an open overview discussion into a finding and a thread apart from file threads",
968 () =>
969 Effect.gen(function* () {
970 const finding = { ...comment, id: "10", body: "Mention the flag in the README" };
971 const reply = { ...comment, id: "11", body: "Will do" };
972 const thread = {
973 side: "right",
974 isResolved: false,
975 isOutdated: false,
976 comments: [],
977 } as const;
978 const provider = yield* make.pipe(
979 Effect.provide(
980 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
981 ...reads,
982 listNotes: () =>
983 Effect.succeed({ comments: [comment, finding, reply], truncated: false }),
984 listDiscussions: () =>
985 Effect.succeed({
986 threads: [
987 { ...thread, id: "overview", path: null, line: null },
988 { ...thread, id: "file", path: "src/a.ts", line: 3 },
989 ],
990 diffRefsByThreadId: new Map(),
991 overviewFindingIds: ["10"],
992 truncated: false,
993 }),
994 }),
995 ),
996 );
997​
998 const { comments, reviewThreads, overviewThreads } =
999 yield* provider.getChangeRequestActivity(reference);
1000​
1001 // Clients that require a thread path must never receive one without it.
1002 expect(reviewThreads.map(({ id }) => id)).toEqual(["file"]);
1003 expect(overviewThreads?.map(({ id }) => id)).toEqual(["overview"]);
1004​
1005 expect(comments.map((item) => [item.id, item.kind])).toEqual([
1006 ["42", "issue-comment"],
1007 ["10", "review-comment"],
1008 ["11", "issue-comment"],
1009 ]);
1010 }),
1011 );
1012​
1013 it.effect("dates edited comments in the conversation and in threads", () =>
1014 Effect.gen(function* () {
1015 const editedAt = "2026-07-02T00:00:00Z";
1016 const provider = yield* make.pipe(
1017 Effect.provide(
1018 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
1019 ...reads,
1020 listDiscussions: () =>
1021 Effect.succeed({
1022 threads: [
1024 id: "d1",
1025 path: "src/a.ts",
1026 line: 1,
1027 side: "right" as const,
1028 isResolved: false,
1029 isOutdated: false,
1030 comments: [comment],
1031 },
1032 ],
1033 diffRefsByThreadId: new Map(),
1034 overviewFindingIds: [],
1035 truncated: false,
1036 }),
1037 listReactions: () =>
1038 Effect.succeed({
1039 reactions: [],
1040 reactionsByNoteId: new Map(),
1041 editedAtByNoteId: new Map([[comment.id, editedAt]]),
1042 botLogins: new Set<string>(),
1043 }),
1044 }),
1045 ),
1046 );
1047​
1048 const activity = yield* provider.getChangeRequestActivity(reference);
1049​
1050 expect(activity.comments[0]?.editedAt).toBe(editedAt);
1051 expect(activity.reviewThreads[0]?.comments[0]?.editedAt).toBe(editedAt);
1052 }),
1053 );
1054​
1055 it.effect("links comments and thread comments to their note on the merge request page", () =>
1056 Effect.gen(function* () {
1057 const provider = yield* make.pipe(
1058 Effect.provide(
1059 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
1060 ...reads,
1061 listDiscussions: () =>
1062 Effect.succeed({
1063 threads: [
1065 id: "d1",
1066 path: "src/a.ts",
1067 line: 1,
1068 side: "right" as const,
1069 isResolved: false,
1070 isOutdated: false,
1071 comments: [comment],
1072 },
1073 ],
1074 diffRefsByThreadId: new Map(),
1075 overviewFindingIds: [],
1076 truncated: false,
1077 }),
1078 }),
1079 ),
1080 );
1081​
1082 const activity = yield* provider.getChangeRequestActivity(reference);
1083​
1084 expect(activity.comments[0]?.url).toBe(`${webUrl}#note_42`);
1085 expect(activity.reviewThreads[0]?.comments[0]?.url).toBe(`${webUrl}#note_42`);
1086 }),
1087 );
1088​
1089 it.effect("marks a thread outdated once the merge request's diff moves past it", () =>
1090 Effect.gen(function* () {
1091 let detailReads = 0;
1092 const thread = (id: string) => ({
1093 id,
1094 path: "src/a.ts",
1095 line: 3,
1096 side: "right" as const,
1097 isResolved: false,
1098 isOutdated: false,
1099 comments: [],
1100 });
1101 const provider = yield* make.pipe(
1102 Effect.provide(
1103 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
1104 ...reads,
1105 getMergeRequestDetail: () =>
1106 Effect.map(reads.getMergeRequestDetail(), (detail) => ({
1107 ...detail,
1108 diffRefs: ++detailReads === 1 ? { ...currentRefs, headSha: "head1" } : currentRefs,
1109 })),
1110 listDiscussions: () =>
1111 Effect.succeed({
1112 threads: [thread("current"), thread("moved"), thread("unplaced")],
1113 diffRefsByThreadId: new Map([
1114 ["current", currentRefs],
1115 ["moved", { ...currentRefs, headSha: "head1" }],
1116 ]),
1117 overviewFindingIds: [],
1118 truncated: false,
1119 }),
1120 }),
1121 ),
1122 );
1123​
1124 const checks = provider.getChangeRequestChecks;
1125 if (!checks) throw new Error("missing getChangeRequestChecks");
1126 yield* checks(reference);
1127 const { reviewThreads } = yield* provider.getChangeRequestActivity(reference);
1128 expect(reviewThreads.map(({ id, isOutdated }) => [id, isOutdated])).toEqual([
1129 ["current", false],
1130 ["moved", true],
1131 ["unplaced", false],
1132 ]);
1133 }),
1134 );
1135​
1136 it.effect("keeps comments and commits when optional discussions, reactions and links fail", () =>
1137 Effect.gen(function* () {
1138 const provider = yield* make.pipe(
1139 Effect.provide(
1140 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
1141 ...reads,
1142 listDiscussions: () =>
1143 Effect.fail(
1144 new GitLabPullRequestCli.GitLabMergeRequestReadError({
1145 command: "glab",
1146 cwd: "/w",
1147 operation: "listDiscussions",
1148 cause: null,
1149 }),
1150 ),
1151 listReactions: () => Effect.fail(new GitLabCli.GitLabCliCommandError(context)),
1152 getMergeRequestDetail: () => Effect.fail(new GitLabCli.GitLabCliCommandError(context)),
1153 }),
1154 ),
1155 );
1156​
1157 expect(yield* provider.getChangeRequestActivity(reference)).toEqual({
1158 comments: [{ ...comment, reactions: [] }],
1159 commentCount: 1,
1160 commentsTruncated: true,
1161 reviewThreads: [],
1162 overviewThreads: [],
1163 reactions: [],
1164 commits: [commit],
1165 });
1166 }),
1167 );
1168​
1169 it.effect("flags comments by bot authors as bots, in the conversation and in threads", () =>
1170 Effect.gen(function* () {
1171 const bot = { login: "project_1_bot_abc", name: "Review bot", avatarUrl: null };
1172 const human = { login: "julius", name: null, avatarUrl: null };
1173 const provider = yield* make.pipe(
1174 Effect.provide(
1175 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
1176 ...reads,
1177 listNotes: () =>
1178 Effect.succeed({
1179 comments: [
1180 { ...comment, author: bot },
1181 { ...comment, id: "43", author: human },
1182 ],
1183 truncated: false,
1184 }),
1185 listDiscussions: () =>
1186 Effect.succeed({
1187 threads: [
1189 id: "d1",
1190 path: "a.ts",
1191 line: 1,
1192 side: "right" as const,
1193 isResolved: false,
1194 isOutdated: false,
1195 comments: [
1196 { id: "44", author: bot, body: "x", createdAt: comment.createdAt, url: null },
1197 ],
1198 },
1199 ],
1200 diffRefsByThreadId: new Map(),
1201 overviewFindingIds: [],
1202 truncated: false,
1203 }),
1204 listReactions: () =>
1205 Effect.succeed({
1206 reactions: [],
1207 reactionsByNoteId: new Map(),
1208 editedAtByNoteId: new Map(),
1209 botLogins: new Set([bot.login.toUpperCase()]),
1210 }),
1211 }),
1212 ),
1213 );
1214​
1215 const activity = yield* provider.getChangeRequestActivity(reference);
1216 expect(activity.comments.map((entry) => entry.author?.isBot)).toEqual([true, undefined]);
1217 expect(activity.reviewThreads[0]?.comments[0]?.author?.isBot).toBe(true);
1218 }),
1219 );
1220});
1221​
1222describe("review decisions", () => {
1223 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 };
1224 const item = {
1225 number: 7,
1226 title: "Merge request 7",
1227 url: "https://gitlab.com/acme/web/-/merge_requests/7",
1228 author: null,
1229 headBranch: "feat/page",
1230 baseBranch: "main",
1231 state: "open" as const,
1232 isDraft: false,
1233 mergeability: "mergeable" as const,
1234 additions: 0,
1235 deletions: 0,
1236 createdAt: "2026-07-01T00:00:00Z",
1237 updatedAt: "2026-07-02T00:00:00Z",
1238 reviewRequestLogins: [],
1239 labels: [],
1240 };
1241 const detail = {
1242 ...item,
1243 body: "",
1244 changedFiles: 1,
1245 mergedAt: null,
1246 closedAt: null,
1247 reviewers: [],
1248 checks: [],
1249 viewerCanMerge: true,
1250 reviewerIds: [],
1251 reviewerUsers: [],
1252 };
1253 const providerWith = (
1254 getListStates: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getListStates"],
1255 overrides: Partial<GitLabPullRequestCli.GitLabPullRequestCli["Service"]> = {},
1256 ) =>
1257 make.pipe(
1258 Effect.provide(
1259 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
1260 supportsGraphqlList: () => Effect.succeed(false),
1261 listMergeRequests: () =>
1262 Effect.succeed({
1263 items: [item, { ...item, number: 8 }],
1264 truncated: false,
1265 cursorAdvance: 2,
1266 }),
1267 ...overrides,
1268 getMergeRequestDetail: () => Effect.succeed(detail),
1269 getListStates,
1270 listMergeRequestStats: () =>
1271 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
1272 }),
1273 ),
1274 );
1275 const listing = {
1276 cwd: "/w",
1277 repository: "acme/web",
1278 host: "gitlab.com",
1279 state: "open" as const,
1280 involvement: "all" as const,
1281 viewer: "julius",
1282 limit: 2,
1283 };
1284​
1285 it.effect(
1286 "puts GitLab's approval and pipeline state on listed and summarized merge requests",
1287 () =>
1288 Effect.gen(function* () {
1289 const provider = yield* providerWith((input) => {
1290 expect(input.host).toBe(reference.host);
1291 return Effect.succeed(
1292 new Map([
1293 [7, { reviewDecision: "approved" as const, checksState: "failing" as const }],
1294 [8, { reviewDecision: null, checksState: null }],
1295 ]),
1296 );
1297 });
1298 const listed = yield* provider.listChangeRequests(listing);
1299 assert.isDefined(provider.getChangeRequestSummary);
1300 const summary = yield* provider.getChangeRequestSummary(reference);
1301​
1302 expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
1303 "approved",
1304 null,
1305 ]);
1306 expect(listed.items.map(({ checksState }) => checksState)).toEqual(["failing", null]);
1307 expect(summary.reviewDecision).toBe("approved");
1308 expect(summary.checksState).toBe("failing");
1309 expect(summary.additions).toBe(40);
1310 expect(summary.deletions).toBe(2);
1311 }),
1312 );
1313​
1314 it.effect(
1315 "lists through GraphQL where the host takes it, using the states that read carried",
1316 () =>
1317 Effect.gen(function* () {
1318 const graphqlFlags: Array<boolean | undefined> = [];
1319 let versionReads = 0;
1320 const providerReading = (
1321 supportsGraphqlList: Effect.Effect<
1322 boolean,
1323 GitLabPullRequestCli.GitLabPullRequestCliError
1324 >,
1325 ) =>
1326 providerWith(() => Effect.die("a GraphQL page carries its own states"), {
1327 supportsGraphqlList: () => {
1328 versionReads += 1;
1329 return supportsGraphqlList;
1330 },
1331 listMergeRequests: (input) => {
1332 graphqlFlags.push(input.graphql);
1333 return Effect.succeed({
1334 items: [item],
1335 truncated: true,
1336 cursorAdvance: 1,
1337 resumeAfter: "eyJpZCI6IjcifQ",
1338 listStates: new Map([
1339 [7, { reviewDecision: "changes-requested" as const, checksState: null }],
1340 ]),
1341 });
1342 },
1343 });
1344 const listedWith = (
1345 supportsGraphqlList: Effect.Effect<
1346 boolean,
1347 GitLabPullRequestCli.GitLabPullRequestCliError
1348 >,
1349 ) =>
1350 providerReading(supportsGraphqlList).pipe(
1351 Effect.flatMap((provider) => provider.listChangeRequests(listing)),
1352 );
1353​
1354 const listed = yield* listedWith(Effect.succeed(true));
1355 expect(listed).toMatchObject({ resumeAfter: "eyJpZCI6IjcifQ", truncated: true });
1356 expect(listed).not.toHaveProperty("listStates");
1357 expect(listed.items[0]?.reviewDecision).toBe("changes-requested");
1358​
1359 // An unreadable version leaves the list on REST rather than failing it, and stays known.
1360 const unreadable = yield* providerReading(
1361 Effect.fail(
1362 new GitLabPullRequestCli.GitLabMergeRequestReadError({
1363 command: "glab",
1364 cwd: "/w",
1365 operation: "supportsGraphqlList",
1366 cause: null,
1367 }),
1368 ),
1369 );
1370 versionReads = 0;
1371 yield* unreadable.listChangeRequests(listing);
1372 yield* unreadable.listChangeRequests(listing);
1373 expect(graphqlFlags).toEqual([true, false, false]);
1374 expect(versionReads).toBe(1);
1375 }),
1376 );
1377​
1378 it.effect.each([
1380 failure: "a failed read",
1381 error: new GitLabPullRequestCli.GitLabMergeRequestReadError({
1382 command: "glab",
1383 cwd: "/w",
1384 operation: "getListStates",
1385 cause: null,
1386 }),
1387 },
1389 failure: "a rate limit",
1390 error: new GitLabCli.GitLabCliRateLimitError({
1391 operation: "execute",
1392 command: "glab",
1393 cwd: "/w",
1394 cause: null,
1395 }),
1396 },
1397 ])("keeps rows and summaries with an unknown decision after $failure", ({ error }) =>
1398 Effect.gen(function* () {
1399 const provider = yield* providerWith(() => Effect.fail(error));
1400 const listed = yield* provider.listChangeRequests(listing);
1401 assert.isDefined(provider.getChangeRequestSummary);
1402 const summary = yield* provider.getChangeRequestSummary(reference);
1403​
1404 expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
1405 undefined,
1406 undefined,
1407 ]);
1408 expect(summary.reviewDecision).toBeUndefined();
1409 }),
1410 );
1411});