Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - The retention test forces garbage collection in Node.
2import * as NodeTimersPromises from "node:timers/promises";
3import * as NodeV8 from "node:v8";
4import * as NodeVM from "node:vm";
5import {
6 EnvironmentId,
7 IssueTrackerKind,
8 ProjectId,
9 type IssueComment,
10 type IssueCommentsPage,
11 type IssueDetail,
12 type IssueListEntry,
13 type IssueListResult,
14 WS_METHODS,
15} from "@t3tools/contracts";
16import * as Cause from "effect/Cause";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Stream from "effect/Stream";
21import * as SubscriptionRef from "effect/SubscriptionRef";
22import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
23import { describe, expect, it } from "@effect/vitest";
24
25import {
26 AVAILABLE_CONNECTION_STATE,
27 PrimaryConnectionTarget,
28 type PreparedConnection,
29 type SupervisorConnectionState,
30} from "../connection/model.ts";
31import { EnvironmentRegistry } from "../connection/registry.ts";
32import { EnvironmentSupervisor } from "../connection/supervisor.ts";
33import type { RpcSession } from "../rpc/session.ts";
34import {
35 beginIssueCommentPost,
36 clearIssueCommentDraftsEnvironment,
37 createIssueCommentPager,
38 createIssueEnvironmentAtoms,
39 createMergedIssueCandidatesAtoms,
40 createMergedIssueListAtoms,
41 editIssueCommentDraft,
42 finishIssueCommentPost,
43 issueCommentDraftAtom,
44 issueEntryKey,
45 mergeIssueListPage,
46 type IssueListTarget,
47} from "./issues.ts";
48
49describe("issue comment drafts", () => {
50 it.each([true, false])(
51 "discards drafts when removing an environment (late send succeeded: %s)",
52 (sent) => {
53 const registry = AtomRegistry.make();
54 const environmentId = EnvironmentId.make("local");
55 const otherEnvironmentId = EnvironmentId.make("local:other");
56 const firstUrl = "https://example.atlassian.net/browse/SUP-12";
57 const draft = issueCommentDraftAtom(environmentId, firstUrl);
58 const otherIssue = issueCommentDraftAtom(
59 environmentId,
60 "https://example.atlassian.net/browse/SUP-13",
61 );
62 const otherEnvironment = issueCommentDraftAtom(otherEnvironmentId, firstUrl);
63 try {
64 editIssueCommentDraft(registry, draft, { body: "Original reply", audience: "public" });
65 editIssueCommentDraft(registry, otherIssue, { body: "Another issue" });
66 editIssueCommentDraft(registry, otherEnvironment, { body: "Another environment" });
67 const oldPost = beginIssueCommentPost(registry, draft)!;
68
69 clearIssueCommentDraftsEnvironment(registry, environmentId);
70
71 expect(registry.get(draft)).toEqual({ body: "", audience: "internal", posting: false });
72 expect(registry.get(otherIssue).body).toBe("");
73 expect(registry.get(otherEnvironment).body).toBe("Another environment");
74
75 editIssueCommentDraft(registry, draft, { body: "New reply after re-pairing" });
76 const newPost = beginIssueCommentPost(registry, draft);
77 finishIssueCommentPost(registry, draft, oldPost, sent);
78
79 expect(registry.get(draft)).toBe(newPost);
80 } finally {
81 registry.dispose();
82 }
83 },
84 );
85});
86
87function entry(overrides: Partial<IssueListEntry> & { key: string }): IssueListEntry {
88 return {
89 tracker: "github" as IssueTrackerKind,
90 host: "github.com",
91 scope: "acme/app",
92 displayKey: `#${overrides.key}`,
93 title: `Issue ${overrides.key}`,
94 url: `https://github.com/acme/app/issues/${overrides.key}`,
95 author: null,
96 state: { category: "open", name: "open" },
97 createdAt: "2026-10-01T00:00:00.000Z",
98 updatedAt: "2026-10-01T00:00:00.000Z",
99 closedAt: null,
100 assignees: [],
101 labels: [],
102 commentCount: 0,
103 projectId: "project-1" as ProjectId,
104 projectTitle: "App",
105 ...overrides,
106 };
107}
108
109describe("mergeIssueListPage", () => {
110 it("keeps rows from scopes the page did not continue and orders by update", () => {
111 const held = [
112 entry({ key: "1", updatedAt: "2026-10-03T00:00:00.000Z" }),
113 entry({ key: "9", scope: "acme/other", updatedAt: "2026-10-02T00:00:00.000Z" }),
114 ];
115 const page = [entry({ key: "2", updatedAt: "2026-10-04T00:00:00.000Z" })];
116 expect(mergeIssueListPage(held, page).map((row) => row.key)).toEqual(["2", "1", "9"]);
117 });
118
119 it("replaces a repeated row with the page's newer words", () => {
120 const held = [entry({ key: "1", title: "Old title" })];
121 const page = [
122 entry({ key: "1", title: "New title", state: { category: "closed", name: "closed" } }),
123 ];
124 const merged = mergeIssueListPage(held, page);
125 expect(merged).toHaveLength(1);
126 expect(merged[0]?.title).toBe("New title");
127 expect(merged[0]?.state.category).toBe("closed");
128 });
129
130 it("keys rows case-insensitively by host and scope, exactly by key", () => {
131 expect(issueEntryKey(entry({ key: "1", host: "GitHub.com", scope: "Acme/App" }))).toBe(
132 issueEntryKey(entry({ key: "1" })),
133 );
134 expect(issueEntryKey(entry({ key: "ENG-1" }))).not.toBe(issueEntryKey(entry({ key: "eng-1" })));
135 });
136});
137
138const comment = (id: string): IssueComment => ({
139 id,
140 author: null,
141 body: id,
142 createdAt: "2026-10-01T00:00:00.000Z",
143 url: null,
144});
145
146describe("createIssueCommentPager", () => {
147 it("keeps older pages through a failed refresh", async () => {
148 const loaded = AsyncResult.success({ comments: [comment("newest")], commentsCursor: "first" });
149 const detail =
150 Atom.make<AsyncResult.AsyncResult<Pick<IssueDetail, "comments" | "commentsCursor">, string>>(
151 loaded,
152 );
153 const pager = createIssueCommentPager(detail);
154 const registry = AtomRegistry.make();
155 const unmount = registry.mount(pager.view);
156 try {
157 await pager.loadOlder(registry, async () =>
158 AsyncResult.success({ comments: [comment("older")], nextCursor: null }),
159 );
160 await pager.refresh(registry, async () => {
161 registry.set(detail, AsyncResult.waiting(loaded));
162 registry.set(
163 detail,
164 AsyncResult.failure(Cause.fail("rate limited"), { previousSuccess: Option.some(loaded) }),
165 );
166 });
167 expect(registry.get(pager.view).comments.map(({ id }) => id)).toEqual(["older", "newest"]);
168 } finally {
169 unmount();
170 registry.dispose();
171 }
172 });
173
174 it("drops older pages once a refresh lands, including one still loading, and pauses paging until it ends", async () => {
175 // The refreshed detail hands back the same cursor, so only the refresh itself can tell pages apart.
176 const detail = Atom.make(
177 AsyncResult.success({ comments: [comment("newest")], commentsCursor: "first-page" }),
178 );
179 const pager = createIssueCommentPager(detail);
180 const registry = AtomRegistry.make();
181 const unmount = registry.mount(pager.view);
182 const ids = () => registry.get(pager.view).comments.map(({ id }) => id);
183 const cursors: string[] = [];
184 const page = AsyncResult.success<IssueCommentsPage>({
185 comments: [comment("older"), comment("newest")],
186 nextCursor: "second-page",
187 });
188 const read = async (cursor: string) => {
189 cursors.push(cursor);
190 return page;
191 };
192 try {
193 await pager.loadOlder(registry, read);
194 expect(ids()).toEqual(["older", "newest"]);
195
196 const pending = Promise.withResolvers<typeof page>();
197 const inFlight = pager.loadOlder(registry, () => pending.promise);
198 const refreshed = Promise.withResolvers<void>();
199 const refresh = pager.refresh(registry, async () => {
200 await refreshed.promise;
201 registry.set(
202 detail,
203 AsyncResult.success({ comments: [comment("newest")], commentsCursor: "first-page" }),
204 );
205 });
206 pending.resolve(page);
207 await inFlight;
208
209 await pager.loadOlder(registry, read);
210 expect(registry.get(pager.view).canLoadOlder).toBe(false);
211 refreshed.resolve();
212 await refresh;
213 expect(ids()).toEqual(["newest"]);
214 await pager.loadOlder(registry, read);
215 expect(cursors).toEqual(["first-page", "first-page"]);
216 expect(ids()).toEqual(["older", "newest"]);
217 } finally {
218 unmount();
219 registry.dispose();
220 }
221 });
222
223 it("discards loaded and late older pages after refreshing unchanged detail", async () => {
224 const value = { comments: [comment("newest")], commentsCursor: "first" };
225 const detail = Atom.make(AsyncResult.success(value));
226 const pager = createIssueCommentPager(detail);
227 const registry = AtomRegistry.make();
228 const unmount = registry.mount(pager.view);
229 const pending = Promise.withResolvers<AsyncResult.Success<IssueCommentsPage>>();
230 try {
231 await pager.loadOlder(registry, async () =>
232 AsyncResult.success({ comments: [comment("older")], nextCursor: "second" }),
233 );
234 const inFlight = pager.loadOlder(registry, () => pending.promise);
235 await pager.refresh(registry, async () => {
236 registry.set(detail, AsyncResult.waiting(registry.get(detail)));
237 registry.set(detail, AsyncResult.success(value));
238 });
239 const afterRefresh = registry.get(pager.view);
240
241 pending.resolve(AsyncResult.success({ comments: [comment("oldest")], nextCursor: null }));
242 await inFlight;
243
244 expect(afterRefresh.comments.map(({ id }) => id)).toEqual(["newest"]);
245 const settled = registry.get(pager.view);
246 expect(settled.comments.map(({ id }) => id)).toEqual(["newest"]);
247 expect(settled.nextCursor).toBe("first");
248 expect(settled.canLoadOlder).toBe(true);
249 } finally {
250 unmount();
251 registry.dispose();
252 }
253 });
254});
255
256describe("createMergedIssueCandidatesAtoms", () => {
257 it("retries only failed scopes that are not already reloading", () => {
258 const registry = AtomRegistry.make();
259 const target = (scope: string) => ({
260 environmentId: EnvironmentId.make("issues"),
261 input: {
262 projectId: ProjectId.make(scope),
263 tracker: IssueTrackerKind.make("github"),
264 host: "github.com",
265 scope,
266 },
267 });
268 const targets = [target("acme/healthy"), target("acme/flaky")];
269 const requests: string[] = [];
270 const candidates = Atom.family((scope: string) =>
271 Atom.make(
272 Effect.suspend(() => {
273 requests.push(scope);
274 if (scope === "acme/healthy") {
275 return Effect.succeed({ labels: [], assignees: [], truncated: false });
276 }
277 return requests.length === 2 ? Effect.fail("Repository unavailable") : Effect.never;
278 }),
279 ),
280 );
281 const merged = createMergedIssueCandidatesAtoms(
282 (t) => candidates(t.input.scope),
283 () => "Repository unavailable",
284 );
285 const view = merged.atom(targets);
286 const unmount = registry.mount(view);
287 try {
288 expect(registry.get(view)).toMatchObject({
289 error: "Repository unavailable",
290 isPending: false,
291 });
292
293 merged.retry(registry, targets);
294 expect(registry.get(view).isPending).toBe(true);
295 merged.retry(registry, targets);
296
297 expect(requests).toEqual(["acme/healthy", "acme/flaky", "acme/flaky"]);
298 } finally {
299 unmount();
300 registry.dispose();
301 }
302 });
303});
304
305describe("createMergedIssueListAtoms", () => {
306 const answer: IssueListResult = {
307 viewers: {},
308 trackers: [],
309 entries: [],
310 errors: [],
311 nextCursors: {},
312 };
313
314 it("refreshes the open listings of the environment written to", () => {
315 const reads = new Map<string, number>();
316 const lists = new Map<string, Atom.Atom<AsyncResult.AsyncResult<IssueListResult>>>();
317 const list = (target: IssueListTarget) => {
318 const key = `${target.environmentId}:${target.input.query}`;
319 const existing = lists.get(key);
320 if (existing !== undefined) return existing;
321 const atom = Atom.make(() => {
322 reads.set(key, (reads.get(key) ?? 0) + 1);
323 return AsyncResult.success(answer);
324 });
325 lists.set(key, atom);
326 return atom;
327 };
328 const listings = createMergedIssueListAtoms(
329 { list, refreshList: (registry, target) => registry.refresh(list(target)) },
330 String,
331 );
332 const registry = AtomRegistry.make();
333 const written = EnvironmentId.make("written");
334 const other = EnvironmentId.make("other");
335 try {
336 const listing = listings.atom([
337 { environmentId: written, input: { state: "open", query: "bug" } },
338 { environmentId: other, input: { state: "open", query: "bug" } },
339 ]);
340 registry.mount(listing);
341
342 listings.refreshEnvironment(registry, written);
343 registry.get(listing);
344 expect(Object.fromEntries(reads)).toEqual({ "written:bug": 2, "other:bug": 1 });
345 } finally {
346 registry.dispose();
347 }
348 });
349
350 it("retries only failed environments, leaving one still loading to finish", () => {
351 const registry = AtomRegistry.make();
352 const targets = ["slow", "flaky"].map((environmentId) => ({
353 environmentId: EnvironmentId.make(environmentId),
354 input: { state: "open" as const },
355 }));
356 const requests: string[] = [];
357 const lists = Atom.family((environmentId: string) =>
358 Atom.make(
359 Effect.suspend(() => {
360 requests.push(environmentId);
361 return environmentId === "flaky" ? Effect.fail("Tracker unavailable") : Effect.never;
362 }),
363 ),
364 );
365 const listings = createMergedIssueListAtoms(
366 { list: (target) => lists(target.environmentId), refreshList: () => {} },
367 () => "Tracker unavailable",
368 );
369 const view = listings.atom(targets);
370 const unmount = registry.mount(view);
371 try {
372 expect(registry.get(view)).toMatchObject({ error: "Tracker unavailable", isPending: true });
373
374 listings.retry(registry, targets);
375
376 expect(requests).toEqual(["slow", "flaky", "flaky"]);
377 } finally {
378 unmount();
379 registry.dispose();
380 }
381 });
382
383 it("releases historical search targets when the list closes", async () => {
384 NodeV8.setFlagsFromString("--expose-gc");
385 const gc = NodeVM.runInNewContext("gc") as () => void;
386 const listings = createMergedIssueListAtoms(
387 { list: () => Atom.make(AsyncResult.success(answer)), refreshList: () => {} },
388 String,
389 );
390 const registry = AtomRegistry.make();
391 const environmentId = EnvironmentId.make("environment");
392 try {
393 const historical = ["search-one", "search-two", "search-three"].map((query) => {
394 const targets = [
395 { environmentId, input: { state: "open", query } },
396 ] satisfies IssueListTarget[];
397 const close = registry.mount(listings.atom(targets));
398 close();
399 return new WeakRef(targets);
400 });
401 // Let the registry remove all three unmounted queries and the WeakRefs leave their creation job.
402 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
403 await NodeTimersPromises.setImmediate();
404 gc();
405
406 listings.refreshEnvironment(registry, environmentId);
407 expect(
408 historical.filter((target) => target.deref() !== undefined).length,
409 "historical issue searches retained after closing",
410 ).toBe(0);
411 } finally {
412 registry.dispose();
413 }
414 });
415});
416
417describe("createIssueEnvironmentAtoms", () => {
418 it.effect("reuses a fresh listing for the same labels selected in a different order", () =>
419 Effect.scoped(
420 Effect.gen(function* () {
421 const environmentId = EnvironmentId.make("env");
422 const target = new PrimaryConnectionTarget({
423 environmentId,
424 label: "Test environment",
425 httpBaseUrl: "https://issues.example.test",
426 wsBaseUrl: "wss://issues.example.test",
427 });
428 const answer: IssueListResult = {
429 viewers: { "github.com": "octocat" },
430 entries: [entry({ key: "1" })],
431 trackers: [],
432 nextCursors: {},
433 errors: [],
434 };
435 let reads = 0;
436 const client = {
437 [WS_METHODS.issuesList]: () =>
438 Effect.sync(() => {
439 reads += 1;
440 return answer;
441 }),
442 };
443 const supervisor = EnvironmentSupervisor.of({
444 target,
445 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
446 ...AVAILABLE_CONNECTION_STATE,
447 phase: "connected",
448 network: "online",
449 desired: true,
450 generation: 1,
451 }),
452 session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)),
453 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
454 connect: Effect.void,
455 disconnect: Effect.void,
456 retryNow: Effect.void,
457 });
458 const environment = EnvironmentRegistry.of({
459 run: (_id, effect) => Effect.provideService(effect, EnvironmentSupervisor, supervisor),
460 followStream: (_id, stream) =>
461 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
462 } as Pick<
463 EnvironmentRegistry["Service"],
464 "run" | "followStream"
465 > as EnvironmentRegistry["Service"]);
466 const runtime = Atom.runtime(Layer.succeed(EnvironmentRegistry, environment));
467 const { list } = createIssueEnvironmentAtoms(runtime);
468 const registry = AtomRegistry.make();
469 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
470 for (const labels of [
471 ["bug", "p1"],
472 ["p1", "bug"],
473 ]) {
474 const atom = list({ environmentId, input: { state: "open", labels } });
475 yield* Effect.acquireRelease(
476 Effect.sync(() => registry.mount(atom)),
477 (unmount) => Effect.sync(unmount),
478 ).pipe(
479 Effect.andThen(AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true })),
480 Effect.scoped,
481 );
482 }
483 expect(reads, "issue searches for the same selected labels").toBe(1);
484 }),
485 ),
486 );
487});