Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
5
6import * as GitLabCli from "./GitLabCli.ts";
7import * as GitLabIssueTracker from "./GitLabIssueTracker.ts";
8
9const encode = (value: unknown) => JSON.stringify(value);
10
11const ISSUE = {
12 iid: 42,
13 title: "Composer loses focus",
14 web_url: "https://gitlab.com/acme/web/-/issues/42",
15 description: "Typing in the composer drops focus after a paste.",
16 author: { id: 1, username: "octocat", name: "Octo Cat", avatar_url: "https://avatars/octocat" },
17 state: "closed",
18 created_at: "2026-07-01T00:00:00Z",
19 updated_at: "2026-07-03T00:00:00Z",
20 closed_at: "2026-07-03T00:00:00Z",
21 assignees: [{ id: 2, username: "theo", name: null }],
22 labels: ["bug", " "],
23 user_notes_count: 3,
24};
25
26/** Every endpoint the detail read touches, answered by the path `glab api` is given. */
27function answer(path: string): string {
28 if (path === "user") return encode({ username: "julius" });
29 if (path === "projects/acme%2Fweb/issues/42") return encode(ISSUE);
30 if (path.startsWith("projects/acme%2Fweb/issues/42/notes")) {
31 return encode([
32 {
33 id: 7,
34 body: "Repro attached.",
35 author: { username: "julius" },
36 created_at: "2026-07-02T00:00:00Z",
37 },
38 {
39 id: 8,
40 body: "closed",
41 author: { username: "theo" },
42 created_at: "2026-07-03T00:00:00Z",
43 system: true,
44 },
45 {
46 id: 9,
47 body: "added ~7 label",
48 author: { username: "theo" },
49 created_at: "2026-07-03T00:00:00Z",
50 system: true,
51 },
52 ]);
53 }
54 if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) {
55 return encode([
56 {
57 id: 3,
58 action: "add",
59 created_at: "2026-07-01T01:00:00Z",
60 user: { username: "theo" },
61 label: { name: "bug" },
62 },
63 ]);
64 }
65 if (path.startsWith("projects/acme%2Fweb/issues/42/closed_by")) {
66 return encode([
67 {
68 iid: 50,
69 title: "fix(web): keep composer focus",
70 web_url: "https://gitlab.com/acme/web/-/merge_requests/50",
71 state: "merged",
72 references: { full: "acme/web!50" },
73 },
74 ]);
75 }
76 if (path.startsWith("projects/acme%2Fweb/issues/42/related_merge_requests")) {
77 return encode([
78 {
79 iid: 50,
80 title: "fix(web): keep composer focus",
81 web_url: "https://gitlab.com/acme/web/-/merge_requests/50",
82 state: "merged",
83 references: { full: "acme/web!50" },
84 },
85 {
86 iid: 51,
87 title: "chore: mention",
88 web_url: "https://gitlab.com/acme/web/-/merge_requests/51",
89 state: "opened",
90 draft: true,
91 references: { full: "acme/web!51" },
92 },
93 ]);
94 }
95 if (path.startsWith("projects/acme%2Fweb/issues/42/award_emoji")) {
96 return encode([{ id: 11, name: "eyes", user: { username: "theo" } }]);
97 }
98 if (path === "graphql") {
99 return encode({
100 data: {
101 currentUser: { username: "julius" },
102 project: {
103 mergeRequest: {
104 notes: {
105 pageInfo: { hasNextPage: false },
106 nodes: [
107 {
108 id: "gid://gitlab/Note/7",
109 awardEmoji: {
110 nodes: [
111 { name: "thumbsup", user: { username: "julius" } },
112 { name: "thumbsup", user: { username: "theo" } },
113 ],
114 },
115 },
116 ],
117 },
118 },
119 },
120 },
121 });
122 }
123 throw new Error(`unexpected path ${path}`);
124}
125
126function tracker(
127 onExecute: (
128 args: ReadonlyArray<string>,
129 input: { readonly host?: string | undefined; readonly stdin?: string },
130 ) => string,
131) {
132 return GitLabIssueTracker.make.pipe(
133 Effect.provide(
134 Layer.mock(GitLabCli.GitLabCli)({
135 execute: (input) =>
136 Effect.succeed(TestSourceControlHost.processOutput(onExecute(input.args, input))),
137 }),
138 ),
139 );
140}
141
142describe("GitLabIssueTracker", () => {
143 it.effect("joins the detail's endpoints into the neutral issue shape", () =>
144 Effect.gen(function* () {
145 const hosts = new Set<string | undefined>();
146 const awardCursors: unknown[] = [];
147 const api = yield* tracker((args, input) => {
148 hosts.add(input.host);
149 if (args[1] === "graphql") {
150 const request = JSON.parse(input.stdin!);
151 // gitlab.com's schema has no `Issue.awardEmoji`; glab exits 1 on such a query.
152 const issueFields = /issue\(iid: \$iid\) \{([\s\S]*?)notes\(/.exec(request.query)?.[1];
153 if (issueFields?.includes("awardEmoji")) {
154 throw new Error("Field 'awardEmoji' doesn't exist on type 'Issue'");
155 }
156 awardCursors.push(request.variables.cursor);
157 }
158 return answer(args[1]!);
159 });
160 const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" };
161 const issue = yield* api.getIssue(target);
162 // A later page of comments carries its own awards, found by the cursor's second half.
163 const later = yield* api.getComments({ ...target, cursor: "2:after-100" });
164 expect(later.comments.map((comment) => comment.reactions?.[0]?.count)).toEqual([2]);
165 expect(awardCursors).toEqual([null, "after-100"]);
166 // Every request names the tracker's own host rather than leaving glab to pick one.
167 expect([...hosts]).toEqual(["gitlab.example.com"]);
168 expect(issue).toMatchObject({
169 key: "42",
170 displayKey: "#42",
171 state: { category: "closed", name: "Closed" },
172 states: [
173 { category: "open", name: "Open" },
174 { category: "closed", name: "Closed" },
175 ],
176 author: { login: "octocat", name: "Octo Cat" },
177 assignees: [{ login: "theo" }],
178 labels: [{ name: "bug", color: null }],
179 commentCount: 3,
180 viewer: "julius",
181 viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
182 commentsCursor: null,
183 reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
184 });
185 expect(issue.comments).toEqual([
186 {
187 id: "7",
188 author: { login: "julius", name: null, avatarUrl: null },
189 body: "Repro attached.",
190 createdAt: "2026-07-02T00:00:00Z",
191 url: null,
192 reactions: [{ content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true }],
193 },
194 ]);
195 // System notes become events; label notes are dropped in favour of the label events.
196 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
197 ["labeled", "bug"],
198 ["closed", null],
199 ]);
200 // A closing merge request is not repeated as a related one.
201 expect(
202 issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]),
203 ).toEqual([
204 [50, true, false],
205 [51, false, true],
206 ]);
207 }),
208 );
209
210 it.effect("keeps system events after the first hundred notes in the issue timeline", () =>
211 Effect.gen(function* () {
212 const firstPage = Array.from({ length: 100 }, (_, index) => ({
213 id: index + 1000,
214 body: "Discussion",
215 author: { username: "julius" },
216 created_at: "2026-07-02T00:00:00Z",
217 }));
218 const api = yield* tracker((args) => {
219 const path = args[1]!;
220 if (path.includes("/notes?")) {
221 const page = new URLSearchParams(path.split("?")[1]).get("page");
222 if (page === "1") return encode(firstPage);
223 if (page === "2") {
224 return encode([
225 {
226 id: 1100,
227 body: "closed",
228 system: true,
229 author: { username: "theo" },
230 created_at: "2026-07-03T00:00:00Z",
231 },
232 ]);
233 }
234 return encode([]);
235 }
236 return answer(path);
237 });
238 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
239 const issue = yield* api.getIssue(target);
240 let cursor = issue.commentsCursor;
241 while (cursor !== null) {
242 cursor = (yield* api.getComments({ ...target, cursor })).nextCursor;
243 }
244 expect(issue.events).toContainEqual(
245 expect.objectContaining({ id: "note-1100", kind: "closed" }),
246 );
247 }),
248 );
249
250 it.effect("follows GitLab's next page past a short page of notes", () =>
251 Effect.gen(function* () {
252 const notes = (next: string, rows: ReadonlyArray<unknown>) =>
253 `HTTP/2.0 200 OK\r\nContent-Type: application/json\r\nX-Next-Page: ${next}\r\nX-Page: 1\r\n\r\n${encode(rows)}`;
254 const api = yield* tracker((args) => {
255 const path = args[1]!;
256 if (path.includes("/notes?")) {
257 const params = new URLSearchParams(path.split("?")[1]);
258 if (params.get("activity_filter") === "only_activity") {
259 return params.get("page") === "1"
260 ? notes("2", [])
261 : notes("", [
262 {
263 id: 300,
264 body: "closed",
265 system: true,
266 author: { username: "theo" },
267 created_at: "2026-07-03T00:00:00Z",
268 },
269 ]);
270 }
271 return notes("2", [
272 {
273 id: 1,
274 body: "Hi",
275 author: { username: "julius" },
276 created_at: "2026-07-02T00:00:00Z",
277 },
278 ]);
279 }
280 return answer(path);
281 });
282 const issue = yield* api.getIssue({
283 cwd: "/w",
284 host: "gitlab.com",
285 scope: "acme/web",
286 key: "42",
287 });
288 expect(issue.commentsCursor).toBe("2");
289 expect(issue.events.map((event) => event.id)).toEqual(["label-3", "note-300"]);
290 }),
291 );
292
293 it.effect("pages a listing by GitLab's page number and stops on a short page", () =>
294 Effect.gen(function* () {
295 const paths: string[] = [];
296 const api = yield* tracker((args) => {
297 paths.push(args[1]!);
298 return encode([ISSUE]);
299 });
300 const page = yield* api.listIssues({
301 cwd: "/w",
302 host: "gitlab.com",
303 scope: "acme/web",
304 state: "open",
305 involvement: "assigned",
306 viewer: "julius",
307 sort: "updated",
308 limit: 1,
309 cursor: "3",
310 });
311 expect(paths[0]).toBe(
312 "projects/acme%2Fweb/issues?state=opened&assignee_username=julius&order_by=updated_at&sort=desc&per_page=1&page=3",
313 );
314 // A named assignee takes the one parameter GitLab reads, so "assigned to me" drops rows here.
315 const both = yield* api.listIssues({
316 cwd: "/w",
317 host: "gitlab.com",
318 scope: "acme/web",
319 state: "open",
320 involvement: "assigned",
321 viewer: "julius",
322 labels: ["bug", "needs triage"],
323 assignee: "theo",
324 sort: "created",
325 limit: 1,
326 });
327 expect(paths[1]).toBe(
328 "projects/acme%2Fweb/issues?state=opened&labels=bug%2Cneeds%20triage&assignee_username=theo&order_by=created_at&sort=desc&per_page=1&page=1",
329 );
330 expect(both.items).toEqual([]);
331 expect(page.items[0]?.key).toBe("42");
332 expect(page.nextCursor).toBe("4");
333 }),
334 );
335
336 it.effect("removes the viewer's own award by id, paging until it is found", () =>
337 Effect.gen(function* () {
338 const calls: string[] = [];
339 const api = yield* tracker((args) => {
340 const path = args[1]!;
341 calls.push(args.includes("DELETE") ? `DELETE ${path}` : path);
342 if (path === "user") return encode({ username: "julius" });
343 if (path.endsWith("page=1")) {
344 return encode([{ id: 1, name: "thumbsup", user: { username: "theo" } }]);
345 }
346 if (path.endsWith("page=2") && path.includes("/notes/7/")) {
347 return encode([{ id: 9, name: "thumbsup", user: { username: "julius" } }]);
348 }
349 return "[]";
350 });
351 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
352 yield* api.setReaction!({ ...target, subjectId: "7", content: "thumbs-up", reacted: false });
353 expect(calls.at(-1)).toBe("DELETE projects/acme%2Fweb/issues/42/notes/7/award_emoji/9");
354 // Nothing to delete is success, with no DELETE sent.
355 calls.length = 0;
356 yield* api.setReaction!({ ...target, content: "thumbs-up", reacted: false });
357 expect(calls).toEqual([
358 "user",
359 "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=1",
360 "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=2",
361 ]);
362 }),
363 );
364
365 it.effect("writes a kept assignee by the id its username resolves to", () =>
366 Effect.gen(function* () {
367 const calls: string[] = [];
368 const bodies: string[] = [];
369 const api = yield* tracker((args, input) => {
370 const path = args[1]!;
371 calls.push(path);
372 if (input.stdin !== undefined) bodies.push(input.stdin);
373 if (path === "users?username=theo") return encode([{ id: 2, username: "theo" }]);
374 if (path.startsWith("users?username=")) return "[]";
375 return "{}";
376 });
377 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
378 // The issue's own assignee comes back by login; a newly picked one by id.
379 yield* api.update!({ ...target, assignees: ["theo", "7"] });
380 expect(calls).toEqual(["users?username=theo", "projects/acme%2Fweb/issues/42"]);
381 expect(JSON.parse(bodies.at(-1)!)).toEqual({ assignee_ids: [2, 7] });
382 const error = yield* Effect.flip(api.update!({ ...target, assignees: ["nobody"] }));
383 expect(error.reason).toBe("failed");
384 }),
385 );
386
387 it.effect("moves an issue to a state by its name and refuses any other name", () =>
388 Effect.gen(function* () {
389 const writes: unknown[] = [];
390 const api = yield* tracker((args, input) => {
391 writes.push([args[1], JSON.parse(input.stdin ?? "null")]);
392 return "{}";
393 });
394 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
395 yield* api.setState!({ ...target, state: "Closed" });
396 yield* api.setState!({ ...target, state: "Open" });
397 // The category is not a state name: nothing is sent for it.
398 const error = yield* Effect.flip(api.setState!({ ...target, state: "closed" }));
399 expect(error).toMatchObject({ operation: "setState", reason: "failed" });
400 expect(writes).toEqual([
401 ["projects/acme%2Fweb/issues/42", { state_event: "close" }],
402 ["projects/acme%2Fweb/issues/42", { state_event: "reopen" }],
403 ]);
404 }),
405 );
406
407 it.effect("refuses a key that names no GitLab issue without a request", () =>
408 Effect.gen(function* () {
409 let requests = 0;
410 const api = yield* tracker(() => {
411 requests += 1;
412 return "{}";
413 });
414 const error = yield* Effect.flip(
415 api.getIssue({ cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "ENG-42" }),
416 );
417 expect(error.reason).toBe("not-found");
418 expect(requests).toBe(0);
419 }),
420 );
421});