Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LinearIssueTracker.test.ts

533 lines19.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import { HttpClient, HttpClientResponse } from "effect/http";
6import { IssueTrackerKind } from "@t3tools/contracts";
7import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker";
8import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost";
9​
10import * as LinearApi from "./LinearApi.ts";
11import * as LinearIssueTracker from "./LinearIssueTracker.ts";
12​
13const user = (id: string, displayName: string) => ({
14 id,
15 name: displayName,
16 displayName,
17 email: `${displayName}@acme.test`,
18 avatarUrl: null,
19});
20const JULIUS = user("usr_julius", "julius");
21const THEO = user("usr_theo", "theo");
22​
23const state = (name: string, type: string, position = 0) => ({
24 id: `st_${name.toLowerCase().replaceAll(" ", "-")}`,
25 name,
26 type,
27 position,
28});
29​
30const issue = (
31 identifier: string,
32 overrides: Partial<Record<string, unknown>> = {},
33): Record<string, unknown> => ({
34 id: `iss_${identifier}`,
35 identifier,
36 number: Number(identifier.split("-")[1]),
37 title: `Issue ${identifier}`,
38 url: `https://linear.app/acme/issue/${identifier}`,
39 description: "body",
40 createdAt: "2026-07-01T00:00:00.000Z",
41 updatedAt: "2026-07-02T00:00:00.000Z",
42 completedAt: null,
43 canceledAt: null,
44 state: state("In Progress", "started"),
45 // The detail query also asks for the team's workflow; a listing ignores it.
46 team: {
47 key: identifier.split("-")[0],
48 states: {
49 nodes: [
50 state("Canceled", "canceled", 3),
51 state("Done", "completed", 2),
52 state("In Progress", "started", 1),
53 state("Todo", "unstarted", 0),
54 ],
55 },
56 },
57 creator: JULIUS,
58 botActor: null,
59 assignee: THEO,
60 labels: { nodes: [{ id: "lbl_bug", name: "Bug", color: "#f00" }] },
61 ...overrides,
62});
63​
64/** An issue as the detail query answers it, with nothing hanging off it. */
65const bareDetail = (identifier: string) =>
66 issue(identifier, {
67 comments: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
68 reactions: [],
69 attachments: { nodes: [] },
70 history: { nodes: [] },
71 });
72​
73/** Answers each GraphQL document by its operation name, the way Linear would. */
74function fakeLinear(
75 answers: Record<string, (variables: Record<string, unknown>) => unknown>,
76 stored: string | null = "lin_api_stored",
77) {
78 const requests: Array<{
79 readonly authorization: string | undefined;
80 readonly operation: string;
81 }> = [];
82 const http = Layer.succeed(
83 HttpClient.HttpClient,
84 HttpClient.make((request) =>
85 Effect.sync(() => {
86 const body = request.body;
87 const text =
88 body._tag === "Uint8Array" ? new TextDecoder().decode(body.body) : String(body._tag);
89 const parsed = JSON.parse(text) as { query: string; variables: Record<string, unknown> };
90 const operation = /^(?:query|mutation) (\w+)/.exec(parsed.query)?.[1] ?? "?";
91 requests.push({ authorization: request.headers.authorization, operation });
92 const answer = answers[operation];
93 const answered = answer?.(parsed.variables);
94 const response =
95 answered instanceof Response
96 ? answered
97 : answer === undefined
98 ? new Response(
99 JSON.stringify({ errors: [{ message: `No answer for ${operation}` }] }),
100 {
101 status: 400,
102 headers: { "content-type": "application/json" },
103 },
104 )
105 : new Response(JSON.stringify({ data: answered }), {
106 status: 200,
107 headers: { "content-type": "application/json" },
108 });
109 return HttpClientResponse.fromWeb(request, response);
110 }),
111 ),
112 );
113 const host = Layer.succeed(
114 IssueTrackerHost.IssueTrackerHost,
115 IssueTrackerHost.IssueTrackerHost.of({
116 credentials: { get: () => Effect.succeed(Option.fromNullishOr(stored)) },
117 }),
118 );
119 // Every optional write is implemented here; the type says so for the calls below.
120 const tracker = LinearIssueTracker.make.pipe(
121 Effect.map((api) => api as Required<StandaloneIssueTrackerApi>),
122 Effect.provide(LinearApi.layer.pipe(Layer.provide(Layer.merge(http, host)))),
123 );
124 return { tracker, requests };
126​
127const target = { cwd: "/w/web", host: "linear.app", scope: "ENG" };
128​
129describe("LinearIssueTracker", () => {
130 it.effect("parses Linear issue links with their workspace and team", () =>
131 Effect.gen(function* () {
132 const api = yield* fakeLinear({}).tracker;
133 for (const suffix of ["", "/issue-title", "/old-title?view=all#comment"]) {
134 expect(api.parseIssueUrl(new URL(`https://linear.app/acme/issue/ENG-1${suffix}`))).toEqual({
135 host: "linear.app",
136 workspace: "acme",
137 scope: "ENG",
138 key: "ENG-1",
139 });
140 }
141 expect(
142 api.parseIssueUrl(new URL("https://linear.app/other-workspace/issue/ENG-1")),
143 ).toMatchObject({
144 workspace: "other-workspace",
145 key: "ENG-1",
146 });
147 for (const url of [
148 "http://linear.app/acme/issue/ENG-1",
149 "https://example.com/acme/issue/ENG-1",
150 "https://linear.app.example.com/acme/issue/ENG-1",
151 "https://linear.app:444/acme/issue/ENG-1",
152 "https://linear.app/acme/team/ENG-1",
153 "https://linear.app//issue/ENG-1",
154 "https://linear.app/acme/issue/",
155 "https://linear.app/acme/issue/ENG-0",
156 "https://linear.app/acme/issue/eng-1",
157 "https://linear.app/acme/issue/ENG-1extra",
158 ]) {
159 expect(api.parseIssueUrl(new URL(url)), url).toBeNull();
160 }
161 }),
162 );
163​
164 it.effect("lists a team's issues as summaries keyed by identifier", () =>
165 Effect.gen(function* () {
166 const { tracker, requests } = fakeLinear({
167 T3Viewer: () => ({
168 viewer: JULIUS,
169 organization: { urlKey: "acme" },
170 teams: { nodes: [] },
171 }),
172 T3Issues: (variables) => {
173 expect(variables.filter).toMatchObject({
174 team: { key: { eq: "ENG" } },
175 state: { type: { nin: ["completed", "canceled", "duplicate"] } },
176 // "Assigned to me" survives an assignee filter: both must hold.
177 assignee: { displayName: { eq: "julius" } },
178 and: [
179 { assignee: { displayName: { eq: "theo" } } },
180 { labels: { some: { name: { eq: "Bug" } } } },
181 ],
182 });
183 expect(variables.orderBy).toBe("createdAt");
184 return {
185 issues: {
186 nodes: [
187 issue("ENG-2", {
188 state: state("Done", "completed"),
189 completedAt: "2026-07-03T00:00:00.000Z",
190 }),
191 issue("ENG-1"),
192 ],
193 pageInfo: { hasNextPage: true, endCursor: "cur_2" },
194 },
195 };
196 },
197 });
198 const api = yield* tracker;
199 expect(api.kind).toBe(IssueTrackerKind.make("linear"));
200 expect(api.standalone).toMatchObject({ host: "linear.app", scopeNoun: "team" });
201​
202 const page = yield* api.listIssues({
203 ...target,
204 state: "open",
205 involvement: "assigned",
206 viewer: "julius",
207 labels: ["Bug"],
208 assignee: "theo",
209 sort: "created",
210 limit: 50,
211 });
212 expect(page.nextCursor).toBe("cur_2");
213 expect(page.items.map((item) => [item.key, item.displayKey, item.state])).toEqual([
214 ["ENG-2", "ENG-2", { category: "closed", name: "Done", closeReason: "completed" }],
215 ["ENG-1", "ENG-1", { category: "open", name: "In Progress" }],
216 ]);
217 // A listing carries no comment totals, whatever the row's position.
218 expect(page.items.map((item) => item.commentCount)).toEqual([0, 0]);
219 expect(page.items[0]).toMatchObject({
220 closedAt: "2026-07-03T00:00:00.000Z",
221 author: { login: "julius", name: "julius" },
222 assignees: [{ login: "theo", name: "theo" }],
223 labels: [{ name: "Bug", color: "#f00" }],
224 });
225 // The stored key goes in as-is, not as a bearer token.
226 expect(requests.map((request) => request.authorization)).toEqual(["lin_api_stored"]);
227​
228 // Linear's reset header is an absolute time in epoch milliseconds.
229 const resetAt = 4_102_444_800_000;
230 const limited = fakeLinear({
231 T3Issues: () =>
232 new Response(JSON.stringify({ errors: [{ message: "Rate limited" }] }), {
233 status: 429,
234 headers: {
235 "content-type": "application/json",
236 "x-ratelimit-requests-reset": String(resetAt),
237 },
238 }),
239 });
240 const refused = yield* Effect.flip(
241 (yield* limited.tracker).listIssues({
242 ...target,
243 state: "open",
244 involvement: "all",
245 sort: "updated",
246 limit: 50,
247 }),
248 );
249 expect([refused.reason, refused.retryAt]).toEqual(["rate-limited", resetAt]);
250 }),
251 );
252​
253 it.effect("reacts to a comment only when it belongs to the issue named", () =>
254 Effect.gen(function* () {
255 const created: Array<unknown> = [];
256 const deleted: Array<unknown> = [];
257 const { tracker } = fakeLinear({
258 T3Viewer: () => ({
259 viewer: JULIUS,
260 organization: { urlKey: "acme" },
261 teams: { nodes: [] },
262 }),
263 T3Issue: (variables) => {
264 // Linear refuses a page of zero comments, which fails the write that looked the issue up.
265 expect(variables.comments).toBeGreaterThan(0);
266 return { issue: bareDetail(String(variables.id)) };
267 },
268 T3CommentReactions: (variables) => ({
269 comment: {
270 issue: { id: variables.id === "cmt_own" ? "iss_ENG-1" : "iss_OPS-9" },
271 reactions: [{ id: "r1", emoji: "+1", user: JULIUS }],
272 },
273 }),
274 T3ReactionCreate: (variables) => {
275 created.push(variables.input);
276 return { reactionCreate: { success: true } };
277 },
278 T3ReactionDelete: (variables) => {
279 deleted.push(variables.id);
280 return { reactionDelete: { success: true } };
281 },
282 });
283 const api = yield* tracker;
284 const reaction = { ...target, key: "ENG-1", content: "thumbs-up" as const };
285 for (const reacted of [true, false]) {
286 const foreign = yield* Effect.flip(
287 api.setReaction({ ...reaction, subjectId: "cmt_other", reacted }),
288 );
289 expect(foreign.detail).toBe("The comment does not belong to the selected issue.");
290 }
291 expect([created, deleted]).toEqual([[], []]);
292​
293 yield* api.setReaction({ ...reaction, subjectId: "cmt_own", reacted: true });
294 yield* api.setReaction({ ...reaction, subjectId: "cmt_own", reacted: false });
295 expect(created).toEqual([{ commentId: "cmt_own", emoji: "πŸ‘" }]);
296 expect(deleted).toEqual(["r1"]);
297 }),
298 );
299​
300 it.effect("reads an issue with its comments, reactions, history and linked pull requests", () =>
301 Effect.gen(function* () {
302 const { tracker } = fakeLinear({
303 T3Viewer: () => ({
304 viewer: JULIUS,
305 organization: { urlKey: "acme" },
306 teams: { nodes: [] },
307 }),
308 T3Issue: () => ({
309 issue: issue("ENG-7", {
310 comments: {
311 nodes: [
312 {
313 id: "cmt_1",
314 body: "hi",
315 createdAt: "2026-07-02T01:00:00.000Z",
316 url: "https://linear.app/acme/issue/ENG-7#comment-cmt_1",
317 user: THEO,
318 botActor: null,
319 reactions: [{ id: "r1", emoji: "+1", user: JULIUS }],
320 },
321 ],
322 pageInfo: { hasNextPage: true, endCursor: "cmt_cur" },
323 },
324 reactions: [
325 { id: "r2", emoji: "πŸš€", user: THEO },
326 { id: "r3", emoji: "rocket", user: JULIUS },
327 { id: "r4", emoji: "🀷", user: THEO },
328 ],
329 attachments: {
330 nodes: [
331 {
332 url: "https://github.com/acme/web/pull/12",
333 title: "Fix it",
334 sourceType: "github",
335 metadata: { status: "merged" },
336 },
337 { url: "https://example.test/doc", title: "Doc", sourceType: null, metadata: {} },
338 ],
339 },
340 history: {
341 nodes: [
342 {
343 id: "h1",
344 createdAt: "2026-07-01T01:00:00.000Z",
345 // An integration acted: Linear names it beside an empty user.
346 actor: null,
347 botActor: { name: "GitHub", userDisplayName: null, avatarUrl: null },
348 fromState: state("Todo", "unstarted"),
349 toState: state("Done", "completed"),
350 fromAssignee: null,
351 toAssignee: JULIUS,
352 addedLabels: [{ id: "lbl_bug", name: "Bug", color: "#f00" }],
353 removedLabels: null,
354 fromTitle: null,
355 toTitle: null,
356 },
357 ],
358 },
359 }),
360 }),
361 });
362 const api = yield* tracker;
363 const detail = yield* api.getIssue({ ...target, key: "eng-7" });
364 expect(detail.viewer).toBe("julius");
365 expect((yield* api.probeCredential("token")).workspace).toBe("acme");
366 // The team's own workflow, in Linear's order, with the category each state falls in.
367 expect(detail.states.map((entry) => [entry.name, entry.category])).toEqual([
368 ["Todo", "open"],
369 ["In Progress", "open"],
370 ["Done", "closed"],
371 ["Canceled", "closed"],
372 ]);
373 expect(detail.commentsCursor).toBe("cmt_cur");
374 expect(detail.comments[0]?.reactions).toEqual([
375 { content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true },
376 ]);
377 // Grouped per emoji, the viewer left out of the names; an emoji outside the vocabulary is dropped.
378 expect(detail.reactions).toEqual([
379 { content: "rocket", count: 2, actors: ["theo"], viewerHasReacted: true },
380 ]);
381 expect(detail.events.map((event) => [event.kind, event.detail])).toEqual([
382 ["closed", "Done"],
383 ["labeled", "Bug"],
384 ["assigned", "julius"],
385 ]);
386 expect(detail.events[0]?.actor).toEqual({
387 isBot: true,
388 login: "GitHub",
389 name: "GitHub",
390 avatarUrl: null,
391 });
392 expect(detail.linkedPullRequests).toEqual([
393 expect.objectContaining({ repository: "acme/web", number: 12, state: "merged" }),
394 ]);
395​
396 const missing = yield* Effect.flip(api.getIssue({ ...target, key: "123" }));
397 expect(missing.reason).toBe("not-found");
398 }),
399 );
400​
401 it.effect("closes through the team's completed state, without a key or outside the team", () =>
402 Effect.gen(function* () {
403 const updates: Array<Record<string, unknown>> = [];
404 const { tracker } = fakeLinear(
405 {
406 T3Team: () => ({
407 teams: {
408 nodes: [
409 {
410 id: "team_eng",
411 key: "ENG",
412 name: "Engineering",
413 states: {
414 nodes: [
415 state("Canceled", "canceled", 3),
416 state("Done", "completed", 2),
417 state("Todo", "unstarted", 1),
418 ],
419 pageInfo: { hasNextPage: false, endCursor: null },
420 },
421 labels: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
422 members: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
423 templates: { nodes: [] },
424 },
425 ],
426 },
427 issueLabels: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
428 }),
429 T3IssueUpdate: (variables) => {
430 updates.push(variables);
431 return { issueUpdate: { success: true } };
432 },
433 },
434 null,
435 );
436 const api = yield* tracker;
437 const unauthenticated = yield* Effect.flip(
438 api.setState({ ...target, key: "ENG-1", state: "Done" }),
439 );
440 expect(unauthenticated.reason).toBe("unauthenticated");
441​
442 const connected = fakeLinear({
443 T3Team: () => ({
444 teams: {
445 nodes: [
446 {
447 id: "team_eng",
448 key: "ENG",
449 name: "Engineering",
450 states: {
451 nodes: [
452 state("Canceled", "canceled", 3),
453 state("Done", "completed", 2),
454 state("Todo", "unstarted", 1),
455 ],
456 pageInfo: { hasNextPage: false, endCursor: null },
457 },
458 labels: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
459 members: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
460 templates: { nodes: [] },
461 },
462 ],
463 },
464 issueLabels: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
465 }),
466 T3Issue: (variables) => ({ issue: bareDetail(String(variables.id)) }),
467 T3IssueUpdate: (variables) => {
468 updates.push(variables);
469 return { issueUpdate: { success: true } };
470 },
471 });
472 const live = yield* connected.tracker;
473 // An identifier from another team resolves in Linear, so the team is checked before writing.
474 const foreign = yield* Effect.flip(live.setState({ ...target, key: "OPS-3", state: "Done" }));
475 expect(foreign.detail).toContain("OPS");
476 // A move names one of the team's own states; nothing is asked for as "open" or "closed".
477 yield* live.setState({ ...target, key: "ENG-1", state: "Canceled" });
478 yield* live.setState({ ...target, key: "ENG-1", state: "Todo" });
479 const unknown = yield* Effect.flip(
480 live.setState({ ...target, key: "ENG-1", state: "closed" }),
481 );
482 expect(unknown.detail).toContain('no "closed" state');
483 expect(updates.map((update) => update.input)).toEqual([
484 { stateId: "st_canceled" },
485 { stateId: "st_todo" },
486 ]);
487 }),
488 );
489​
490 it("offers plain templates as drafts and form or rich ones as links into Linear", () => {
491 const labels = new Map([["lbl_bug", "Bug"]]);
492 const plain = LinearIssueTracker.toTemplate(
493 {
494 id: "tpl_1",
495 name: "Bug report",
496 description: "For bugs",
497 content: "## Steps",
498 type: "issue",
499 hasFormFields: false,
500 templateData: { title: "Bug: ", labelIds: ["lbl_bug", "lbl_unknown"], assigneeId: null },
501 },
502 "ENG",
503 labels,
504 );
505 expect(plain).toEqual({
506 template: {
507 key: "tpl_1",
508 name: "Bug report",
509 about: "For bugs",
510 title: "Bug: ",
511 body: "## Steps",
512 labels: ["Bug"],
513 assignees: [],
514 },
515 });
516 const form = LinearIssueTracker.toTemplate(
517 {
518 id: "tpl_2",
519 name: "Intake",
520 description: null,
521 content: null,
522 type: "issue",
523 hasFormFields: true,
524 templateData: {},
525 },
526 "ENG",
527 labels,
528 );
529 expect(form).toEqual({
530 link: { name: "Intake", about: "", url: "https://linear.app/team/ENG/new?template=tpl_2" },
531 });
532 });
533});