@devries-cameron20 / t3code-1 / commits / fab95f38a5
Fork 0

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

fix(gitlab): the checks and review list filters work (#30433)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>

Antony committed Nov 6, 2026 at 01:49 UTC fab95f38a5803a2364821e80d62dfb7eb4abd2b1
8 files changed +1085 -157
apps/server/src/pullRequest/PullRequestService.test.ts
+13 -2
@@ -3614,7 +3614,7 @@ it.effect("hands a host's own resume position back on the next read", () =>
3614 }),
3615 );
3616
3617 -it.effect("judges the review filter only on a host that summarises its reviews", () =>
3617 +it.effect("judges review and checks filters only on a host that summarises them", () =>
3618 Effect.gen(function* () {
3619 const service = yield* makeService({
3620 projects: [
@@ -3632,10 +3632,15 @@ it.effect("judges the review filter only on a host that summarises its reviews",
3632 listChangeRequests: () =>
3633 Effect.succeed({
3634 items: [
3635 - { ...changeRequest(1, "2026-07-02T00:00:00Z"), reviewDecision: null },
3635 + {
3636 + ...changeRequest(1, "2026-07-02T00:00:00Z"),
3637 + reviewDecision: null,
3638 + checksState: "failing" as const,
3639 + },
3640 {
3641 ...changeRequest(2, "2026-07-02T00:00:00Z"),
3642 reviewDecision: "approved" as const,
3643 + checksState: null,
3644 },
3645 ],
3646 truncated: false,
@@ -3658,6 +3663,12 @@ it.effect("judges the review filter only on a host that summarises its reviews",
3663
3664 const approved = yield* service.list({ state: "open", filters: { review: "approved" } });
3665 assert.deepStrictEqual(approved.entries.map((entry) => entry.number).toSorted(), [2, 3]);
3666 +
3667 + const failing = yield* service.list({ state: "open", filters: { checks: "failing" } });
3668 + assert.deepStrictEqual(failing.entries.map((entry) => entry.number).toSorted(), [1, 3]);
3669 +
3670 + const passing = yield* service.list({ state: "open", filters: { checks: "passing" } });
3671 + assert.deepStrictEqual(passing.entries.map((entry) => entry.number).toSorted(), [3]);
3672 }),
3673 );
3674
apps/server/src/pullRequest/PullRequestService.ts
+3 -1
@@ -1197,7 +1197,6 @@ export const make = Effect.gen(function* () {
1197 { concurrency: REPOSITORY_CONCURRENCY },
1198 );
1199
1200 - // Only the host can filter checks; listed rows have no check state.
1200 const matchesRowFilters = (
1201 item: ProviderChangeRequest,
1202 filters: PullRequestListFilters | undefined,
@@ -1213,6 +1212,9 @@ export const make = Effect.gen(function* () {
1212 (filters.review === "none"
1213 ? item.reviewDecision === null
1214 : item.reviewDecision === filters.review)) &&
1215 + (filters.checks === undefined ||
1216 + item.checksState === undefined ||
1217 + item.checksState === filters.checks) &&
1218 (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
1219 (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
1220 (filters.author === undefined ||
packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+227 -3
@@ -114,6 +114,40 @@ function callAt(index: number) {
114 return call[0];
115 }
116
117 +function graphqlListPage(
118 + numbers: ReadonlyArray<number>,
119 + pageInfo: { readonly hasNextPage: boolean; readonly endCursor: string | null },
120 +): string {
121 + return JSON.stringify({
122 + data: {
123 + metadata: { enterprise: true },
124 + project: {
125 + mergeRequests: {
126 + pageInfo,
127 + nodes: numbers.map((number) => ({
128 + iid: String(number),
129 + title: `Merge request ${number}`,
130 + webUrl: `https://gitlab.com/acme/web/-/merge_requests/${number}`,
131 + createdAt: "2026-07-01T00:00:00Z",
132 + updatedAt: "2026-07-02T00:00:00Z",
133 + sourceBranch: "feat/page",
134 + targetBranch: "main",
135 + approved: true,
136 + approvedBy: { nodes: [{ username: "julius" }] },
137 + })),
138 + },
139 + },
140 + },
141 + });
142 +}
143 +
144 +function graphqlRequestOf(index: number) {
145 + return JSON.parse(callAt(index).stdin ?? "{}") as {
146 + readonly query: string;
147 + readonly variables: Record<string, unknown>;
148 + };
149 +}
150 +
151 afterEach(() => {
152 mockedExecute.mockReset();
153 });
@@ -144,16 +178,16 @@ layer("GitLabPullRequestCli.layer", (it) => {
178 });
179 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
180 const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.internal" };
147 - expect(yield* cli.getReviewDecisions({ ...reference, numbers: [] })).toEqual(new Map());
181 + expect(yield* cli.getListStates({ ...reference, numbers: [] })).toEqual(new Map());
182 expect(mockedExecute).not.toHaveBeenCalled();
149 - const decisions = yield* cli.getReviewDecisions({
183 + const decisions = yield* cli.getListStates({
184 ...reference,
185 numbers: Array.from({ length: 101 }, (_, index) => index + 1),
186 });
187 expect(callAt(0).host).toBe(reference.host);
188 expect(callAt(1).host).toBe(reference.host);
189 expect(decisions.size).toBe(101);
156 - expect(decisions.get(101)).toBe("approved");
190 + expect(decisions.get(101)).toEqual({ reviewDecision: "approved", checksState: null });
191 expect(mockedExecute).toHaveBeenCalledTimes(2);
192 expect(
193 [0, 1].map((index) => JSON.parse(callAt(index).stdin ?? "{}").variables.iids.length),
@@ -238,6 +272,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
272 excludedLabels: ["wontfix", "stale", "any"],
273 author: "@me",
274 draft: "only",
275 + review: "approved",
276 },
277 });
278
@@ -246,6 +281,195 @@ layer("GitLabPullRequestCli.layer", (it) => {
281 expect(params.get("not[labels]")).toBe("wontfix,stale");
282 expect(params.get("author_username")).toBe("bilal");
283 expect(params.get("wip")).toBe("yes");
284 + expect(params.get("approved_by_usernames[]")).toBe("Any");
285 + }),
286 + );
287 +
288 + it.effect("narrows by approval only where GitLab returns every row the decision keeps", () =>
289 + Effect.gen(function* () {
290 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
291 + const reviews = ["none", "review-required", "changes-requested"] as const;
292 + for (const review of reviews) {
293 + mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))));
294 + yield* cli.listMergeRequests({
295 + cwd: "/w",
296 + repository: "acme/web",
297 + state: "open",
298 + involvement: "all",
299 + viewer: "bilal",
300 + limit: 10,
301 + filters: { review },
302 + });
303 + }
304 +
305 + const sent = reviews.map((_, call) => {
306 + const params = new URLSearchParams((argsOfCall(call)[1] ?? "").split("?")[1]);
307 + return [params.get("approved_by_ids[]"), params.get("approved_by_usernames[]")];
308 + });
309 + expect(sent).toEqual([
310 + ["None", null],
311 + [null, null],
312 + [null, null],
313 + ]);
314 + }),
315 + );
316 +
317 + it.effect(
318 + "lists through GraphQL with the filters GitLab narrows there, declaring only those",
319 + () =>
320 + Effect.gen(function* () {
321 + mockedExecute.mockReturnValue(
322 + Effect.succeed(output(graphqlListPage([1], { hasNextPage: false, endCursor: null }))),
323 + );
324 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
325 +
326 + yield* cli.listMergeRequests({
327 + cwd: "/w",
328 + repository: "acme/web",
329 + state: "open",
330 + involvement: "all",
331 + viewer: "bilal",
332 + limit: 10,
333 + query: " page ",
334 + graphql: true,
335 + cursor: {
336 + updatedBefore: "2026-07-03T00:00:00Z",
337 + delivered: 10,
338 + resumeAfter: "eyJpZCI6IjEifQ",
339 + },
340 + filters: {
341 + labels: [["bug"], ["size:S", "size:XS"]],
342 + excludedLabels: ["wontfix"],
343 + author: "octocat",
344 + draft: "hide",
345 + review: "changes-requested",
346 + },
347 + });
348 +
349 + const { query, variables } = graphqlRequestOf(0);
350 + expect(variables).toEqual({
351 + fullPath: "acme/web",
352 + first: 10,
353 + after: "eyJpZCI6IjEifQ",
354 + state: "opened",
355 + authorUsername: "octocat",
356 + search: "page",
357 + labels: ["bug"],
358 + draft: false,
359 + reviewStates: ["REQUESTED_CHANGES"],
360 + notLabels: ["wontfix"],
361 + });
362 + expect(query).toContain("reviewStates: $reviewStates");
363 + expect(query).toContain("not: { labels: $notLabels }");
364 + expect(query).not.toContain("$approvedBy");
365 +
366 + // Beside a reviewer, GitLab would match only that reviewer's own state.
367 + yield* cli.listMergeRequests({
368 + cwd: "/w",
369 + repository: "acme/web",
370 + state: "open",
371 + involvement: "reviewing",
372 + viewer: "bilal",
373 + limit: 10,
374 + graphql: true,
375 + filters: { review: "changes-requested" },
376 + });
377 + expect(graphqlRequestOf(1).variables).toMatchObject({ reviewerUsername: "bilal" });
378 + expect(graphqlRequestOf(1).variables).not.toHaveProperty("reviewStates");
379 + }),
380 + );
381 +
382 + it.effect("walks GraphQL pages by GitLab's cursor and hands the last one back", () =>
383 + Effect.gen(function* () {
384 + mockedExecute
385 + .mockReturnValueOnce(
386 + Effect.succeed(output(graphqlListPage([1, 2], { hasNextPage: true, endCursor: "c1" }))),
387 + )
388 + .mockReturnValueOnce(
389 + Effect.succeed(output(graphqlListPage([3], { hasNextPage: true, endCursor: "c2" }))),
390 + );
391 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
392 +
393 + const batch = yield* cli.listMergeRequests({
394 + cwd: "/w",
395 + repository: "acme/web",
396 + state: "open",
397 + involvement: "all",
398 + viewer: "bilal",
399 + limit: 3,
400 + graphql: true,
401 + filters: { review: "approved" },
402 + });
403 +
404 + expect(batch).toMatchObject({ truncated: true, cursorAdvance: 3, resumeAfter: "c2" });
405 + expect(batch.items.map((item) => item.number)).toEqual([1, 2, 3]);
406 + expect(batch.listStates?.get(3)).toEqual({ reviewDecision: "approved", checksState: null });
407 + expect([0, 1].map((call) => graphqlRequestOf(call).variables)).toMatchObject([
408 + { first: 3, after: null, approvedBy: ["Any"] },
409 + { first: 1, after: "c1" },
410 + ]);
411 + }),
412 + );
413 +
414 + it.effect("reads REST for a REST cursor, and when a first GraphQL read or command fails", () =>
415 + Effect.gen(function* () {
416 + mockedExecute
417 + .mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))))
418 + .mockReturnValueOnce(
419 + Effect.succeed(
420 + output(JSON.stringify({ errors: [{ message: "Field 'search' doesn't exist" }] })),
421 + ),
422 + )
423 + .mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))))
424 + .mockReturnValueOnce(Effect.succeed(output(JSON.stringify({ errors: [] }))))
425 + .mockReturnValueOnce(
426 + Effect.fail(
427 + new GitLabCli.GitLabCliCommandError({
428 + operation: "execute",
429 + command: "glab",
430 + cwd: "/w",
431 + cause: new Error("502 Bad Gateway"),
432 + }),
433 + ),
434 + )
435 + .mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 2))));
436 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
437 + const list = (cursor?: { updatedBefore: string; delivered: number; resumeAfter?: string }) =>
438 + cli.listMergeRequests({
439 + cwd: "/w",
440 + repository: "acme/web",
441 + state: "open",
442 + involvement: "all",
443 + viewer: "bilal",
444 + limit: 10,
445 + // A cursor, not the host's current answer, picks the API.
446 + graphql: cursor?.resumeAfter === undefined,
447 + ...(cursor === undefined ? {} : { cursor }),
448 + });
449 +
450 + yield* list({ updatedBefore: "2026-07-03T00:00:00Z", delivered: 10 });
451 + const fellBack = yield* list();
452 + // A resumed GraphQL read stays on GraphQL and fails, since REST would read `delivered` as an offset.
453 + const resumed = yield* Effect.result(
454 + list({ updatedBefore: "2026-07-03T00:00:00Z", delivered: 10, resumeAfter: "c1" }),
455 + );
456 + const commandFailed = yield* list();
457 +
458 + expect(fellBack.items.map((item) => item.number)).toEqual([1]);
459 + expect(fellBack).not.toHaveProperty("resumeAfter");
460 + expect(mockedExecute.mock.calls.map(([request]) => request.args[1]?.split("?")[0])).toEqual([
461 + "projects/acme%2Fweb/merge_requests",
462 + "graphql",
463 + "projects/acme%2Fweb/merge_requests",
464 + "graphql",
465 + "graphql",
466 + "projects/acme%2Fweb/merge_requests",
467 + ]);
468 + expect(commandFailed.items.map((item) => item.number)).toEqual([2]);
469 + expect(resumed).toMatchObject({
470 + _tag: "Failure",
471 + failure: { _tag: "GitLabMergeRequestReadError" },
472 + });
473 }),
474 );
475
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+231 -22
@@ -24,7 +24,6 @@ import type {
24 PullRequestReaction,
25 PullRequestReactionContent,
26 PullRequestReviewCommentDraft,
27 - PullRequestReviewDecision,
27 PullRequestReviewPosition,
28 PullRequestReviewThread,
29 PullRequestReviewVerdict,
@@ -46,6 +45,8 @@ import {
45 decodeMergeRequestDetailJson,
46 decodeMergeRequestDiffsJson,
47 decodeMergeRequestChangesJson,
48 + decodeGraphqlListSupportJson,
49 + decodeMergeRequestGraphqlListJson,
50 decodeMergeRequestListJson,
51 decodeMergeRequestFileStatsJson,
52 decodeMergeRequestStatsJson,
@@ -55,7 +56,7 @@ import {
56 decodeProjectLabelsJson,
57 decodeProjectUsersJson,
58 decodeRepositoryBlobsJson,
58 - decodeReviewDecisionsJson,
59 + decodeListStatesJson,
60 decodeSourceBranchJson,
61 decodeTriggerJobChecksJson,
62 decodeViewerJson,
@@ -65,11 +66,14 @@ import {
66 MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
67 MERGE_REQUEST_STATS_GRAPHQL_QUERY,
68 REPOSITORY_BLOBS_GRAPHQL_QUERY,
68 - REVIEW_DECISIONS_GRAPHQL_QUERY,
69 + LIST_ITEM_GRAPHQL_FIELDS,
70 + LIST_STATES_GRAPHQL_QUERY,
71 + SERVER_VERSION_GRAPHQL_QUERY,
72 SOURCE_BRANCH_GRAPHQL_QUERY,
73 type GitLabDiffRefs,
74 type GitLabMergeRequestDetail,
75 type GitLabMergeRequestListItem,
76 + type GitLabMergeRequestListState,
77 type GitLabProjectUsers,
78 } from "./gitLabMergeRequestJson.ts";
79 import type {
@@ -283,6 +287,10 @@ export interface GitLabMergeRequestListBatch {
287 readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
288 readonly truncated: boolean;
289 readonly cursorAdvance: number;
290 + /** GitLab's GraphQL cursor past the last row, when the page was read through GraphQL. */
291 + readonly resumeAfter?: string;
292 + /** Present when the read already carried each row's approval and pipeline state. */
293 + readonly listStates?: ReadonlyMap<number, GitLabMergeRequestListState>;
294 }
295
296 export interface GitLabMergeRequestDiffSlice {
@@ -310,8 +318,19 @@ export class GitLabPullRequestCli extends Context.Service<
318 readonly query?: string | undefined;
319 readonly cursor?: ProviderListCursor | undefined;
320 readonly filters?: PullRequestListFilters | undefined;
321 + /**
322 + * Read a first page through GraphQL, which narrows more filters; see `supportsGraphqlList`.
323 + * A cursor keeps the API that handed it out.
324 + */
325 + readonly graphql?: boolean;
326 }) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>;
327
328 + /** Whether this host's GraphQL list takes every filter the REST list does. */
329 + readonly supportsGraphqlList: (input: {
330 + readonly cwd: string;
331 + readonly host?: string | undefined;
332 + }) => Effect.Effect<boolean, GitLabPullRequestCliError>;
333 +
334 readonly getMergeRequestDetail: (input: {
335 readonly cwd: string;
336 readonly host?: string | undefined;
@@ -321,13 +340,14 @@ export class GitLabPullRequestCli extends Context.Service<
340 readonly downstreamChecks?: boolean;
341 }) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
342
324 - readonly getReviewDecisions: (input: {
343 + /** Approval and head pipeline state, read in one GraphQL request per 100 merge requests. */
344 + readonly getListStates: (input: {
345 readonly cwd: string;
346 readonly host?: string | undefined;
347 readonly repository: string;
348 readonly numbers: ReadonlyArray<number>;
349 }) => Effect.Effect<
330 - ReadonlyMap<number, PullRequestReviewDecision | null>,
350 + ReadonlyMap<number, GitLabMergeRequestListState>,
351 GitLabPullRequestCliError
352 >;
353
@@ -605,7 +625,19 @@ function involvementParams(input: {
625 * GitLab's `labels` asks for every label it names, so only groups of one go to it; a group of
626 * alternatives is left for the service to narrow. A comma would split a name in two, and `None`
627 * and `Any` mean "unlabeled" and "labeled" to GitLab rather than labels of those names.
628 + * Review filters go only where GitLab returns every row the service's exact filter keeps.
629 */
630 +function listableLabels(filters: PullRequestListFilters) {
631 + const listable = (names: ReadonlyArray<string>) =>
632 + names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
633 + return {
634 + required: listable(
635 + (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
636 + ),
637 + excluded: listable(filters.excludedLabels ?? []),
638 + };
639 +}
640 +
641 function filterParams(input: {
642 readonly filters?: PullRequestListFilters | undefined;
643 readonly involvement: PullRequestInvolvement;
@@ -613,12 +645,7 @@ function filterParams(input: {
645 }): ReadonlyArray<readonly [string, string]> {
646 const filters = input.filters;
647 if (filters === undefined) return [];
616 - const listable = (names: ReadonlyArray<string>) =>
617 - names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
618 - const required = listable(
619 - (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
620 - );
621 - const excluded = listable(filters.excludedLabels ?? []);
648 + const { required, excluded } = listableLabels(filters);
649 return [
650 ...(required.length === 0 ? [] : [["labels", required.join(",")] as const]),
651 ...(excluded.length === 0 ? [] : [["not[labels]", excluded.join(",")] as const]),
@@ -633,9 +660,92 @@ function filterParams(input: {
660 ...(filters.draft === undefined
661 ? []
662 : [["wip", filters.draft === "only" ? "yes" : "no"] as const]),
663 + ...(filters.review === "approved"
664 + ? [["approved_by_usernames[]", "Any"] as const]
665 + : filters.review === "none"
666 + ? [["approved_by_ids[]", "None"] as const]
667 + : []),
668 ];
669 }
670
671 +/**
672 + * The GraphQL list takes the REST filters and narrows two review filters exactly: `approvedBy`
673 + * Any for approved, and reviewer states for changes requested. Only arguments in use are
674 + * declared, since GraphQL rejects a declared variable the query never reads.
675 + */
676 +function graphqlListQuery(input: {
677 + readonly repository: string;
678 + readonly state: PullRequestListState;
679 + readonly involvement: PullRequestInvolvement;
680 + readonly viewer: string;
681 + readonly query?: string | undefined;
682 + readonly filters?: PullRequestListFilters | undefined;
683 + readonly first: number;
684 + readonly after: string | undefined;
685 +}): { readonly query: string; readonly variables: Record<string, unknown> } {
686 + const filters = input.filters ?? {};
687 + const { required, excluded } = listableLabels(filters);
688 + const search = input.query?.trim() ?? "";
689 + const author =
690 + input.involvement === "authored"
691 + ? input.viewer
692 + : filters.author === undefined
693 + ? undefined
694 + : resolvePullRequestAuthorFilter(filters.author, input.viewer);
695 + const args: ReadonlyArray<readonly [name: string, type: string, value: unknown]> = [
696 + ["state", "MergeRequestState", stateParam(input.state)],
697 + ...(author === undefined ? [] : [["authorUsername", "String", author] as const]),
698 + ...(input.involvement === "reviewing"
699 + ? [["reviewerUsername", "String", input.viewer] as const]
700 + : []),
701 + ...(search.length === 0 ? [] : [["search", "String", search] as const]),
702 + ...(required.length === 0 ? [] : [["labels", "[String!]", required] as const]),
703 + ...(filters.draft === undefined
704 + ? []
705 + : [["draft", "Boolean", filters.draft === "only"] as const]),
706 + ...(filters.review === "approved" ? [["approvedBy", "[String!]", ["Any"]] as const] : []),
707 + // Beside `reviewerUsername`, GitLab matches review states on that reviewer alone.
708 + ...(filters.review === "changes-requested" && input.involvement !== "reviewing"
709 + ? [["reviewStates", "[MergeRequestReviewState!]", ["REQUESTED_CHANGES"]] as const]
710 + : []),
711 + ];
712 + const declarations = [
713 + "$fullPath: ID!",
714 + "$first: Int!",
715 + "$after: String",
716 + ...args.map(([name, type]) => `$${name}: ${type}`),
717 + ...(excluded.length === 0 ? [] : ["$notLabels: [String!]"]),
718 + ];
719 + const usages = [
720 + "sort: UPDATED_DESC",
721 + "first: $first",
722 + "after: $after",
723 + ...args.map(([name]) => `${name}: $${name}`),
724 + ...(excluded.length === 0 ? [] : ["not: { labels: $notLabels }"]),
725 + ];
726 + return {
727 + query: `query(${declarations.join(", ")}) {
728 + metadata { enterprise }
729 + project(fullPath: $fullPath) {
730 + mergeRequests(${usages.join(", ")}) {
731 + pageInfo { hasNextPage endCursor }
732 + nodes { ${LIST_ITEM_GRAPHQL_FIELDS} }
733 + }
734 + }
735 +}`,
736 + variables: {
737 + fullPath: input.repository.trim(),
738 + first: input.first,
739 + after: input.after ?? null,
740 + ...Object.fromEntries(args.map(([name, , value]) => [name, value])),
741 + ...(excluded.length === 0 ? {} : { notLabels: excluded }),
742 + },
743 + };
744 +}
745 +
746 +/** The list cursor carries GitLab's own position only when it fits the cursor's alphabet. */
747 +const RESUME_AFTER_PATTERN = /^[\w.:~+-]{1,128}$/u;
748 +
749 function diffCursorPage(cursor: string): number | null {
750 return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
751 }
@@ -1300,6 +1410,66 @@ export const make = Effect.gen(function* () {
1410 }),
1411 );
1412
1413 + const graphqlListPage = (input: {
1414 + readonly cwd: string;
1415 + readonly host?: string | undefined;
1416 + readonly repository: string;
1417 + readonly state: PullRequestListState;
1418 + readonly involvement: PullRequestInvolvement;
1419 + readonly viewer: string;
1420 + readonly limit: number;
1421 + readonly query?: string | undefined;
1422 + readonly filters?: PullRequestListFilters | undefined;
1423 + readonly after: string | undefined;
1424 + readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
1425 + readonly states: ReadonlyMap<number, GitLabMergeRequestListState>;
1426 + readonly cursorAdvance: number;
1427 + /** Bounds the walk when whole pages fail to decode. */
1428 + readonly reads: number;
1429 + }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> =>
1430 + graphqlRead({
1431 + cwd: input.cwd,
1432 + host: input.host,
1433 + operation: "listMergeRequests",
1434 + ...graphqlListQuery({
1435 + ...input,
1436 + first: Math.max(1, Math.min(input.limit - input.collected.length, MAX_PAGE_SIZE)),
1437 + }),
1438 + decode: decodeMergeRequestGraphqlListJson,
1439 + }).pipe(
1440 + Effect.flatMap((page) => {
1441 + const collected = [...input.collected, ...page.items];
1442 + const states = new Map([...input.states, ...page.states]);
1443 + const cursorAdvance = input.cursorAdvance + page.rawCount;
1444 + const resumeAfter =
1445 + page.endCursor !== null && RESUME_AFTER_PATTERN.test(page.endCursor)
1446 + ? page.endCursor
1447 + : undefined;
1448 + if (
1449 + page.hasNextPage &&
1450 + resumeAfter !== undefined &&
1451 + collected.length < input.limit &&
1452 + input.reads > 1
1453 + ) {
1454 + return graphqlListPage({
1455 + ...input,
1456 + after: resumeAfter,
1457 + collected,
1458 + states,
1459 + cursorAdvance,
1460 + reads: input.reads - 1,
1461 + });
1462 + }
1463 + return Effect.succeed({
1464 + items: collected,
1465 + truncated: page.hasNextPage,
1466 + cursorAdvance,
1467 + ...(resumeAfter === undefined ? {} : { resumeAfter }),
1468 + listStates: states,
1469 + });
1470 + }),
1471 + );
1472 +
1473 const labelPermission = (input: {
1474 readonly cwd: string;
1475 readonly host?: string | undefined;
@@ -1544,22 +1714,19 @@ export const make = Effect.gen(function* () {
1714 }),
1715 );
1716
1547 - const reviewDecisionsOf = (input: {
1717 + const listStatesOf = (input: {
1718 readonly cwd: string;
1719 readonly host?: string | undefined;
1720 readonly repository: string;
1721 readonly numbers: ReadonlyArray<number>;
1552 - }): Effect.Effect<
1553 - ReadonlyMap<number, PullRequestReviewDecision | null>,
1554 - GitLabPullRequestCliError
1555 - > =>
1722 + }): Effect.Effect<ReadonlyMap<number, GitLabMergeRequestListState>, GitLabPullRequestCliError> =>
1723 graphqlRead({
1724 cwd: input.cwd,
1725 host: input.host,
1559 - operation: "getReviewDecisions",
1560 - query: REVIEW_DECISIONS_GRAPHQL_QUERY,
1726 + operation: "getListStates",
1727 + query: LIST_STATES_GRAPHQL_QUERY,
1728 variables: { fullPath: input.repository, iids: input.numbers.map(String) },
1562 - decode: decodeReviewDecisionsJson,
1729 + decode: decodeListStatesJson,
1730 });
1731
1732 const viewerUsername = (input: { readonly cwd: string; readonly host?: string | undefined }) =>
@@ -1588,9 +1755,51 @@ export const make = Effect.gen(function* () {
1755 listMergeRequests: Effect.fn("GitLabPullRequestCli.listMergeRequests")(function (input) {
1756 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
1757 const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;
1591 - return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
1758 + const rest = Effect.suspend(() =>
1759 + listPage({ ...input, page, collected: [], cursorAdvance: 0 }),
1760 + );
1761 + // A cursor's offset means something only to the API that handed it out.
1762 + const viaGraphql =
1763 + input.cursor === undefined
1764 + ? input.graphql === true
1765 + : input.cursor.resumeAfter !== undefined;
1766 + if (!viaGraphql) return rest;
1767 + const graphql = graphqlListPage({
1768 + ...input,
1769 + after: input.cursor?.resumeAfter,
1770 + collected: [],
1771 + states: new Map(),
1772 + cursorAdvance: 0,
1773 + reads: Math.ceil(input.limit / MAX_PAGE_SIZE) + 1,
1774 + });
1775 + // GraphQL counts only filtered rows, so its `delivered` is no REST offset once resumed.
1776 + if (input.cursor !== undefined) return graphql;
1777 + return graphql.pipe(
1778 + Effect.catchIf(
1779 + (cause) =>
1780 + cause._tag !== "GitLabCliUnavailableError" &&
1781 + cause._tag !== "GitLabCliAuthenticationError" &&
1782 + cause._tag !== "GitLabCliRateLimitError",
1783 + (cause) =>
1784 + Effect.logWarning("GitLab GraphQL merge request list failed; reading REST instead", {
1785 + repository: input.repository,
1786 + reason: cause._tag,
1787 + }).pipe(Effect.andThen(rest)),
1788 + ),
1789 + );
1790 }),
1791
1792 + supportsGraphqlList: Effect.fn("GitLabPullRequestCli.supportsGraphqlList")((input) =>
1793 + graphqlRead({
1794 + cwd: input.cwd,
1795 + host: input.host,
1796 + operation: "supportsGraphqlList",
1797 + query: SERVER_VERSION_GRAPHQL_QUERY,
1798 + variables: {},
1799 + decode: decodeGraphqlListSupportJson,
1800 + }),
1801 + ),
1802 +
1803 getMergeRequestDetail: Effect.fn("GitLabPullRequestCli.getMergeRequestDetail")(
1804 function* (input) {
1805 const [read, viewerCanEditLabels] = yield* Effect.all(
@@ -1628,12 +1837,12 @@ export const make = Effect.gen(function* () {
1837 },
1838 ),
1839
1631 - getReviewDecisions: Effect.fn("GitLabPullRequestCli.getReviewDecisions")(function (input) {
1840 + getListStates: Effect.fn("GitLabPullRequestCli.getListStates")(function (input) {
1841 const batches: Array<ReadonlyArray<number>> = [];
1842 for (let at = 0; at < input.numbers.length; at += MAX_PAGE_SIZE) {
1843 batches.push(input.numbers.slice(at, at + MAX_PAGE_SIZE));
1844 }
1636 - return Effect.forEach(batches, (numbers) => reviewDecisionsOf({ ...input, numbers }), {
1845 + return Effect.forEach(batches, (numbers) => listStatesOf({ ...input, numbers }), {
1846 concurrency: 2,
1847 }).pipe(Effect.map((pages) => new Map(pages.flatMap((page) => [...page]))));
1848 }),
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+99 -25
@@ -197,7 +197,7 @@ describe("getChangeRequest base freshness", () => {
197 Effect.provide(
198 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
199 getMergeRequestDetail: () => Effect.succeed(detail),
200 - getReviewDecisions: () => Effect.succeed(new Map()),
200 + getListStates: () => Effect.succeed(new Map()),
201
202 listMergeRequestStats: () => Effect.succeed([]),
203 }),
@@ -298,7 +298,7 @@ describe("getChangeRequest base freshness", () => {
298 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
299 getMergeRequestDetail: () => Effect.succeed(detail),
300 getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),
301 - getReviewDecisions: () => Effect.succeed(new Map()),
301 + getListStates: () => Effect.succeed(new Map()),
302 listMergeRequestStats: () =>
303 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
304 }),
@@ -346,7 +346,7 @@ describe("merge request reads", () => {
346 Effect.provide(
347 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
348 listMergeRequestStats: () => Effect.succeed([]),
349 - getReviewDecisions: () => Effect.succeed(new Map()),
349 + getListStates: () => Effect.succeed(new Map()),
350 getMergeRequestDetail: (input) =>
351 Effect.sync(() => {
352 calls.detail += 1;
@@ -772,19 +772,22 @@ describe("review decisions", () => {
772 reviewerIds: [],
773 };
774 const providerWith = (
775 - getReviewDecisions: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getReviewDecisions"],
775 + getListStates: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getListStates"],
776 + overrides: Partial<GitLabPullRequestCli.GitLabPullRequestCli["Service"]> = {},
777 ) =>
778 make.pipe(
779 Effect.provide(
780 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
781 + supportsGraphqlList: () => Effect.succeed(false),
782 listMergeRequests: () =>
783 Effect.succeed({
784 items: [item, { ...item, number: 8 }],
785 truncated: false,
786 cursorAdvance: 2,
787 }),
788 + ...overrides,
789 getMergeRequestDetail: () => Effect.succeed(detail),
787 - getReviewDecisions,
790 + getListStates,
791 listMergeRequestStats: () =>
792 Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
793 }),
@@ -800,26 +803,97 @@ describe("review decisions", () => {
803 limit: 2,
804 };
805
803 - it.effect("puts GitLab's approval state on listed and summarized merge requests", () =>
804 - Effect.gen(function* () {
805 - const provider = yield* providerWith((input) => {
806 - expect(input.host).toBe(reference.host);
807 - return Effect.succeed(
808 - new Map([
809 - [7, "approved" as const],
810 - [8, null],
811 - ]),
812 - );
813 - });
814 - const listed = yield* provider.listChangeRequests(listing);
815 - assert.isDefined(provider.getChangeRequestSummary);
816 - const summary = yield* provider.getChangeRequestSummary(reference);
806 + it.effect(
807 + "puts GitLab's approval and pipeline state on listed and summarized merge requests",
808 + () =>
809 + Effect.gen(function* () {
810 + const provider = yield* providerWith((input) => {
811 + expect(input.host).toBe(reference.host);
812 + return Effect.succeed(
813 + new Map([
814 + [7, { reviewDecision: "approved" as const, checksState: "failing" as const }],
815 + [8, { reviewDecision: null, checksState: null }],
816 + ]),
817 + );
818 + });
819 + const listed = yield* provider.listChangeRequests(listing);
820 + assert.isDefined(provider.getChangeRequestSummary);
821 + const summary = yield* provider.getChangeRequestSummary(reference);
822 +
823 + expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
824 + "approved",
825 + null,
826 + ]);
827 + expect(listed.items.map(({ checksState }) => checksState)).toEqual(["failing", null]);
828 + expect(summary.reviewDecision).toBe("approved");
829 + expect(summary.checksState).toBe("failing");
830 + expect(summary.additions).toBe(40);
831 + expect(summary.deletions).toBe(2);
832 + }),
833 + );
834
818 - expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual(["approved", null]);
819 - expect(summary.reviewDecision).toBe("approved");
820 - expect(summary.additions).toBe(40);
821 - expect(summary.deletions).toBe(2);
822 - }),
835 + it.effect(
836 + "lists through GraphQL where the host takes it, using the states that read carried",
837 + () =>
838 + Effect.gen(function* () {
839 + const graphqlFlags: Array<boolean | undefined> = [];
840 + let versionReads = 0;
841 + const providerReading = (
842 + supportsGraphqlList: Effect.Effect<
843 + boolean,
844 + GitLabPullRequestCli.GitLabPullRequestCliError
845 + >,
846 + ) =>
847 + providerWith(() => Effect.die("a GraphQL page carries its own states"), {
848 + supportsGraphqlList: () => {
849 + versionReads += 1;
850 + return supportsGraphqlList;
851 + },
852 + listMergeRequests: (input) => {
853 + graphqlFlags.push(input.graphql);
854 + return Effect.succeed({
855 + items: [item],
856 + truncated: true,
857 + cursorAdvance: 1,
858 + resumeAfter: "eyJpZCI6IjcifQ",
859 + listStates: new Map([
860 + [7, { reviewDecision: "changes-requested" as const, checksState: null }],
861 + ]),
862 + });
863 + },
864 + });
865 + const listedWith = (
866 + supportsGraphqlList: Effect.Effect<
867 + boolean,
868 + GitLabPullRequestCli.GitLabPullRequestCliError
869 + >,
870 + ) =>
871 + providerReading(supportsGraphqlList).pipe(
872 + Effect.flatMap((provider) => provider.listChangeRequests(listing)),
873 + );
874 +
875 + const listed = yield* listedWith(Effect.succeed(true));
876 + expect(listed).toMatchObject({ resumeAfter: "eyJpZCI6IjcifQ", truncated: true });
877 + expect(listed).not.toHaveProperty("listStates");
878 + expect(listed.items[0]?.reviewDecision).toBe("changes-requested");
879 +
880 + // An unreadable version leaves the list on REST rather than failing it, and stays known.
881 + const unreadable = yield* providerReading(
882 + Effect.fail(
883 + new GitLabPullRequestCli.GitLabMergeRequestReadError({
884 + command: "glab",
885 + cwd: "/w",
886 + operation: "supportsGraphqlList",
887 + cause: null,
888 + }),
889 + ),
890 + );
891 + versionReads = 0;
892 + yield* unreadable.listChangeRequests(listing);
893 + yield* unreadable.listChangeRequests(listing);
894 + expect(graphqlFlags).toEqual([true, false, false]);
895 + expect(versionReads).toBe(1);
896 + }),
897 );
898
899 it.effect.each([
@@ -828,7 +902,7 @@ describe("review decisions", () => {
902 error: new GitLabPullRequestCli.GitLabMergeRequestReadError({
903 command: "glab",
904 cwd: "/w",
831 - operation: "getReviewDecisions",
905 + operation: "getListStates",
906 cause: null,
907 }),
908 },
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+69 -41
@@ -8,11 +8,11 @@ import type {
8 PullRequestActor,
9 PullRequestCapabilities,
10 PullRequestReaction,
11 - PullRequestReviewDecision,
11 PullRequestViewerPermissions,
12 } from "@t3tools/contracts";
13
14 import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
15 +import type { GitLabMergeRequestListState } from "./gitLabMergeRequestJson.ts";
16 import {
17 PullRequestProviderError,
18 type PullRequestProviderFailure,
@@ -94,6 +94,8 @@ const MERGE_REQUEST_DETAIL_TTL = Duration.minutes(1);
94 /** A project's merge methods change in its settings, which nobody does between page views. */
95 const PROJECT_MERGE_CAPABILITIES_TTL = Duration.minutes(15);
96 const READ_CACHE_CAPACITY = 256;
97 +/** A host's GitLab version only changes on upgrade. */
98 +const GRAPHQL_LIST_SUPPORT_TTL = Duration.hours(1);
99
100 function gitLabProviderFailure(
101 error: GitLabPullRequestCli.GitLabPullRequestCliError,
@@ -120,6 +122,25 @@ export const make = Effect.gen(function* () {
122 timeToLive: (exit) => (Exit.isSuccess(exit) ? MERGE_REQUEST_DETAIL_TTL : Duration.zero),
123 },
124 );
125 + const graphqlListSupport = yield* Cache.makeWith(
126 + (key: string) => {
127 + const [cwd, host] = JSON.parse(key) as [string, string | undefined];
128 + // A host whose version read fails keeps failing it; remember REST rather than ask each poll.
129 + return cli.supportsGraphqlList({ cwd, host }).pipe(
130 + Effect.catchIf(
131 + (cause) =>
132 + cause._tag !== "GitLabCliUnavailableError" &&
133 + cause._tag !== "GitLabCliAuthenticationError" &&
134 + cause._tag !== "GitLabCliRateLimitError",
135 + () => Effect.succeed(false),
136 + ),
137 + );
138 + },
139 + {
140 + capacity: READ_CACHE_CAPACITY,
141 + timeToLive: (exit) => (Exit.isSuccess(exit) ? GRAPHQL_LIST_SUPPORT_TTL : Duration.zero),
142 + },
143 + );
144 const projectMergeCapabilities = yield* Cache.makeWith(
145 (key: string) => {
146 const [cwd, repository, host] = JSON.parse(key) as [string, string, string];
@@ -190,14 +211,14 @@ export const make = Effect.gen(function* () {
211 }),
212 );
213
193 - // The rows were already read, so even a rate limit only leaves their decision unknown.
194 - const reviewDecisions = (input: Parameters<typeof cli.getReviewDecisions>[0]) =>
195 - cli.getReviewDecisions(input).pipe(
214 + // The rows were already read, so even a rate limit only leaves their states unknown.
215 + const listStates = (input: Parameters<typeof cli.getListStates>[0]) =>
216 + cli.getListStates(input).pipe(
217 Effect.catch((error) =>
197 - Effect.logWarning("GitLab merge request approval read failed", {
218 + Effect.logWarning("GitLab merge request approval and pipeline read failed", {
219 repository: input.repository,
220 reason: error._tag,
200 - }).pipe(Effect.as<ReadonlyMap<number, PullRequestReviewDecision | null>>(new Map())),
221 + }).pipe(Effect.as<ReadonlyMap<number, GitLabMergeRequestListState>>(new Map())),
222 ),
223 );
224
@@ -236,36 +257,43 @@ export const make = Effect.gen(function* () {
257 getViewer: (input) => cli.getViewerUsername(input).pipe(Effect.mapError(fail("getViewer"))),
258
259 listChangeRequests: (input) =>
239 - cli
240 - .listMergeRequests({
241 - cwd: input.cwd,
242 - host: input.host,
243 - repository: input.repository,
244 - state: input.state,
245 - involvement: input.involvement,
246 - viewer: input.viewer,
247 - limit: input.limit,
248 - query: input.query,
249 - cursor: input.cursor,
250 - filters: input.filters,
251 - })
252 - .pipe(
253 - Effect.flatMap((batch) =>
254 - reviewDecisions({
255 - cwd: input.cwd,
256 - host: input.host,
257 - repository: input.repository,
258 - numbers: batch.items.map((item) => item.number),
259 - }).pipe(
260 - Effect.map((decisions) => ({
261 - ...batch,
262 - items: batch.items.map((item) => withReviewDecision(item, decisions)),
263 - continues: true,
264 - })),
265 - ),
260 + Cache.get(graphqlListSupport, JSON.stringify([input.cwd, input.host])).pipe(
261 + // Without a known version the REST list still answers, only with fewer filters.
262 + Effect.orElseSucceed(() => false),
263 + Effect.flatMap((graphql) =>
264 + cli.listMergeRequests({
265 + cwd: input.cwd,
266 + host: input.host,
267 + repository: input.repository,
268 + state: input.state,
269 + involvement: input.involvement,
270 + viewer: input.viewer,
271 + limit: input.limit,
272 + query: input.query,
273 + cursor: input.cursor,
274 + filters: input.filters,
275 + graphql,
276 + }),
277 + ),
278 + Effect.flatMap(({ listStates: carried, ...batch }) =>
279 + (carried === undefined
280 + ? listStates({
281 + cwd: input.cwd,
282 + host: input.host,
283 + repository: input.repository,
284 + numbers: batch.items.map((item) => item.number),
285 + })
286 + : Effect.succeed(carried)
287 + ).pipe(
288 + Effect.map((states) => ({
289 + ...batch,
290 + items: batch.items.map((item) => withListState(item, states)),
291 + continues: true,
292 + })),
293 ),
267 - Effect.mapError(fail("listChangeRequests")),
294 ),
295 + Effect.mapError(fail("listChangeRequests")),
296 + ),
297
298 getFileStats: (input) =>
299 cli.getMergeRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
@@ -287,7 +315,7 @@ export const make = Effect.gen(function* () {
315 Effect.all(
316 [
317 mergeRequestWithStats(input),
290 - reviewDecisions({
318 + listStates({
319 cwd: input.cwd,
320 host: input.host,
321 repository: input.repository,
@@ -296,7 +324,7 @@ export const make = Effect.gen(function* () {
324 ],
325 { concurrency: 2 },
326 ).pipe(
299 - Effect.map(([mergeRequest, decisions]) => withReviewDecision(mergeRequest, decisions)),
327 + Effect.map(([mergeRequest, states]) => withListState(mergeRequest, states)),
328 Effect.mapError(fail("getChangeRequestSummary")),
329 ),
330
@@ -584,10 +612,10 @@ export const make = Effect.gen(function* () {
612 return provider;
613 });
614
587 -function withReviewDecision<Item extends { readonly number: number }>(
615 +function withListState<Item extends { readonly number: number }>(
616 item: Item,
589 - decisions: ReadonlyMap<number, PullRequestReviewDecision | null>,
590 -): Item & { readonly reviewDecision?: PullRequestReviewDecision | null } {
591 - const reviewDecision = decisions.get(item.number);
592 - return reviewDecision === undefined ? item : { ...item, reviewDecision };
617 + states: ReadonlyMap<number, GitLabMergeRequestListState>,
618 +): Item & Partial<GitLabMergeRequestListState> {
619 + const state = states.get(item.number);
620 + return state === undefined ? item : { ...item, ...state };
621 }
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
+172 -16
@@ -5,6 +5,8 @@ import {
5 decodeAwardEmojiJson,
6 decodeRepositoryBlobsJson,
7 decodeCommitsJson,
8 + decodeGraphqlListSupportJson,
9 + decodeMergeRequestGraphqlListJson,
10 decodeMergeMessagesJson,
11 decodeMergeRequestDetailJson,
12 decodeMergeRequestDiffsJson,
@@ -13,7 +15,7 @@ import {
15 decodeMergeRequestStatsJson,
16 decodeNotesJson,
17 decodeOwnAwardIdJson,
16 - decodeReviewDecisionsJson,
18 + decodeListStatesJson,
19 decodeTriggerJobChecksJson,
20 } from "./gitLabMergeRequestJson.ts";
21
@@ -708,10 +710,10 @@ describe("decodeRepositoryBlobsJson", () => {
710 });
711 });
712
711 -describe("decodeReviewDecisionsJson", () => {
712 - const decisionsOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
713 +describe("decodeListStatesJson", () => {
714 + const statesOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
715 expectSuccess(
714 - decodeReviewDecisionsJson(
716 + decodeListStatesJson(
717 JSON.stringify({
718 data: {
719 metadata: enterprise === null ? null : { enterprise },
@@ -723,6 +725,9 @@ describe("decodeReviewDecisionsJson", () => {
725 const approvedBy = (...usernames: ReadonlyArray<string>) => ({
726 nodes: usernames.map((username) => ({ username })),
727 });
728 + const reviewers = (...reviewStates: ReadonlyArray<string>) => ({
729 + nodes: reviewStates.map((reviewState) => ({ mergeRequestInteraction: { reviewState } })),
730 + });
731
732 it.each([
733 {
@@ -761,25 +766,89 @@ describe("decodeReviewDecisionsJson", () => {
766 approval: { approved: false, approvedBy: approvedBy() },
767 decision: null,
768 },
769 + {
770 + reading: "a reviewer requesting changes after another approved",
771 + enterprise: true,
772 + approval: {
773 + approved: true,
774 + approvedBy: approvedBy("julius"),
775 + reviewers: reviewers("APPROVED", "REQUESTED_CHANGES"),
776 + },
777 + decision: "changes-requested",
778 + },
779 + {
780 + reading: "a Community Edition reviewer requesting changes",
781 + enterprise: false,
782 + approval: {
783 + approved: false,
784 + approvedBy: approvedBy(),
785 + reviewers: reviewers("REQUESTED_CHANGES"),
786 + },
787 + decision: "changes-requested",
788 + },
789 + {
790 + reading: "reviewers who have not asked for changes",
791 + enterprise: false,
792 + approval: {
793 + approved: true,
794 + approvedBy: approvedBy("julius"),
795 + reviewers: reviewers("UNREVIEWED", "REVIEWED"),
796 + },
797 + decision: "approved",
798 + },
799 ])("reads $reading as $decision", ({ enterprise, approval, decision }) => {
765 - expect([...decisionsOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([[7, decision]]);
800 + expect([...statesOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([
801 + [7, { reviewDecision: decision, checksState: null }],
802 + ]);
803 });
804
805 + it.each([
806 + { pipeline: { status: "SUCCESS" }, checksState: "passing" },
807 + { pipeline: { status: "FAILED" }, checksState: "failing" },
808 + { pipeline: { status: "CANCELED" }, checksState: "failing" },
809 + { pipeline: { status: "RUNNING" }, checksState: "pending" },
810 + { pipeline: { status: "WAITING_FOR_RESOURCE" }, checksState: "pending" },
811 + { pipeline: { status: "MANUAL" }, checksState: null },
812 + { pipeline: { status: "SKIPPED" }, checksState: null },
813 + { pipeline: null, checksState: null },
814 + ])(
815 + "reads a $pipeline.status head pipeline as $checksState checks",
816 + ({ pipeline, checksState }) => {
817 + expect([
818 + ...statesOf(false, [
819 + { iid: "7", approved: false, approvedBy: approvedBy(), headPipeline: pipeline },
820 + ]),
821 + ]).toEqual([[7, { reviewDecision: null, checksState }]]);
822 + },
823 + );
824 +
825 it("leaves out a merge request it cannot key, and a project the reader cannot see", () => {
769 - expect([...decisionsOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
770 - expect([
771 - ...decisionsOf(null, [{ iid: "7", approved: false, approvedBy: approvedBy() }]),
772 - ]).toEqual([]);
773 - expect([
774 - ...decisionsOf(true, [
775 - { iid: "7", approved: null, approvedBy: approvedBy("julius") },
776 - { iid: "8", approved: true, approvedBy: null },
777 - ]),
778 - ]).toEqual([]);
826 + expect([...statesOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
827 expect(
780 - expectSuccess(decodeReviewDecisionsJson(JSON.stringify({ data: { project: null } }))),
828 + expectSuccess(decodeListStatesJson(JSON.stringify({ data: { project: null } }))),
829 ).toEqual(new Map());
830 });
831 +
832 + it("keeps the checks of a merge request whose approval it cannot judge", () => {
833 + expect([
834 + ...statesOf(null, [
835 + {
836 + iid: "7",
837 + approved: false,
838 + approvedBy: approvedBy(),
839 + headPipeline: { status: "FAILED" },
840 + },
841 + ]),
842 + ...statesOf(true, [
843 + { iid: "8", approved: null, approvedBy: approvedBy("julius") },
844 + { iid: "9", approved: true, approvedBy: null },
845 + ]),
846 + ]).toEqual([
847 + [7, { checksState: "failing" }],
848 + [8, { checksState: null }],
849 + [9, { checksState: null }],
850 + ]);
851 + });
852 });
853
854 describe("decodeMergeRequestStatsJson", () => {
@@ -838,6 +907,93 @@ describe("decodeMergeRequestStatsJson", () => {
907 });
908 });
909
910 +describe("decodeMergeRequestGraphqlListJson", () => {
911 + it("reads a row and its review state in one page, counting rows it cannot read", () => {
912 + const page = expectSuccess(
913 + decodeMergeRequestGraphqlListJson(
914 + JSON.stringify({
915 + data: {
916 + metadata: { enterprise: false },
917 + project: {
918 + mergeRequests: {
919 + pageInfo: { hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" },
920 + nodes: [
921 + {
922 + iid: "7",
923 + title: "Add the merge requests page",
924 + webUrl: "https://gitlab.com/acme/web/-/merge_requests/7",
925 + state: "opened",
926 + draft: true,
927 + createdAt: "2026-07-01T00:00:00Z",
928 + updatedAt: "2026-07-02T00:00:00Z",
929 + sourceBranch: "feat/page",
930 + targetBranch: "main",
931 + conflicts: true,
932 + mergeStatusEnum: "CHECKING",
933 + author: { username: "bilal", name: "Bilal", avatarUrl: null },
934 + labels: { nodes: [{ title: "bug" }] },
935 + approved: false,
936 + approvedBy: { nodes: [] },
937 + reviewers: {
938 + nodes: [
939 + {
940 + username: "julius",
941 + mergeRequestInteraction: { reviewState: "REQUESTED_CHANGES" },
942 + },
943 + ],
944 + },
945 + headPipeline: { status: "FAILED" },
946 + },
947 + { iid: "8" },
948 + ],
949 + },
950 + },
951 + },
952 + }),
953 + ),
954 + );
955 +
956 + expect(page.items).toEqual([
957 + expect.objectContaining({
958 + number: 7,
959 + state: "open",
960 + isDraft: true,
961 + mergeability: "conflicting",
962 + reviewRequestLogins: ["julius"],
963 + labels: [expect.objectContaining({ name: "bug" })],
964 + }),
965 + ]);
966 + expect([...page.states]).toEqual([
967 + [7, { reviewDecision: "changes-requested", checksState: "failing" }],
968 + ]);
969 + expect(page).toMatchObject({ rawCount: 2, hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" });
970 + });
971 + it("fails on a project the reader cannot see, rather than reading it as empty", () => {
972 + expect(
973 + Result.isFailure(
974 + decodeMergeRequestGraphqlListJson(
975 + JSON.stringify({ data: { metadata: { enterprise: true }, project: null } }),
976 + ),
977 + ),
978 + ).toBe(true);
979 + });
980 +});
981 +
982 +describe("decodeGraphqlListSupportJson", () => {
983 + it.each([
984 + { version: "17.8.4", supported: false },
985 + { version: "17.9.0", supported: true },
986 + { version: "19.6.0-pre", supported: true },
987 + { version: null, supported: false },
988 + ])("reads GitLab $version as supported: $supported", ({ version, supported }) => {
989 + expect(
990 + expectSuccess(
991 + decodeGraphqlListSupportJson(JSON.stringify({ data: { metadata: { version } } })),
992 + ),
993 + ).toBe(supported);
994 + });
995 +});
996 +
997 describe("decodeMergeMessagesJson", () => {
998 it("fails a partial response instead of reading errored fields as absent templates", () => {
999 const decoded = decodeMergeMessagesJson(
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+271 -47
@@ -7,6 +7,7 @@ import type {
7 PullRequestActor,
8 PullRequestCheck,
9 PullRequestCheckStatus,
10 + PullRequestChecksState,
11 PullRequestComment,
12 PullRequestCommit,
13 PullRequestLabel,
@@ -222,7 +223,9 @@ function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefine
223 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
224 }
225
225 -function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
226 +function toState(
227 + raw: Pick<Schema.Schema.Type<typeof RawMergeRequestSchema>, "state" | "merged_at">,
228 +): PullRequestState {
229 if (trimmed(raw.merged_at) !== null) return "merged";
230 switch (raw.state?.trim().toLowerCase()) {
231 case "merged":
@@ -235,7 +238,7 @@ function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullReq
238 }
239
240 function toMergeability(
238 - raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
241 + raw: Pick<Schema.Schema.Type<typeof RawMergeRequestSchema>, "has_conflicts" | "merge_status">,
242 ): PullRequestMergeability {
243 if (raw.has_conflicts === true) return "conflicting";
244 switch (raw.merge_status?.trim().toLowerCase()) {
@@ -1213,41 +1216,71 @@ export function decodeMergeMessagesJson(
1216 });
1217 }
1218
1216 -export const REVIEW_DECISIONS_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {
1219 +/** What a listed merge request needs beyond REST: its approval, reviewer and pipeline state. */
1220 +const LIST_STATE_GRAPHQL_FIELDS = `iid approved approvedBy(first: 1) { nodes { username } }
1221 + reviewers(first: 20) { nodes { username mergeRequestInteraction { reviewState } } }
1222 + headPipeline { status }`;
1223 +
1224 +export const LIST_STATES_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {
1225 metadata { enterprise }
1226 project(fullPath: $fullPath) {
1227 mergeRequests(iids: $iids, first: 100) {
1220 - nodes { iid approved approvedBy(first: 1) { nodes { username } } }
1228 + nodes { ${LIST_STATE_GRAPHQL_FIELDS} }
1229 }
1230 }
1231 }`;
1232
1225 -const RawReviewDecisionsSchema = Schema.Struct({
1226 - data: Schema.Struct({
1227 - metadata: Schema.optional(
1228 - Schema.NullOr(Schema.Struct({ enterprise: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
1233 +const RawMetadataSchema = Schema.optional(
1234 + Schema.NullOr(Schema.Struct({ enterprise: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
1235 +);
1236 +
1237 +const RawListStateFields = {
1238 + iid: Schema.String,
1239 + approved: Schema.optional(Schema.NullOr(Schema.Boolean)),
1240 + approvedBy: Schema.optional(
1241 + Schema.NullOr(
1242 + Schema.Struct({
1243 + nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
1244 + }),
1245 ),
1230 - project: Schema.NullOr(
1246 + ),
1247 + reviewers: Schema.optional(
1248 + Schema.NullOr(
1249 Schema.Struct({
1232 - mergeRequests: Schema.optional(
1250 + nodes: Schema.optional(
1251 Schema.NullOr(
1234 - Schema.Struct({
1235 - nodes: Schema.Array(
1236 - Schema.NullOr(
1237 - Schema.Struct({
1238 - iid: Schema.String,
1239 - approved: Schema.optional(Schema.NullOr(Schema.Boolean)),
1240 - approvedBy: Schema.optional(
1241 - Schema.NullOr(
1242 - Schema.Struct({
1243 - nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
1244 - }),
1245 - ),
1252 + Schema.Array(
1253 + Schema.NullOr(
1254 + Schema.Struct({
1255 + username: Schema.optional(Schema.NullOr(Schema.String)),
1256 + mergeRequestInteraction: Schema.optional(
1257 + Schema.NullOr(
1258 + Schema.Struct({ reviewState: Schema.optional(Schema.NullOr(Schema.String)) }),
1259 ),
1247 - }),
1248 - ),
1260 + ),
1261 + }),
1262 ),
1250 - }),
1263 + ),
1264 + ),
1265 + ),
1266 + }),
1267 + ),
1268 + ),
1269 + headPipeline: Schema.optional(
1270 + Schema.NullOr(Schema.Struct({ status: Schema.optional(Schema.NullOr(Schema.String)) })),
1271 + ),
1272 +};
1273 +
1274 +const RawListStateNodeSchema = Schema.Struct(RawListStateFields);
1275 +
1276 +const RawListStatesSchema = Schema.Struct({
1277 + data: Schema.Struct({
1278 + metadata: RawMetadataSchema,
1279 + project: Schema.NullOr(
1280 + Schema.Struct({
1281 + mergeRequests: Schema.optional(
1282 + Schema.NullOr(
1283 + Schema.Struct({ nodes: Schema.Array(Schema.NullOr(RawListStateNodeSchema)) }),
1284 ),
1285 ),
1286 }),
@@ -1255,43 +1288,234 @@ const RawReviewDecisionsSchema = Schema.Struct({
1288 }),
1289 });
1290
1258 -const decodeReviewDecisions = decodeJsonResult(RawReviewDecisionsSchema);
1291 +const decodeListStates = decodeJsonResult(RawListStatesSchema);
1292 +
1293 +export interface GitLabMergeRequestListState {
1294 + /** Absent when the approval state can't be judged. */
1295 + readonly reviewDecision?: PullRequestReviewDecision | null;
1296 + readonly checksState: PullRequestChecksState | null;
1297 +}
1298 +
1299 +function toChecksState(pipelineStatus: string | null | undefined): PullRequestChecksState | null {
1300 + if (pipelineStatus == null) return null;
1301 + switch (toPipelineStatus(pipelineStatus)) {
1302 + case "success":
1303 + return "passing";
1304 + case "failure":
1305 + case "cancelled":
1306 + return "failing";
1307 + case "pending":
1308 + return "pending";
1309 + default:
1310 + return null;
1311 + }
1312 +}
1313
1314 /**
1315 * Only Enterprise Edition holds `approved` to the project's approval rules, so an unapproved
1316 * merge request there still needs review even when someone, such as a bot, approved it.
1317 * Community Edition reports `approved` once anyone approves and requires no review.
1318 + * A reviewer asking for changes outranks both, as it does on GitHub.
1319 */
1265 -export function decodeReviewDecisionsJson(
1320 +function toListState(
1321 + node: typeof RawListStateNodeSchema.Type,
1322 + enterprise: boolean | null | undefined,
1323 +): GitLabMergeRequestListState {
1324 + const checksState = toChecksState(node.headPipeline?.status);
1325 + if (
1326 + node.reviewers?.nodes?.some(
1327 + (reviewer) => reviewer?.mergeRequestInteraction?.reviewState === "REQUESTED_CHANGES",
1328 + )
1329 + ) {
1330 + return { reviewDecision: "changes-requested", checksState };
1331 + }
1332 + const approvals = node.approvedBy?.nodes?.length;
1333 + if (
1334 + node.approved == null ||
1335 + approvals === undefined ||
1336 + (node.approved === false && approvals === 0 && enterprise == null)
1337 + ) {
1338 + return { checksState };
1339 + }
1340 + return {
1341 + reviewDecision:
1342 + node.approved === false && (enterprise || approvals > 0)
1343 + ? "review-required"
1344 + : approvals > 0
1345 + ? "approved"
1346 + : null,
1347 + checksState,
1348 + };
1349 +}
1350 +
1351 +export function decodeListStatesJson(
1352 raw: string,
1267 -): Result.Result<ReadonlyMap<number, PullRequestReviewDecision | null>, DecodeFailure> {
1268 - const decoded = decodeReviewDecisions(raw);
1353 +): Result.Result<ReadonlyMap<number, GitLabMergeRequestListState>, DecodeFailure> {
1354 + const decoded = decodeListStates(raw);
1355 if (!Result.isSuccess(decoded)) {
1356 return Result.fail(decoded.failure);
1357 }
1358 const enterprise = decoded.success.data.metadata?.enterprise;
1273 - const decisions = new Map<number, PullRequestReviewDecision | null>();
1359 + const states = new Map<number, GitLabMergeRequestListState>();
1360 for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) {
1361 const number = Number(node?.iid);
1276 - if (
1277 - node === null ||
1278 - !Number.isSafeInteger(number) ||
1279 - node.approved == null ||
1280 - node.approvedBy?.nodes == null
1281 - )
1282 - continue;
1283 - const approvals = node.approvedBy.nodes.length;
1284 - if (node.approved === false && approvals === 0 && enterprise == null) continue;
1285 - decisions.set(
1362 + if (node === null || !Number.isSafeInteger(number)) continue;
1363 + states.set(number, toListState(node, enterprise));
1364 + }
1365 + return Result.succeed(states);
1366 +}
1367 +
1368 +/** The fields a listed merge request needs, so one GraphQL read stands in for REST and states. */
1369 +export const LIST_ITEM_GRAPHQL_FIELDS = `${LIST_STATE_GRAPHQL_FIELDS}
1370 + title webUrl state draft createdAt updatedAt mergedAt sourceBranch targetBranch
1371 + conflicts mergeStatusEnum author { username name avatarUrl } labels(first: 100) { nodes { title } }`;
1372 +
1373 +const RawGraphqlListNodeSchema = Schema.Struct({
1374 + ...RawListStateFields,
1375 + title: Schema.String,
1376 + webUrl: Schema.String,
1377 + state: Schema.optional(Schema.NullOr(Schema.String)),
1378 + draft: Schema.optional(Schema.NullOr(Schema.Boolean)),
1379 + createdAt: Schema.String,
1380 + updatedAt: Schema.String,
1381 + mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
1382 + sourceBranch: Schema.String,
1383 + targetBranch: Schema.String,
1384 + conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
1385 + mergeStatusEnum: Schema.optional(Schema.NullOr(Schema.String)),
1386 + author: Schema.optional(
1387 + Schema.NullOr(
1388 + Schema.Struct({
1389 + username: Schema.optional(Schema.NullOr(Schema.String)),
1390 + name: Schema.optional(Schema.NullOr(Schema.String)),
1391 + avatarUrl: Schema.optional(Schema.NullOr(Schema.String)),
1392 + }),
1393 + ),
1394 + ),
1395 + labels: Schema.optional(
1396 + Schema.NullOr(
1397 + Schema.Struct({
1398 + nodes: Schema.optional(
1399 + Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Struct({ title: Schema.String })))),
1400 + ),
1401 + }),
1402 + ),
1403 + ),
1404 +});
1405 +
1406 +// GitLab answers `project: null` for a project the reader cannot see, which REST reports as an error.
1407 +const RawGraphqlListSchema = Schema.Struct({
1408 + data: Schema.Struct({
1409 + metadata: RawMetadataSchema,
1410 + project: Schema.Struct({
1411 + mergeRequests: Schema.Struct({
1412 + pageInfo: Schema.Struct({
1413 + hasNextPage: Schema.Boolean,
1414 + endCursor: Schema.optional(Schema.NullOr(Schema.String)),
1415 + }),
1416 + nodes: Schema.Array(Schema.Unknown),
1417 + }),
1418 + }),
1419 + }),
1420 +});
1421 +
1422 +const decodeGraphqlList = decodeJsonResult(RawGraphqlListSchema);
1423 +const decodeGraphqlListNode = Schema.decodeUnknownExit(RawGraphqlListNodeSchema);
1424 +
1425 +export interface GitLabMergeRequestGraphqlPage {
1426 + readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
1427 + readonly states: ReadonlyMap<number, GitLabMergeRequestListState>;
1428 + /** Count before decoding, so a page of rows that fail to decode still moves on. */
1429 + readonly rawCount: number;
1430 + readonly hasNextPage: boolean;
1431 + readonly endCursor: string | null;
1432 +}
1433 +
1434 +export function decodeMergeRequestGraphqlListJson(
1435 + raw: string,
1436 +): Result.Result<GitLabMergeRequestGraphqlPage, DecodeFailure> {
1437 + const decoded = decodeGraphqlList(raw);
1438 + if (!Result.isSuccess(decoded)) {
1439 + return Result.fail(decoded.failure);
1440 + }
1441 + const page = decoded.success.data.project.mergeRequests;
1442 + const enterprise = decoded.success.data.metadata?.enterprise;
1443 + const items: GitLabMergeRequestListItem[] = [];
1444 + const states = new Map<number, GitLabMergeRequestListState>();
1445 + for (const entry of page.nodes) {
1446 + const exit = decodeGraphqlListNode(entry);
1447 + if (!Exit.isSuccess(exit)) continue;
1448 + const node = exit.value;
1449 + const number = Number(node.iid);
1450 + if (!Number.isSafeInteger(number)) continue;
1451 + items.push({
1452 number,
1287 - node.approved === false && (enterprise || approvals > 0)
1288 - ? "review-required"
1289 - : approvals > 0
1290 - ? "approved"
1291 - : null,
1292 - );
1453 + title: node.title,
1454 + url: node.webUrl,
1455 + author: toActor(
1456 + node.author == null
1457 + ? null
1458 + : {
1459 + username: node.author.username ?? "",
1460 + name: node.author.name,
1461 + avatar_url: node.author.avatarUrl,
1462 + },
1463 + ),
1464 + headBranch: node.sourceBranch,
1465 + baseBranch: node.targetBranch,
1466 + state: toState({ state: node.state, merged_at: node.mergedAt }),
1467 + isDraft: node.draft ?? false,
1468 + mergeability: toMergeability({
1469 + has_conflicts: node.conflicts,
1470 + merge_status: node.mergeStatusEnum,
1471 + }),
1472 + additions: 0,
1473 + deletions: 0,
1474 + createdAt: node.createdAt,
1475 + updatedAt: node.updatedAt,
1476 + reviewRequestLogins: (node.reviewers?.nodes ?? []).flatMap((reviewer) => {
1477 + const login = trimmed(reviewer?.username);
1478 + return login === null ? [] : [login];
1479 + }),
1480 + labels: toLabels((node.labels?.nodes ?? []).flatMap((label) => (label ? [label.title] : []))),
1481 + });
1482 + states.set(number, toListState(node, enterprise));
1483 + }
1484 + return Result.succeed({
1485 + items,
1486 + states,
1487 + rawCount: page.nodes.length,
1488 + hasNextPage: page.pageInfo.hasNextPage,
1489 + endCursor: trimmed(page.pageInfo.endCursor),
1490 + });
1491 +}
1492 +
1493 +export const SERVER_VERSION_GRAPHQL_QUERY = "{ metadata { version } }";
1494 +
1495 +const decodeServerVersion = decodeJsonResult(
1496 + Schema.Struct({
1497 + data: Schema.Struct({
1498 + metadata: Schema.optional(
1499 + Schema.NullOr(Schema.Struct({ version: Schema.optional(Schema.NullOr(Schema.String)) })),
1500 + ),
1501 + }),
1502 + }),
1503 +);
1504 +
1505 +/**
1506 + * Whether the GraphQL merge request list takes every filter the REST list does: `search` came
1507 + * last, in 17.9. An instance that hides its version keeps REST.
1508 + */
1509 +export function decodeGraphqlListSupportJson(raw: string): Result.Result<boolean, DecodeFailure> {
1510 + const decoded = decodeServerVersion(raw);
1511 + if (!Result.isSuccess(decoded)) {
1512 + return Result.fail(decoded.failure);
1513 }
1294 - return Result.succeed(decisions);
1514 + const match = /^(\d+)\.(\d+)/u.exec(decoded.success.data.metadata?.version?.trim() ?? "");
1515 + if (match === null) return Result.succeed(false);
1516 + const major = Number(match[1]);
1517 + const minor = Number(match[2]);
1518 + return Result.succeed(major > 17 || (major === 17 && minor >= 9));
1519 }
1520
1521 /**