@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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