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