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 === "graphql") {
96 return encode({
97 data: {
98 currentUser: { username: "julius" },
99 project: {
100 mergeRequest: {
101 awardEmoji: { nodes: [{ name: "eyes", user: { username: "theo" } }] },
102 notes: {
103 pageInfo: { hasNextPage: false },
104 nodes: [
105 {
106 id: "gid://gitlab/Note/7",
107 awardEmoji: {
108 nodes: [
109 { name: "thumbsup", user: { username: "julius" } },
110 { name: "thumbsup", user: { username: "theo" } },
111 ],
112 },
113 },
114 ],
115 },
116 },
117 },
118 },
119 });
120 }
121 throw new Error(`unexpected path ${path}`);
122}
123
124function tracker(
125 onExecute: (
126 args: ReadonlyArray<string>,
127 input: { readonly host?: string | undefined; readonly stdin?: string },
128 ) => string,
129) {
130 return GitLabIssueTracker.make.pipe(
131 Effect.provide(
132 Layer.mock(GitLabCli.GitLabCli)({
133 execute: (input) =>
134 Effect.succeed(TestSourceControlHost.processOutput(onExecute(input.args, input))),
135 }),
136 ),
137 );
138}
139
140describe("GitLabIssueTracker", () => {
141 it.effect("joins the detail's endpoints into the neutral issue shape", () =>
142 Effect.gen(function* () {
143 const hosts = new Set<string | undefined>();
144 const awardCursors: unknown[] = [];
145 const api = yield* tracker((args, input) => {
146 hosts.add(input.host);
147 if (args[1] === "graphql") awardCursors.push(JSON.parse(input.stdin!).variables.cursor);
148 return answer(args[1]!);
149 });
150 const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" };
151 const issue = yield* api.getIssue(target);
152 // A later page of comments carries its own awards, found by the cursor's second half.
153 const later = yield* api.getComments({ ...target, cursor: "2:after-100" });
154 expect(later.comments.map((comment) => comment.reactions?.[0]?.count)).toEqual([2]);
155 expect(awardCursors).toEqual([null, "after-100"]);
156 // Every request names the tracker's own host rather than leaving glab to pick one.
157 expect([...hosts]).toEqual(["gitlab.example.com"]);
158 expect(issue).toMatchObject({
159 key: "42",
160 displayKey: "#42",
161 state: { category: "closed", name: "Closed" },
162 states: [
163 { category: "open", name: "Open" },
164 { category: "closed", name: "Closed" },
165 ],
166 author: { login: "octocat", name: "Octo Cat" },
167 assignees: [{ login: "theo" }],
168 labels: [{ name: "bug", color: null }],
169 commentCount: 3,
170 viewer: "julius",
171 viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
172 commentsCursor: null,
173 reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
174 });
175 expect(issue.comments).toEqual([
176 {
177 id: "7",
178 author: { login: "julius", name: null, avatarUrl: null },
179 body: "Repro attached.",
180 createdAt: "2026-07-02T00:00:00Z",
181 url: null,
182 reactions: [{ content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true }],
183 },
184 ]);
185 // System notes become events; label notes are dropped in favour of the label events.
186 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
187 ["labeled", "bug"],
188 ["closed", null],
189 ]);
190 // A closing merge request is not repeated as a related one.
191 expect(
192 issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]),
193 ).toEqual([
194 [50, true, false],
195 [51, false, true],
196 ]);
197 }),
198 );
199
200 it.effect("keeps system events after the first hundred notes in the issue timeline", () =>
201 Effect.gen(function* () {
202 const firstPage = Array.from({ length: 100 }, (_, index) => ({
203 id: index + 1000,
204 body: "Discussion",
205 author: { username: "julius" },
206 created_at: "2026-07-02T00:00:00Z",
207 }));
208 const api = yield* tracker((args) => {
209 const path = args[1]!;
210 if (path.includes("/notes?")) {
211 const page = new URLSearchParams(path.split("?")[1]).get("page");
212 if (page === "1") return encode(firstPage);
213 if (page === "2") {
214 return encode([
215 {
216 id: 1100,
217 body: "closed",
218 system: true,
219 author: { username: "theo" },
220 created_at: "2026-07-03T00:00:00Z",
221 },
222 ]);
223 }
224 return encode([]);
225 }
226 return answer(path);
227 });
228 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
229 const issue = yield* api.getIssue(target);
230 let cursor = issue.commentsCursor;
231 while (cursor !== null) {
232 cursor = (yield* api.getComments({ ...target, cursor })).nextCursor;
233 }
234 expect(issue.events).toContainEqual(
235 expect.objectContaining({ id: "note-1100", kind: "closed" }),
236 );
237 }),
238 );
239
240 it.effect("follows GitLab's next page past a short page of notes", () =>
241 Effect.gen(function* () {
242 const notes = (next: string, rows: ReadonlyArray<unknown>) =>
243 `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)}`;
244 const api = yield* tracker((args) => {
245 const path = args[1]!;
246 if (path.includes("/notes?")) {
247 const params = new URLSearchParams(path.split("?")[1]);
248 if (params.get("activity_filter") === "only_activity") {
249 return params.get("page") === "1"
250 ? notes("2", [])
251 : notes("", [
252 {
253 id: 300,
254 body: "closed",
255 system: true,
256 author: { username: "theo" },
257 created_at: "2026-07-03T00:00:00Z",
258 },
259 ]);
260 }
261 return notes("2", [
262 {
263 id: 1,
264 body: "Hi",
265 author: { username: "julius" },
266 created_at: "2026-07-02T00:00:00Z",
267 },
268 ]);
269 }
270 return answer(path);
271 });
272 const issue = yield* api.getIssue({
273 cwd: "/w",
274 host: "gitlab.com",
275 scope: "acme/web",
276 key: "42",
277 });
278 expect(issue.commentsCursor).toBe("2");
279 expect(issue.events.map((event) => event.id)).toEqual(["label-3", "note-300"]);
280 }),
281 );
282
283 it.effect("pages a listing by GitLab's page number and stops on a short page", () =>
284 Effect.gen(function* () {
285 const paths: string[] = [];
286 const api = yield* tracker((args) => {
287 paths.push(args[1]!);
288 return encode([ISSUE]);
289 });
290 const page = yield* api.listIssues({
291 cwd: "/w",
292 host: "gitlab.com",
293 scope: "acme/web",
294 state: "open",
295 involvement: "assigned",
296 viewer: "julius",
297 sort: "updated",
298 limit: 1,
299 cursor: "3",
300 });
301 expect(paths[0]).toBe(
302 "projects/acme%2Fweb/issues?state=opened&assignee_username=julius&order_by=updated_at&sort=desc&per_page=1&page=3",
303 );
304 // A named assignee takes the one parameter GitLab reads, so "assigned to me" drops rows here.
305 const both = yield* api.listIssues({
306 cwd: "/w",
307 host: "gitlab.com",
308 scope: "acme/web",
309 state: "open",
310 involvement: "assigned",
311 viewer: "julius",
312 labels: ["bug", "needs triage"],
313 assignee: "theo",
314 sort: "created",
315 limit: 1,
316 });
317 expect(paths[1]).toBe(
318 "projects/acme%2Fweb/issues?state=opened&labels=bug%2Cneeds%20triage&assignee_username=theo&order_by=created_at&sort=desc&per_page=1&page=1",
319 );
320 expect(both.items).toEqual([]);
321 expect(page.items[0]?.key).toBe("42");
322 expect(page.nextCursor).toBe("4");
323 }),
324 );
325
326 it.effect("removes the viewer's own award by id, paging until it is found", () =>
327 Effect.gen(function* () {
328 const calls: string[] = [];
329 const api = yield* tracker((args) => {
330 const path = args[1]!;
331 calls.push(args.includes("DELETE") ? `DELETE ${path}` : path);
332 if (path === "user") return encode({ username: "julius" });
333 if (path.endsWith("page=1")) {
334 return encode([{ id: 1, name: "thumbsup", user: { username: "theo" } }]);
335 }
336 if (path.endsWith("page=2") && path.includes("/notes/7/")) {
337 return encode([{ id: 9, name: "thumbsup", user: { username: "julius" } }]);
338 }
339 return "[]";
340 });
341 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
342 yield* api.setReaction!({ ...target, subjectId: "7", content: "thumbs-up", reacted: false });
343 expect(calls.at(-1)).toBe("DELETE projects/acme%2Fweb/issues/42/notes/7/award_emoji/9");
344 // Nothing to delete is success, with no DELETE sent.
345 calls.length = 0;
346 yield* api.setReaction!({ ...target, content: "thumbs-up", reacted: false });
347 expect(calls).toEqual([
348 "user",
349 "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=1",
350 "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=2",
351 ]);
352 }),
353 );
354
355 it.effect("writes a kept assignee by the id its username resolves to", () =>
356 Effect.gen(function* () {
357 const calls: string[] = [];
358 const bodies: string[] = [];
359 const api = yield* tracker((args, input) => {
360 const path = args[1]!;
361 calls.push(path);
362 if (input.stdin !== undefined) bodies.push(input.stdin);
363 if (path === "users?username=theo") return encode([{ id: 2, username: "theo" }]);
364 if (path.startsWith("users?username=")) return "[]";
365 return "{}";
366 });
367 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
368 // The issue's own assignee comes back by login; a newly picked one by id.
369 yield* api.update!({ ...target, assignees: ["theo", "7"] });
370 expect(calls).toEqual(["users?username=theo", "projects/acme%2Fweb/issues/42"]);
371 expect(JSON.parse(bodies.at(-1)!)).toEqual({ assignee_ids: [2, 7] });
372 const error = yield* Effect.flip(api.update!({ ...target, assignees: ["nobody"] }));
373 expect(error.reason).toBe("failed");
374 }),
375 );
376
377 it.effect("moves an issue to a state by its name and refuses any other name", () =>
378 Effect.gen(function* () {
379 const writes: unknown[] = [];
380 const api = yield* tracker((args, input) => {
381 writes.push([args[1], JSON.parse(input.stdin ?? "null")]);
382 return "{}";
383 });
384 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
385 yield* api.setState!({ ...target, state: "Closed" });
386 yield* api.setState!({ ...target, state: "Open" });
387 // The category is not a state name: nothing is sent for it.
388 const error = yield* Effect.flip(api.setState!({ ...target, state: "closed" }));
389 expect(error).toMatchObject({ operation: "setState", reason: "failed" });
390 expect(writes).toEqual([
391 ["projects/acme%2Fweb/issues/42", { state_event: "close" }],
392 ["projects/acme%2Fweb/issues/42", { state_event: "reopen" }],
393 ]);
394 }),
395 );
396
397 it.effect("refuses a key that names no GitLab issue without a request", () =>
398 Effect.gen(function* () {
399 let requests = 0;
400 const api = yield* tracker(() => {
401 requests += 1;
402 return "{}";
403 });
404 const error = yield* Effect.flip(
405 api.getIssue({ cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "ENG-42" }),
406 );
407 expect(error.reason).toBe("not-found");
408 expect(requests).toBe(0);
409 }),
410 );
411});