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