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

main
ts 428 lines 14.8 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it, afterEach, expect, vi } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Path from "effect/Path";
7 import { ChildProcessSpawner } from "effect/process";
8
9 import { VcsProcessExitError } from "@t3tools/contracts";
10
11 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
13 import * as GitLabCli from "./GitLabCli.ts";
14
15 const mockedRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
16 const layer = it.layer(
17 GitLabCli.layer.pipe(
18 Layer.provide(TestSourceControlHost.layer({ process: { run: mockedRun } })),
19 Layer.provideMerge(NodeServices.layer),
20 ),
21 );
22
23 function processOutput(stdout: string): SourceControlHost.SourceControlProcessOutput {
24 return {
25 exitCode: ChildProcessSpawner.ExitCode(0),
26 stdout,
27 stderr: "",
28 stdoutTruncated: false,
29 stderrTruncated: false,
30 };
31 }
32
33 afterEach(() => {
34 mockedRun.mockReset();
35 });
36
37 layer("GitLabCli.layer", (it) => {
38 it.effect("parses merge request view output", () =>
39 Effect.gen(function* () {
40 mockedRun.mockReturnValueOnce(
41 Effect.succeed(
42 processOutput(
43 JSON.stringify({
44 iid: 42,
45 title: "Add MR thread creation",
46 web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
47 target_branch: "main",
48 source_branch: "feature/mr-threads",
49 sha: "a".repeat(40),
50 state: "closed",
51 closed_at: "2026-08-23T10:00:00Z",
52 source_project_id: 101,
53 target_project_id: 100,
54 source_project: {
55 path_with_namespace: "octocat/t3code",
56 },
57 }),
58 ),
59 ),
60 );
61
62 const result = yield* Effect.gen(function* () {
63 const glab = yield* GitLabCli.GitLabCli;
64 return yield* glab.getMergeRequest({
65 cwd: "/repo",
66 reference: "42",
67 });
68 });
69
70 assert.deepStrictEqual(result, {
71 number: 42,
72 title: "Add MR thread creation",
73 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
74 baseRefName: "main",
75 headRefName: "feature/mr-threads",
76 headSha: "a".repeat(40),
77 state: "closed",
78 closedAt: "2026-08-23T10:00:00Z",
79 mergedAt: null,
80 isCrossRepository: true,
81 headRepositoryNameWithOwner: "octocat/t3code",
82 headRepositoryOwnerLogin: "octocat",
83 });
84 expect(mockedRun).toHaveBeenCalledWith(
85 expect.objectContaining({
86 command: "glab",
87 cwd: "/repo",
88 args: ["mr", "view", "--output", "json", "--", "42"],
89 }),
90 );
91 const classifyFailure = mockedRun.mock.calls.at(-1)?.[0].classifyFailure;
92 assert.strictEqual(
93 classifyFailure?.(
94 "x gitlab.example.test has not been authenticated with glab. Run `glab auth login`",
95 ),
96 "authentication",
97 );
98 assert.strictEqual(
99 classifyFailure?.(
100 'Failed to get merge request 42: oauth2: "invalid_grant" "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."',
101 ),
102 "authentication",
103 );
104 }),
105 );
106
107 // A strictly confined glab (Snap) has a private /tmp, so it cannot open the server's body file.
108 it.effect("sends the merge request description to glab on stdin, not as a file path", () =>
109 Effect.gen(function* () {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" });
113 const bodyFile = path.join(bodyDir, "t3code-pr-body.md");
114 yield* fileSystem.writeFileString(bodyFile, "## Summary\n\nFixes the thing.\n");
115 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
116
117 const glab = yield* GitLabCli.GitLabCli;
118 yield* glab.createMergeRequest({
119 cwd: "/repo",
120 baseBranch: "main",
121 headSelector: "feature/mr",
122 title: "Add MR",
123 bodyFile,
124 });
125
126 const call = mockedRun.mock.calls.at(-1)?.[0];
127 expect(call?.args.join(" ")).not.toContain(bodyFile);
128 expect(call?.args).toContain("description=@-");
129 assert.strictEqual(call?.stdin, "## Summary\n\nFixes the thing.\n");
130 }).pipe(Effect.scoped),
131 );
132
133 it.effect("fails with a typed error and skips glab when the description cannot be read", () =>
134 Effect.gen(function* () {
135 const fileSystem = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const bodyDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-gitlab-mr-body-" });
138 const glab = yield* GitLabCli.GitLabCli;
139 const error = yield* glab
140 .createMergeRequest({
141 cwd: "/repo",
142 baseBranch: "main",
143 headSelector: "feature/mr",
144 title: "Add MR",
145 bodyFile: path.join(bodyDir, "missing.md"),
146 })
147 .pipe(Effect.flip);
148
149 assert.strictEqual(error._tag, "GitLabMergeRequestBodyReadError");
150 assert.strictEqual(error.detail, "The merge request description could not be read.");
151 expect(mockedRun).not.toHaveBeenCalled();
152 }).pipe(Effect.scoped),
153 );
154
155 it.effect("skips invalid entries when parsing MR lists", () =>
156 Effect.gen(function* () {
157 mockedRun.mockReturnValueOnce(
158 Effect.succeed(
159 processOutput(
160 JSON.stringify([
161 {
162 iid: 0,
163 title: "invalid",
164 web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
165 target_branch: "main",
166 source_branch: "feature/invalid",
167 },
168 {
169 iid: 43,
170 title: " Valid MR ",
171 web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
172 target_branch: " main ",
173 source_branch: " feature/mr-list ",
174 state: "merged",
175 merged_at: "2026-08-23T11:00:00Z",
176 },
177 ]),
178 ),
179 ),
180 );
181
182 const result = yield* Effect.gen(function* () {
183 const glab = yield* GitLabCli.GitLabCli;
184 return yield* glab.listMergeRequests({
185 cwd: "/repo",
186 headSelector: "feature/mr-list",
187 state: "all",
188 });
189 });
190
191 assert.deepStrictEqual(result, [
192 {
193 number: 43,
194 title: "Valid MR",
195 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
196 baseRefName: "main",
197 headRefName: "feature/mr-list",
198 state: "merged",
199 closedAt: null,
200 mergedAt: "2026-08-23T11:00:00Z",
201 },
202 ]);
203 expect(mockedRun).toHaveBeenCalledWith(
204 expect.objectContaining({
205 command: "glab",
206 cwd: "/repo",
207 args: [
208 "mr",
209 "list",
210 "--source-branch",
211 "feature/mr-list",
212 "--all",
213 "--per-page",
214 "20",
215 "--output",
216 "json",
217 ],
218 }),
219 );
220 }),
221 );
222
223 it.effect(
224 "retries oversized MR lists with smaller pages without losing same-named branches",
225 () =>
226 Effect.gen(function* () {
227 const entries = Array.from({ length: 4 }, (_, index) => ({
228 iid: index + 1,
229 title: "MR " + index,
230 // The first alone escapes past the default 1 MB cap; together they pass the list cap.
231 description: index === 0 ? '"'.repeat(600_000) : "x".repeat(3_000_000),
232 web_url: "https://gitlab.com/acme/web/-/merge_requests/" + (index + 1),
233 target_branch: "main",
234 source_branch: "feature",
235 source_project_id: index === 3 ? 100 : 101,
236 target_project_id: 100,
237 }));
238 mockedRun.mockImplementation((input) => {
239 const size = Number(input.args[input.args.indexOf("--per-page") + 1]);
240 const pageIndex = input.args.indexOf("--page");
241 const page = pageIndex < 0 ? 1 : Number(input.args[pageIndex + 1]);
242 const raw = JSON.stringify(entries.slice((page - 1) * size, page * size));
243 const cap = input.maxOutputBytes ?? 1_000_000;
244 return Effect.succeed({
245 ...processOutput(raw.slice(0, cap)),
246 stdoutTruncated: raw.length > cap,
247 });
248 });
249 const glab = yield* GitLabCli.GitLabCli;
250 const result = yield* glab.listMergeRequests({
251 cwd: "/repo",
252 headSelector: "feature",
253 state: "open",
254 limit: 4,
255 });
256 assert.deepStrictEqual(
257 result.map((mr) => mr.number),
258 [1, 2, 3, 4],
259 );
260 assert.strictEqual(result[3]?.isCrossRepository, false);
261 }),
262 );
263
264 it.effect("creates same-project MRs without a repository lookup, drafts by title prefix", () =>
265 Effect.gen(function* () {
266 const fileSystem = yield* FileSystem.FileSystem;
267 const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "t3-gitlab-mr-body-" });
268 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
269 const glab = yield* GitLabCli.GitLabCli;
270 yield* glab.createMergeRequest({
271 cwd: "/repo",
272 baseBranch: "main",
273 headSelector: "feature/fix",
274 title: "Fix remote flow",
275 bodyFile,
276 });
277 expect(mockedRun).toHaveBeenCalledExactlyOnceWith(
278 expect.objectContaining({
279 args: [
280 "api",
281 "--method",
282 "POST",
283 "projects/:fullpath/merge_requests",
284 "--raw-field",
285 "source_branch=feature/fix",
286 "--raw-field",
287 "target_branch=main",
288 "--raw-field",
289 "title=Fix remote flow",
290 "--field",
291 "description=@-",
292 ],
293 }),
294 );
295
296 const draftTitle = (title: string) =>
297 Effect.gen(function* () {
298 mockedRun.mockClear();
299 mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
300 yield* glab.createMergeRequest({
301 cwd: "/repo",
302 baseBranch: "main",
303 headSelector: "feature/fix",
304 title,
305 bodyFile,
306 draft: true,
307 });
308 return mockedRun.mock.calls[0]?.[0].args.find((arg) => arg.startsWith("title="));
309 });
310 expect(yield* draftTitle("Fix remote flow")).toBe("title=Draft: Fix remote flow");
311 expect(yield* draftTitle("draft: Fix remote flow")).toBe("title=draft: Fix remote flow");
312 expect(yield* draftTitle("[Draft] Fix remote flow")).toBe("title=[Draft] Fix remote flow");
313 }).pipe(Effect.scoped),
314 );
315
316 it.effect("surfaces a friendly error when the merge request is not found", () =>
317 Effect.gen(function* () {
318 const cause = new VcsProcessExitError({
319 operation: "GitLabCli.execute",
320 command: "glab",
321 cwd: "/repo",
322 exitCode: 1,
323 detail: "GET 404 merge request not found",
324 failureKind: "not-found",
325 });
326 mockedRun.mockReturnValueOnce(Effect.fail(cause));
327
328 const error = yield* Effect.gen(function* () {
329 const glab = yield* GitLabCli.GitLabCli;
330 return yield* glab.getMergeRequest({
331 cwd: "/repo",
332 reference: "4888",
333 });
334 }).pipe(Effect.flip);
335
336 assert.equal(error.message.includes("Merge request 4888 was not found"), true);
337 assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
338 assert.strictEqual(error.command, "glab");
339 assert.strictEqual(error.cwd, "/repo");
340 assert.strictEqual(error.cause, cause);
341 assert.equal(error.message.includes(cause.detail), false);
342 }),
343 );
344
345 it.effect.each([
346 { repository: "group/project", args: ["api", "projects/group%2Fproject"], env: {} },
347 {
348 repository: "https://gitlab.example.com:8443/group/sub/project.git",
349 args: ["api", "--hostname", "gitlab.example.com:8443", "projects/group%2Fsub%2Fproject"],
350 // The environment token is the default host's login, not this host's.
351 env: { GITLAB_TOKEN: "", GITLAB_ACCESS_TOKEN: "", OAUTH_TOKEN: "" },
352 },
353 {
354 repository: "https://gitlab.com/group/project/-/tree/main",
355 args: ["api", "--hostname", "gitlab.com", "projects/group%2Fproject"],
356 env: {},
357 },
358 ])("looks up $repository by its project path", ({ repository, args, env }) =>
359 Effect.gen(function* () {
360 mockedRun.mockReturnValueOnce(
361 Effect.succeed(
362 processOutput(
363 JSON.stringify({
364 path_with_namespace: "group/project",
365 web_url: "https://sourcecontrol.example.com/group/project",
366 http_url_to_repo: "https://sourcecontrol.example.com/group/project.git",
367 ssh_url_to_repo: "git@sourcecontrol.example.com:group/project.git",
368 }),
369 ),
370 ),
371 );
372
373 const glab = yield* GitLabCli.GitLabCli;
374 yield* glab.getRepositoryCloneUrls({ cwd: "/repo", repository });
375
376 expect(mockedRun).toHaveBeenCalledWith(
377 expect.objectContaining({ command: "glab", args, env }),
378 );
379 }),
380 );
381
382 it.effect("keeps non-merge-request not-found failures generic", () =>
383 Effect.gen(function* () {
384 const cause = new VcsProcessExitError({
385 operation: "GitLabCli.execute",
386 command: "glab",
387 cwd: "/repo",
388 exitCode: 1,
389 detail: "GET 404 project not found",
390 failureKind: "not-found",
391 });
392 mockedRun.mockReturnValueOnce(Effect.fail(cause));
393
394 const error = yield* Effect.gen(function* () {
395 const glab = yield* GitLabCli.GitLabCli;
396 return yield* glab.getRepositoryCloneUrls({
397 cwd: "/repo",
398 repository: "missing/project",
399 });
400 }).pipe(Effect.flip);
401
402 assert.strictEqual(error._tag, "GitLabCliCommandError");
403 assert.strictEqual(error.cause, cause);
404 }),
405 );
406
407 it.effect("preserves rate-limit failures as a distinct error", () =>
408 Effect.gen(function* () {
409 const cause = new VcsProcessExitError({
410 operation: "GitLabCli.execute",
411 command: "glab",
412 cwd: "/repo",
413 exitCode: 1,
414 detail: "API rate limit exceeded.",
415 failureKind: "rate-limited",
416 });
417 mockedRun.mockReturnValueOnce(Effect.fail(cause));
418
419 const glab = yield* GitLabCli.GitLabCli;
420 const error = yield* glab
421 .execute({ cwd: "/repo", args: ["api", "projects"] })
422 .pipe(Effect.flip);
423
424 assert.strictEqual(error._tag, "GitLabCliRateLimitError");
425 assert.strictEqual(error.cause, cause);
426 }),
427 );
428 });