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";
4
5import * as Redacted from "effect/Redacted";
6import * as Schema from "effect/Schema";
7import { HttpClient, HttpClientResponse } from "effect/http";
8import { IssueTemplateList } from "@t3tools/contracts";
9import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
10import * as GitHubCredentials from "./GitHubCredentials.ts";
11import * as GitHubRest from "./GitHubRest.ts";
12import * as GitHubQuota from "./GitHubQuota.ts";
13import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
14import * as GitHubIssueTracker from "./GitHubIssueTracker.ts";
15
16const DETAIL_RESPONSE = JSON.stringify({
17 data: {
18 viewer: { login: "julius" },
19 repository: {
20 viewerPermission: "TRIAGE",
21 issue: {
22 __typename: "Issue",
23 number: 42,
24 title: "Composer loses focus",
25 url: "https://github.com/acme/web/issues/42",
26 author: {
27 __typename: "User",
28 login: "octocat",
29 avatarUrl: "https://avatars/octocat",
30 name: "Octo Cat",
31 },
32 state: "CLOSED",
33 stateReason: "DUPLICATE",
34 createdAt: "2026-07-01T00:00:00Z",
35 updatedAt: "2026-07-03T00:00:00Z",
36 closedAt: "2026-07-03T00:00:00Z",
37 comments: {
38 totalCount: 3,
39 pageInfo: { hasPreviousPage: true, startCursor: "Y3Vyc29y" },
40 nodes: [
41 {
42 __typename: "IssueComment",
43 id: "IC_1",
44 author: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
45 body: "Repro attached.",
46 createdAt: "2026-07-02T00:00:00Z",
47 url: "https://github.com/acme/web/issues/42#issuecomment-1",
48 reactionGroups: [
49 {
50 content: "THUMBS_UP",
51 viewerHasReacted: true,
52 reactors: {
53 totalCount: 2,
54 nodes: [
55 { __typename: "User", login: "julius" },
56 { __typename: "User", login: "theo" },
57 ],
58 },
59 },
60 {
61 content: "EYES",
62 viewerHasReacted: false,
63 reactors: { totalCount: 0, nodes: [] },
64 },
65 ],
66 },
67 ],
68 },
69 assignees: {
70 pageInfo: { hasNextPage: false, endCursor: null },
71 nodes: [{ login: "theo", name: null, avatarUrl: "https://avatars/julius" }],
72 },
73 labels: {
74 pageInfo: { hasNextPage: true, endCursor: "labels-next" },
75 nodes: [{ name: "bug", color: "d73a4a" }, null],
76 },
77 body: "Typing in the composer drops focus after a paste.",
78 viewerCanUpdate: false,
79 viewerCanClose: false,
80 viewerCanReopen: true,
81 reactionGroups: [],
82 closedByPullRequestsReferences: {
83 pageInfo: { hasNextPage: true, endCursor: "links-next" },
84 nodes: [
85 {
86 number: 50,
87 title: "fix(web): keep composer focus",
88 url: "https://github.com/acme/web/pull/50",
89 state: "MERGED",
90 isDraft: false,
91 repository: { nameWithOwner: "acme/web" },
92 },
93 ],
94 },
95 timelineItems: {
96 nodes: [
97 {
98 __typename: "LabeledEvent",
99 id: "LE_1",
100 createdAt: "2026-07-01T01:00:00Z",
101 actor: { __typename: "User", login: "theo", avatarUrl: "https://avatars/theo" },
102 label: { name: "bug" },
103 },
104 {
105 __typename: "CrossReferencedEvent",
106 id: "CRE_1",
107 createdAt: "2026-07-02T01:00:00Z",
108 actor: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
109 source: {
110 __typename: "PullRequest",
111 number: 50,
112 title: "fix(web): keep composer focus",
113 url: "https://github.com/acme/web/pull/50",
114 state: "MERGED",
115 isDraft: false,
116 repository: { nameWithOwner: "acme/web" },
117 },
118 },
119 { __typename: "MentionedEvent", id: "ME_1", createdAt: "2026-07-02T02:00:00Z" },
120 {
121 __typename: "ClosedEvent",
122 id: "CE_1",
123 createdAt: "2026-07-03T00:00:00Z",
124 actor: null,
125 },
126 ],
127 },
128 },
129 },
130 },
131});
132
133const decodeVariables = Schema.decodeUnknownSync(
134 Schema.fromJsonString(
135 Schema.Struct({
136 query: Schema.String,
137 variables: Schema.Record(Schema.String, Schema.Unknown),
138 }),
139 ),
140);
141
142function transport(httpClient: HttpClient.HttpClient) {
143 return GitHubRest.layer.pipe(
144 Layer.provideMerge(
145 Layer.mergeAll(
146 GitHubQuota.layer,
147 SourceControlRateLimit.layer,
148 Layer.mock(GitHubCredentials.GitHubCredentials)({
149 saved: () => Effect.succeedNone,
150 get: (host) =>
151 Effect.succeed({
152 host,
153 token: Redacted.make("test-token"),
154 source: "gh" as const,
155 fingerprint: "test",
156 }),
157 }),
158 Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
159 enabled: false,
160 token: () => Effect.succeedNone,
161 invalidate: () => Effect.void,
162 }),
163 Layer.succeed(HttpClient.HttpClient, httpClient),
164 ),
165 ),
166 );
167}
168
169function tracker(onRequest: (variables: unknown) => void, templateRepository?: unknown) {
170 return GitHubIssueTracker.make.pipe(
171 Effect.provide(
172 transport(
173 HttpClient.make((request) => {
174 if (request.body._tag !== "Uint8Array")
175 return Effect.die("Expected a GraphQL JSON request.");
176 const { variables } = decodeVariables(new TextDecoder().decode(request.body.body));
177 onRequest(variables);
178 const body =
179 templateRepository !== undefined
180 ? JSON.stringify({ data: { repository: templateRepository } })
181 : "labelsCursor" in variables
182 ? JSON.stringify({
183 data: {
184 repository: {
185 issue: {
186 labels: {
187 pageInfo: { hasNextPage: false, endCursor: null },
188 nodes: [{ name: "needs repro", color: "ffffff" }],
189 },
190 closedByPullRequestsReferences: {
191 pageInfo: { hasNextPage: false, endCursor: null },
192 nodes: [
193 {
194 number: 61,
195 title: "fix(web): restore focus after paste",
196 url: "https://github.com/acme/web/pull/61",
197 state: "OPEN",
198 isDraft: true,
199 repository: { nameWithOwner: "acme/web" },
200 },
201 ],
202 },
203 },
204 },
205 },
206 })
207 : DETAIL_RESPONSE;
208 return Effect.succeed(
209 HttpClientResponse.fromWeb(
210 request,
211 new Response(body, {
212 headers: { "content-type": "application/json" },
213 }),
214 ),
215 );
216 }),
217 ),
218 ),
219 );
220}
221
222const encodeTemplateList = Schema.encodeSync(IssueTemplateList);
223
224const decodeBody = Schema.decodeUnknownSync(
225 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
226);
227
228describe("GitHubIssueTracker", () => {
229 it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () =>
230 Effect.gen(function* () {
231 const requests: unknown[] = [];
232 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
233 const url = "https://github.com/acme/web/issues/42";
234 const found = yield* tracker((input) => requests.push(input), {
235 issue: { number: 42, title: "Fixture issue", url },
236 });
237 expect(yield* found.getIssueLink(target)).toEqual({
238 displayKey: "#42",
239 title: "Fixture issue",
240 url,
241 });
242
243 const missing = yield* tracker((input) => requests.push(input), { issue: null });
244 expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({
245 reason: "not-found",
246 });
247 expect(requests).toEqual([
248 { owner: "acme", name: "web", number: 42 },
249 { owner: "acme", name: "web", number: 42 },
250 ]);
251 }),
252 );
253
254 it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () =>
255 Effect.gen(function* () {
256 const writes: unknown[] = [];
257 let issueState: { state: string; stateReason: string | null } = {
258 state: "OPEN",
259 stateReason: null,
260 };
261 const http = HttpClient.make((request) => {
262 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
263 const text = new TextDecoder().decode(request.body.body);
264 let response: unknown = {};
265 if (request.url === "https://api.github.com/graphql") {
266 const { query, variables } = decodeVariables(text);
267 expect(request.method).toBe("POST");
268 const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1];
269 if (operation === "IssueNodeId" || operation === "IssueCommentScope") {
270 expect(variables).toMatchObject({ owner: "acme", name: "web" });
271 response = {
272 data: {
273 repository: {
274 issue: variables["number"] === 42 ? { id: "I_42", ...issueState } : null,
275 },
276 ...(operation === "IssueCommentScope"
277 ? { node: { __typename: "IssueComment", issue: { id: "I_other" } } }
278 : {}),
279 },
280 };
281 } else {
282 expect(["AddReaction", "RemoveReaction"]).toContain(operation);
283 expect(variables).toEqual({ subjectId: "I_42", content: "THUMBS_UP" });
284 writes.push(operation);
285 response = {
286 data: {
287 [operation === "AddReaction" ? "addReaction" : "removeReaction"]: {
288 reaction: { content: "THUMBS_UP" },
289 },
290 },
291 };
292 }
293 } else {
294 const body = decodeBody(text);
295 writes.push([request.method, request.url, body]);
296 if (typeof body["state"] === "string") {
297 issueState = {
298 state: body["state"].toUpperCase(),
299 stateReason:
300 typeof body["state_reason"] === "string"
301 ? body["state_reason"].toUpperCase()
302 : null,
303 };
304 }
305 if (request.url.endsWith("/issues")) {
306 response = { number: 42, html_url: "https://github.com/acme/web/issues/42" };
307 } else if (request.method === "PATCH" && body["title"] === "Dropped") {
308 // What GitHub answers a caller without triage access: success, metadata untouched.
309 response = { labels: [{ name: "Bug" }], assignees: [] };
310 } else if (request.method === "PATCH") {
311 response = { labels: [], assignees: [] };
312 }
313 }
314 return Effect.succeed(
315 HttpClientResponse.fromWeb(
316 request,
317 new Response(JSON.stringify(response), {
318 headers: { "content-type": "application/json" },
319 }),
320 ),
321 );
322 });
323 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
324 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
325 expect(
326 yield* api.create({
327 ...target,
328 title: "Fixture",
329 body: "Body",
330 labels: ["bug"],
331 assignees: ["octocat"],
332 }),
333 ).toEqual({
334 key: "42",
335 displayKey: "#42",
336 url: "https://github.com/acme/web/issues/42",
337 });
338 yield* api.comment({ ...target, body: "Comment" });
339 yield* api.update({ ...target, title: "Updated", body: "Edited", labels: [], assignees: [] });
340 expect(
341 yield* Effect.flip(api.update({ ...target, title: "Dropped", labels: ["bug", "p1"] })),
342 ).toMatchObject({ operation: "update", reason: "failed" });
343 yield* api.update({ ...target, title: "Dropped", labels: ["bug"], assignees: [] });
344 expect(yield* Effect.flip(api.setState({ ...target, state: "closed" }))).toMatchObject({
345 operation: "setState",
346 reason: "failed",
347 });
348 yield* api.setState({ ...target, state: "Not planned" });
349 // GitHub ignores a new reason on a closed issue, so it is refused instead of sent.
350 expect(
351 yield* api.setState({ ...target, state: "Completed" }).pipe(Effect.result),
352 ).toMatchObject({ _tag: "Failure", failure: { operation: "setState", reason: "failed" } });
353 yield* api.setState({ ...target, state: "Open" });
354 yield* api.setState({ ...target, state: "Duplicate" });
355 yield* api.setState({ ...target, state: "Open" });
356 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: true });
357 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: false });
358
359 const pullRequest = { ...target, key: "50" };
360 expect(
361 yield* api.update({ ...pullRequest, title: "Do not edit" }).pipe(Effect.result),
362 ).toMatchObject({ _tag: "Failure", failure: { operation: "update", reason: "not-found" } });
363 expect(
364 yield* api.setState({ ...pullRequest, state: "Completed" }).pipe(Effect.result),
365 ).toMatchObject({
366 _tag: "Failure",
367 failure: { operation: "setState", reason: "not-found" },
368 });
369 expect(
370 yield* api.comment({ ...pullRequest, body: "Do not comment" }).pipe(Effect.result),
371 ).toMatchObject({ _tag: "Failure", failure: { operation: "comment", reason: "not-found" } });
372 expect(
373 yield* Effect.flip(
374 api.setReaction({
375 ...target,
376 subjectId: "IC_other",
377 content: "thumbs-up",
378 reacted: true,
379 }),
380 ),
381 ).toMatchObject({ operation: "setReaction", reason: "failed" });
382
383 expect(writes).toEqual([
384 [
385 "POST",
386 "https://api.github.com/repos/acme/web/issues",
387 { title: "Fixture", body: "Body", labels: ["bug"], assignees: ["octocat"] },
388 ],
389 ["POST", "https://api.github.com/repos/acme/web/issues/42/comments", { body: "Comment" }],
390 [
391 "PATCH",
392 "https://api.github.com/repos/acme/web/issues/42",
393 { title: "Updated", body: "Edited", labels: [], assignees: [] },
394 ],
395 [
396 "PATCH",
397 "https://api.github.com/repos/acme/web/issues/42",
398 { title: "Dropped", labels: ["bug", "p1"] },
399 ],
400 [
401 "PATCH",
402 "https://api.github.com/repos/acme/web/issues/42",
403 { title: "Dropped", labels: ["bug"], assignees: [] },
404 ],
405 [
406 "PATCH",
407 "https://api.github.com/repos/acme/web/issues/42",
408 { state: "closed", state_reason: "not_planned" },
409 ],
410 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
411 [
412 "PATCH",
413 "https://api.github.com/repos/acme/web/issues/42",
414 { state: "closed", state_reason: "duplicate" },
415 ],
416 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
417 "AddReaction",
418 "RemoveReaction",
419 ]);
420 }),
421 );
422
423 it.effect("asks search for the labels, assignee and order a listing names", () =>
424 Effect.gen(function* () {
425 const seen: unknown[] = [];
426 const api = yield* tracker((variables) => seen.push(variables));
427 // The canned answer is not a search result; only the query sent matters here.
428 yield* api
429 .listIssues({
430 cwd: "/w",
431 host: "github.com",
432 scope: "acme/web",
433 state: "open",
434 involvement: "all",
435 labels: ['needs "repro"'],
436 assignee: "theo",
437 sort: "created",
438 limit: 10,
439 })
440 .pipe(Effect.exit);
441 expect(seen[0]).toMatchObject({
442 q: 'is:issue repo:acme/web is:open label:"needs \\"repro\\"" assignee:"theo" sort:created-desc',
443 });
444 }),
445 );
446
447 it.effect("offers YAML issue forms when blank issues are disabled", () =>
448 Effect.gen(function* () {
449 const form = {
450 __typename: "Blob",
451 isTruncated: false,
452 text: `name: Bug report
453description: Report broken behavior.
454title: "[Bug]: "
455labels: [bug, needs-triage]
456assignees: "octocat, theo"
457body:
458 - type: markdown
459 attributes:
460 value: Search existing issues first.
461 - type: checkboxes
462 attributes:
463 label: Before submitting
464 options:
465 - label: I searched existing issues.
466 required: true
467 - type: dropdown
468 attributes:
469 label: Area
470 description: Which part is affected?
471 options: [Web, Server]
472 default: 1
473 validations:
474 required: true
475 - type: textarea
476 attributes:
477 label: Steps to reproduce
478 placeholder: Start the app.
479 - type: input
480 attributes:
481 label: Version
482 value: main
483 - type: upload
484 attributes:
485 label: Supporting files
486 description: Redact secrets before uploading.
487`,
488 };
489 const config = {
490 __typename: "Blob",
491 isTruncated: false,
492 text: '"blank_issues_enabled": false # use a template',
493 };
494 const repository = {
495 issueTemplates: [],
496 templateDirectory: {
497 __typename: "Tree",
498 entries: [
499 { name: "config.yml", object: config },
500 { name: "bug_report.yml", object: form },
501 {
502 name: "empty_name.yml",
503 object: { ...form, text: 'name: ""\ndescription: Empty name\nbody: []' },
504 },
505 {
506 name: "blank_name.yml",
507 object: { ...form, text: 'name: " "\ndescription: Blank name\nbody: []' },
508 },
509 {
510 name: "invalid.yml",
511 object: { ...form, text: "name: Missing required metadata\nbody: []" },
512 },
513 ],
514 },
515 };
516 const api = yield* tracker(() => {}, repository);
517 const input = { cwd: "/w", host: "github.com", scope: "acme/web" };
518 const result = yield* api.listTemplates!(input);
519 expect(encodeTemplateList(result)).toEqual(result);
520 expect(result.blankIssuesEnabled).toBe(false);
521 expect(result.templates).toHaveLength(1);
522 expect(result.templates[0]).toMatchObject({
523 key: "bug_report.yml",
524 name: "Bug report",
525 about: "Report broken behavior.",
526 title: "[Bug]: ",
527 labels: ["bug", "needs-triage"],
528 assignees: ["octocat", "theo"],
529 });
530 expect(result.templates[0]?.body).toBe(`Search existing issues first.
531
532### Before submitting
533
534- [ ] I searched existing issues. (required)
535
536### Area
537
538Which part is affected?
539
540Required.
541
542Choose one:
543
544- Web
545- Server (default)
546
547### Steps to reproduce
548
549Example:
550> Start the app.
551
552### Version
553
554main
555
556### Supporting files
557
558Redact secrets before uploading.`);
559 config.isTruncated = true;
560 expect(yield* Effect.flip(api.listTemplates!(input))).toMatchObject({
561 reason: "failed",
562 detail: "GitHub returned incomplete issue template contents.",
563 });
564 }),
565 );
566
567 it.effect("maps a detail read to the neutral issue shape", () =>
568 Effect.gen(function* () {
569 const seen: unknown[] = [];
570 const api = yield* tracker((variables) => {
571 seen.push(variables);
572 });
573 const issue = yield* api.getIssue({
574 cwd: "/w",
575 host: "github.com",
576 scope: "acme/web",
577 key: "42",
578 });
579 expect(seen).toEqual([
580 { owner: "acme", name: "web", number: 42 },
581 {
582 owner: "acme",
583 name: "web",
584 number: 42,
585 labelsCursor: "labels-next",
586 assigneesCursor: null,
587 closingPullRequestsCursor: "links-next",
588 withLabels: true,
589 withAssignees: false,
590 withClosingPullRequests: true,
591 },
592 ]);
593 expect(issue).toMatchObject({
594 key: "42",
595 displayKey: "#42",
596 title: "Composer loses focus",
597 body: "Typing in the composer drops focus after a paste.",
598 state: { category: "closed", name: "Duplicate", closeReason: "duplicate" },
599 states: [
600 { category: "open", name: "Open" },
601 { category: "closed", name: "Completed", closeReason: "completed" },
602 { category: "closed", name: "Not planned", closeReason: "not-planned" },
603 { category: "closed", name: "Duplicate", closeReason: "duplicate" },
604 ],
605 author: {
606 login: "octocat",
607 name: "Octo Cat",
608 avatarUrl: "https://avatars/octocat",
609 },
610 assignees: [{ login: "theo" }],
611 labels: [
612 { name: "bug", color: "d73a4a" },
613 { name: "needs repro", color: "ffffff" },
614 ],
615 commentCount: 3,
616 viewer: "julius",
617 // Triage may label, assign, close and reopen; `viewerCanUpdate: false` withholds edits.
618 viewerPermissions: {
619 setState: true,
620 edit: false,
621 labels: true,
622 assignees: true,
623 comment: true,
624 },
625 commentsCursor: "Y3Vyc29y",
626 });
627 // The viewer is left out of `actors` and shown as "You"; an empty group is dropped.
628 expect(issue.comments[0]?.reactions).toEqual([
629 { content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true },
630 ]);
631 // The closing reference wins over the cross-reference sighting of the same pull request.
632 expect(issue.linkedPullRequests).toEqual([
633 {
634 repository: "acme/web",
635 number: 50,
636 title: "fix(web): keep composer focus",
637 url: "https://github.com/acme/web/pull/50",
638 state: "merged",
639 isDraft: false,
640 closesIssue: true,
641 },
642 // A closing reference past the first page, with no timeline sighting, still shows.
643 {
644 repository: "acme/web",
645 number: 61,
646 title: "fix(web): restore focus after paste",
647 url: "https://github.com/acme/web/pull/61",
648 state: "open",
649 isDraft: true,
650 closesIssue: true,
651 },
652 ]);
653 // An event kind this page has no vocabulary for is dropped rather than guessed at.
654 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
655 ["labeled", "bug"],
656 ["referenced", "acme/web#50"],
657 ["closed", null],
658 ]);
659 // A cross-reference keeps what a surface needs to open its source, not only a label.
660 expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({
661 reference: {
662 repository: "acme/web",
663 number: 50,
664 kind: "pull-request",
665 url: "https://github.com/acme/web/pull/50",
666 },
667 });
668 }),
669 );
670});