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

GitHubIssueTracker.test.ts

613 lines20.8 KB

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 );
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 );
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 viewer: "julius",
401 labels: ['needs "repro"'],
402 assignee: "theo",
403 sort: "created",
404 limit: 10,
405 })
406 .pipe(Effect.exit);
407 expect(seen[0]).toMatchObject({
408 q: 'is:issue repo:acme/web is:open label:"needs \\"repro\\"" assignee:"theo" sort:created-desc',
409 });
410 }),
411 );
412​
413 it.effect("offers YAML issue forms when blank issues are disabled", () =>
414 Effect.gen(function* () {
415 const form = {
416 __typename: "Blob",
417 isTruncated: false,
418 text: `name: Bug report
419description: Report broken behavior.
420title: "[Bug]: "
421labels: [bug, needs-triage]
422assignees: "octocat, theo"
423body:
424 - type: markdown
425 attributes:
426 value: Search existing issues first.
427 - type: checkboxes
428 attributes:
429 label: Before submitting
430 options:
431 - label: I searched existing issues.
432 required: true
433 - type: dropdown
434 attributes:
435 label: Area
436 description: Which part is affected?
437 options: [Web, Server]
438 default: 1
439 validations:
440 required: true
441 - type: textarea
442 attributes:
443 label: Steps to reproduce
444 placeholder: Start the app.
445 - type: input
446 attributes:
447 label: Version
448 value: main
449 - type: upload
450 attributes:
451 label: Supporting files
452 description: Redact secrets before uploading.
453`,
454 };
455 const config = {
456 __typename: "Blob",
457 isTruncated: false,
458 text: '"blank_issues_enabled": false # use a template',
459 };
460 const repository = {
461 issueTemplates: [],
462 templateDirectory: {
463 __typename: "Tree",
464 entries: [
465 { name: "config.yml", object: config },
466 { name: "bug_report.yml", object: form },
467 {
468 name: "empty_name.yml",
469 object: { ...form, text: 'name: ""\ndescription: Empty name\nbody: []' },
470 },
471 {
472 name: "blank_name.yml",
473 object: { ...form, text: 'name: " "\ndescription: Blank name\nbody: []' },
474 },
475 {
476 name: "invalid.yml",
477 object: { ...form, text: "name: Missing required metadata\nbody: []" },
478 },
479 ],
480 },
481 };
482 const api = yield* tracker(() => {}, repository);
483 const input = { cwd: "/w", host: "github.com", scope: "acme/web" };
484 const result = yield* api.listTemplates!(input);
485 expect(encodeTemplateList(result)).toEqual(result);
486 expect(result.blankIssuesEnabled).toBe(false);
487 expect(result.templates).toHaveLength(1);
488 expect(result.templates[0]).toMatchObject({
489 key: "bug_report.yml",
490 name: "Bug report",
491 about: "Report broken behavior.",
492 title: "[Bug]: ",
493 labels: ["bug", "needs-triage"],
494 assignees: ["octocat", "theo"],
495 });
496 expect(result.templates[0]?.body).toBe(`Search existing issues first.
497​
498### Before submitting
499​
500- [ ] I searched existing issues. (required)
501​
502### Area
503​
504Which part is affected?
505​
506Required.
507​
508Choose one:
509​
510- Web
511- Server (default)
512​
513### Steps to reproduce
514​
515Example:
516> Start the app.
517​
518### Version
519​
520main
521​
522### Supporting files
523​
524Redact secrets before uploading.`);
525 config.isTruncated = true;
526 expect(yield* Effect.flip(api.listTemplates!(input))).toMatchObject({
527 reason: "failed",
528 detail: "GitHub returned incomplete issue template contents.",
529 });
530 }),
531 );
532​
533 it.effect("maps a detail read to the neutral issue shape", () =>
534 Effect.gen(function* () {
535 const seen: unknown[] = [];
536 const api = yield* tracker((variables) => {
537 seen.push(variables);
538 });
539 const issue = yield* api.getIssue({
540 cwd: "/w",
541 host: "github.com",
542 scope: "acme/web",
543 key: "42",
544 });
545 expect(seen).toEqual([
546 { owner: "acme", name: "web", number: 42 },
547 {
548 owner: "acme",
549 name: "web",
550 number: 42,
551 labelsCursor: "labels-next",
552 assigneesCursor: null,
553 },
554 ]);
555 expect(issue).toMatchObject({
556 key: "42",
557 displayKey: "#42",
558 title: "Composer loses focus",
559 body: "Typing in the composer drops focus after a paste.",
560 state: { category: "closed", name: "Duplicate", closeReason: "duplicate" },
561 states: [
562 { category: "open", name: "Open" },
563 { category: "closed", name: "Completed", closeReason: "completed" },
564 { category: "closed", name: "Not planned", closeReason: "not-planned" },
565 { category: "closed", name: "Duplicate", closeReason: "duplicate" },
566 ],
567 author: {
568 login: "octocat",
569 name: "Octo Cat",
570 avatarUrl: "https://avatars/octocat",
571 },
572 assignees: [{ login: "theo" }],
573 labels: [
574 { name: "bug", color: "d73a4a" },
575 { name: "needs repro", color: "ffffff" },
576 ],
577 commentCount: 3,
578 viewer: "julius",
579 // Triage may label, assign, close and reopen; `viewerCanUpdate: false` withholds edits.
580 viewerPermissions: {
581 setState: true,
582 edit: false,
583 labels: true,
584 assignees: true,
585 comment: true,
586 },
587 commentsCursor: "Y3Vyc29y",
588 });
589 // The viewer is left out of `actors` and shown as "You"; an empty group is dropped.
590 expect(issue.comments[0]?.reactions).toEqual([
591 { content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true },
592 ]);
593 // The closing reference wins over the cross-reference sighting of the same pull request.
594 expect(issue.linkedPullRequests).toEqual([
595 {
596 repository: "acme/web",
597 number: 50,
598 title: "fix(web): keep composer focus",
599 url: "https://github.com/acme/web/pull/50",
600 state: "merged",
601 isDraft: false,
602 closesIssue: true,
603 },
604 ]);
605 // An event kind this page has no vocabulary for is dropped rather than guessed at.
606 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
607 ["labeled", "bug"],
608 ["referenced", "acme/web#50"],
609 ["closed", null],
610 ]);
611 }),
612 );
613});