@devries-cameron20 / t3code Mirror · read-only / commits / d426166dfd
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 04:15 UTC

fix(server): load merge request diffs on older GitLab (#15886)

Arav Jain committed Oct 18, 2026 at 14:29 UTC d426166dfd716fe40189cf556d1760e89a255e63
3 files changed +269 -8
packages/source-control-gitlab/src/server/GitLabPullRequestCli.legacy.test.ts new
+205
@@ -0,0 +1,205 @@
1 +import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import { ChildProcessSpawner } from "effect/process";
5 +import { VcsProcessExitError } from "@t3tools/contracts";
6 +
7 +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
8 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
9 +import * as GitLabCli from "./GitLabCli.ts";
10 +import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
11 +
12 +const run = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
13 +const layer = it.layer(
14 + GitLabPullRequestCli.layer.pipe(
15 + Layer.provide(GitLabCli.layer),
16 + Layer.provide(TestSourceControlHost.layer({ process: { run } })),
17 + ),
18 +);
19 +const input = { cwd: "/repo", repository: "acme/nested/web", number: 7 };
20 +const file = {
21 + old_path: "src/old.ts",
22 + new_path: "src/new.ts",
23 + renamed_file: true,
24 + new_file: false,
25 + deleted_file: false,
26 + a_mode: "100644",
27 + b_mode: "100644",
28 + diff: "@@ -1 +1 @@\n-before\n+after\n",
29 +};
30 +/** Supplies JSON at the process boundary while retaining the real CLI adapter and decoder. */
31 +function output(body: unknown, stdoutTruncated = false) {
32 + return Effect.succeed({
33 + exitCode: ChildProcessSpawner.ExitCode(0),
34 + stdout: JSON.stringify(body),
35 + stderr: "",
36 + stdoutTruncated,
37 + stderrTruncated: false,
38 + });
39 +}
40 +/** Supplies the failure classification produced by VcsProcess for an unsuccessful glab call. */
41 +function failure(failureKind: "not-found" | "authentication" | "rate-limited" | "command-failed") {
42 + return Effect.fail(
43 + new VcsProcessExitError({
44 + operation: "GitLabCli.execute",
45 + command: "glab",
46 + cwd: input.cwd,
47 + exitCode: 1,
48 + detail: "GitLab HTTP failure",
49 + failureKind,
50 + }),
51 + );
52 +}
53 +afterEach(() => run.mockReset());
54 +
55 +layer("legacy GitLab diff requests through GitLabCli", (it) => {
56 + it.effect.each([0, 1, 100, 247])("returns %s legacy changes as one terminal slice", (count) =>
57 + Effect.gen(function* () {
58 + run.mockReturnValueOnce(failure("not-found"));
59 + run.mockReturnValueOnce(
60 + output({
61 + changes: Array.from({ length: count }, () => file),
62 + overflow: false,
63 + changes_count: String(count),
64 + }),
65 + );
66 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
67 + const result = yield* cli.getMergeRequestDiff(input);
68 + expect(result.nextCursor).toBeNull();
69 + expect(result.truncated).toBe(false);
70 + expect(result.patch.match(/^diff --git /gm)?.length ?? 0).toBe(count);
71 + if (count > 0) {
72 + expect(result.patch).toContain("rename from src/old.ts\nrename to src/new.ts");
73 + expect(result.patch).toContain("@@ -1 +1 @@\n-before\n+after\n");
74 + expect(result.patch.endsWith("\n")).toBe(true);
75 + }
76 + expect(run.mock.calls.map(([call]) => call.args)).toEqual([
77 + ["api", "projects/acme%2Fnested%2Fweb/merge_requests/7/diffs?per_page=100&page=1"],
78 + ["api", "projects/acme%2Fnested%2Fweb/merge_requests/7/changes?access_raw_diffs=true"],
79 + ]);
80 + expect(run.mock.calls[1]?.[0]).toMatchObject({
81 + cwd: "/repo",
82 + maxOutputBytes: 8 * 1024 * 1024,
83 + timeoutMs: 60_000,
84 + });
85 + }),
86 + );
87 + it.effect.each([false, true])("accepts an unavailable legacy count (overflow: %s)", (overflow) =>
88 + Effect.gen(function* () {
89 + run.mockReturnValueOnce(failure("not-found"));
90 + run.mockReturnValueOnce(output({ changes: [file], changes_count: null, overflow }));
91 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
92 + const result = yield* cli.getMergeRequestDiff(input);
93 + expect(result.truncated).toBe(overflow);
94 + expect(result.nextCursor).toBeNull();
95 + expect(result.patch).toContain("@@ -1 +1 @@\n-before\n+after\n");
96 + }),
97 + );
98 + it.effect.each([{ overflow: true }, { changes_count: "247+" }])(
99 + "marks legacy limits %j truncated",
100 + (metadata) =>
101 + Effect.gen(function* () {
102 + run.mockReturnValueOnce(failure("not-found"));
103 + run.mockReturnValueOnce(output({ changes: [file], ...metadata }));
104 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
105 + expect(yield* cli.getMergeRequestDiff(input)).toMatchObject({
106 + truncated: true,
107 + nextCursor: null,
108 + });
109 + }),
110 + );
111 + it.effect.each([{}, { changes: null }, { changes: {} }, [file]])(
112 + "rejects malformed legacy wrapper %j",
113 + (body) =>
114 + Effect.gen(function* () {
115 + run.mockReturnValueOnce(failure("not-found"));
116 + run.mockReturnValueOnce(output(body));
117 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
118 + const error = yield* cli.getMergeRequestDiff(input).pipe(Effect.flip);
119 + assert.equal(error._tag, "GitLabMergeRequestReadError");
120 + }),
121 + );
122 + it.effect.each([false, true])("marks skipped file entries truncated (legacy: %s)", (legacy) =>
123 + Effect.gen(function* () {
124 + const entries = [file, { new_path: "missing-old-path.ts" }];
125 + if (legacy) run.mockReturnValueOnce(failure("not-found"));
126 + run.mockReturnValueOnce(output(legacy ? { changes: entries } : entries));
127 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
128 + const result = yield* cli.getMergeRequestDiff(input);
129 + expect(result.truncated).toBe(true);
130 + expect(result.nextCursor).toBeNull();
131 + expect(result.patch.match(/^diff --git /gm)).toHaveLength(1);
132 + expect(result.patch).toContain("@@ -1 +1 @@\n-before\n+after\n");
133 + }),
134 + );
135 + it.effect("rejects a byte-truncated legacy response", () =>
136 + Effect.gen(function* () {
137 + run.mockReturnValueOnce(failure("not-found"));
138 + run.mockReturnValueOnce(output({ changes: [file] }, true));
139 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
140 + expect((yield* cli.getMergeRequestDiff(input).pipe(Effect.flip))._tag).toBe(
141 + "GitLabMergeRequestReadError",
142 + );
143 + }),
144 + );
145 + it.effect.each(["authentication", "rate-limited", "command-failed"] as const)(
146 + "does not fall back on %s",
147 + (kind) =>
148 + Effect.gen(function* () {
149 + run.mockReturnValueOnce(failure(kind));
150 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
151 + yield* cli.getMergeRequestDiff(input).pipe(Effect.flip);
152 + expect(run).toHaveBeenCalledTimes(1);
153 + }),
154 + );
155 + it.effect("does not fall back for a missing commit or later MR page", () =>
156 + Effect.gen(function* () {
157 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
158 + for (const target of [
159 + { ...input, commit: "abc1234" },
160 + { ...input, cursor: "2" },
161 + ]) {
162 + run.mockReturnValueOnce(failure("not-found"));
163 + yield* cli.getMergeRequestDiff(target).pipe(Effect.flip);
164 + }
165 + expect(run).toHaveBeenCalledTimes(2);
166 + }),
167 + );
168 + it.effect("propagates failure of the legacy endpoint", () =>
169 + Effect.gen(function* () {
170 + run.mockReturnValueOnce(failure("not-found"));
171 + run.mockReturnValueOnce(failure("not-found"));
172 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
173 + expect((yield* cli.getMergeRequestDiff(input).pipe(Effect.flip))._tag).toBe(
174 + "GitLabCliCommandError",
175 + );
176 + expect(run).toHaveBeenCalledTimes(2);
177 + }),
178 + );
179 + it.effect("does not fall back on an unreadable successful modern response", () =>
180 + Effect.gen(function* () {
181 + run.mockReturnValueOnce(output({ changes: [file] }));
182 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
183 + expect((yield* cli.getMergeRequestDiff(input).pipe(Effect.flip))._tag).toBe(
184 + "GitLabMergeRequestReadError",
185 + );
186 + expect(run).toHaveBeenCalledTimes(1);
187 + }),
188 + );
189 + it.effect("keeps modern pagination without requesting legacy changes", () =>
190 + Effect.gen(function* () {
191 + run.mockReturnValueOnce(output(Array.from({ length: 100 }, () => file)));
192 + run.mockReturnValueOnce(output([file]));
193 + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
194 + const first = yield* cli.getMergeRequestDiff(input);
195 + expect(first.nextCursor).toBe("2");
196 + expect(
197 + (yield* cli.getMergeRequestDiff({ ...input, cursor: first.nextCursor! })).nextCursor,
198 + ).toBeNull();
199 + expect(run).toHaveBeenCalledTimes(2);
200 + expect(run.mock.calls[1]?.[0].args).toContain(
201 + "projects/acme%2Fnested%2Fweb/merge_requests/7/diffs?per_page=100&page=2",
202 + );
203 + }),
204 + );
205 +});
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+28 -3
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import * as Result from "effect/Result";
5 import * as Schema from "effect/Schema";
6 +import { VcsProcessExitError } from "@t3tools/contracts";
7 import type {
8 PullRequestAction,
9 PullRequestComment,
@@ -30,6 +31,7 @@ import {
31 decodeDiscussionsJson,
32 decodeMergeRequestDetailJson,
33 decodeMergeRequestDiffsJson,
34 + decodeMergeRequestChangesJson,
35 decodeMergeRequestListJson,
36 decodeNotesJson,
37 decodeOwnAwardIdJson,
@@ -182,6 +184,7 @@ const COMMIT_PAGE_SIZE = 100;
184 const CONVERSATION_PAGES = 10;
185 const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
186 const DIFF_TIMEOUT_MS = 60_000;
187 +const isVcsProcessExitError = Schema.is(VcsProcessExitError);
188 const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
189
190 export interface GitLabMergeRequestListBatch {
@@ -620,7 +623,27 @@ export const make = Effect.gen(function* () {
623 maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
624 timeoutMs: DIFF_TIMEOUT_MS,
625 }).pipe(
623 - Effect.flatMap((result) => {
626 + Effect.map((result) => ({ result, legacy: false })),
627 + Effect.catchTags({
628 + GitLabCliCommandError: (error) => {
629 + if (
630 + input.commit !== undefined ||
631 + input.page !== 1 ||
632 + !isVcsProcessExitError(error.cause) ||
633 + error.cause.failureKind !== "not-found"
634 + ) {
635 + return Effect.fail(error);
636 + }
637 + // GitLab before 15.7 has no /diffs endpoint. /changes returns one complete slice.
638 + return api({
639 + cwd: input.cwd,
640 + path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/changes?access_raw_diffs=true`,
641 + maxOutputBytes: DIFF_MAX_OUTPUT_BYTES,
642 + timeoutMs: DIFF_TIMEOUT_MS,
643 + }).pipe(Effect.map((result) => ({ result, legacy: true })));
644 + },
645 + }),
646 + Effect.flatMap(({ result, legacy }) => {
647 // A byte-truncated response is a JSON prefix, so this page cannot be read at all.
648 // Answering with no cursor would call the diff whole while silently dropping this page
649 // and every one after it, so the read fails and says which page could not be had.
@@ -636,7 +659,9 @@ export const make = Effect.gen(function* () {
659 }),
660 );
661 }
639 - const decoded = decodeMergeRequestDiffsJson(result.stdout.trim());
662 + const decoded = (legacy ? decodeMergeRequestChangesJson : decodeMergeRequestDiffsJson)(
663 + result.stdout.trim(),
664 + );
665 if (!Result.isSuccess(decoded)) {
666 return Effect.fail(
667 new GitLabMergeRequestReadError({
@@ -650,7 +675,7 @@ export const make = Effect.gen(function* () {
675 const patch = decoded.success.patch;
676 // Counted before decoding, so a page whose files all failed to decode still moves on
677 // rather than pointing the reader back at the page it just read.
653 - const morePages = decoded.success.rawCount >= MAX_PAGE_SIZE;
678 + const morePages = !legacy && decoded.success.rawCount >= MAX_PAGE_SIZE;
679 return Effect.succeed({
680 // The slice ends on a newline, so a file GitLab gave a header and no hunks for does
681 // not run into the first line of the next slice.
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+36 -5
@@ -356,6 +356,13 @@ const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
356 const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
357 const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
358 const decodeCommit = decodeJsonResult(RawCommitSchema);
359 +const decodeMergeRequestChanges = decodeJsonResult(
360 + Schema.Struct({
361 + changes: Schema.Array(Schema.Unknown),
362 + overflow: Schema.optional(Schema.Boolean),
363 + changes_count: Schema.optional(Schema.NullOr(Schema.String)),
364 + }),
365 +);
366 const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
367 const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
368 const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
@@ -613,11 +620,35 @@ export function decodeMergeRequestDiffsJson(
620 if (!Result.isSuccess(decoded)) {
621 return Result.fail(decoded.failure);
622 }
623 + return Result.succeed(mergeRequestPatch(decoded.success));
624 +}
625 +
626 +/** Older GitLab instances return all files in a non-paginated merge request wrapper. */
627 +export function decodeMergeRequestChangesJson(
628 + raw: string,
629 +): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
630 + const decoded = decodeMergeRequestChanges(raw);
631 + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
632 + const patch = mergeRequestPatch(decoded.success.changes);
633 + return Result.succeed({
634 + ...patch,
635 + truncated:
636 + patch.truncated ||
637 + decoded.success.overflow === true ||
638 + decoded.success.changes_count?.endsWith("+") === true,
639 + });
640 +}
641 +
642 +/** Builds file patches, retaining raw counts and recording files whose contents are missing. */
643 +function mergeRequestPatch(entries: ReadonlyArray<unknown>): GitLabMergeRequestPatch {
644 const sections: string[] = [];
645 let truncated = false;
618 - for (const entry of decoded.success) {
646 + for (const entry of entries) {
647 const file = decodeDiffEntry(entry);
620 - if (Exit.isFailure(file)) continue;
648 + if (Exit.isFailure(file)) {
649 + truncated = true;
650 + continue;
651 + }
652 const value = file.value;
653 const hunks = value.diff ?? "";
654 if (hunks.length === 0) {
@@ -639,11 +670,11 @@ export function decodeMergeRequestDiffsJson(
670 ].join("\n");
671 sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
672 }
642 - return Result.succeed({
673 + return {
674 patch: sections.join("\n"),
675 truncated,
645 - rawCount: decoded.success.length,
646 - });
676 + rawCount: entries.length,
677 + };
678 }
679
680 const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {