Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import {
3 EnvironmentId,
4 ProjectId,
5 type PullRequestListEntry,
6 type PullRequestListInput,
7 PullRequestUnavailableError,
8 PullRequestOperationError,
9 type PullRequestListResult,
10 type PullRequestSummary,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Effect from "effect/Effect";
14import { AsyncResult, Atom } from "effect/reactivity";
15import { describe, expect, it, vi } from "vite-plus/test";
16
17const listAnswers = vi.hoisted(() => new Map<string, unknown>());
18const registry = await vi.hoisted(async () =>
19 (await import("effect/reactivity")).AtomRegistry.make(),
20);
21
22vi.mock("@effect/atom-react", async (importOriginal) => ({
23 ...(await importOriginal<typeof import("@effect/atom-react")>()),
24 useAtomValue: (atom: Atom.Atom<unknown>) => registry.get(atom),
25}));
26vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: registry }));
27vi.mock("@t3tools/client-runtime/state/pull-requests", async (importOriginal) => {
28 const actual =
29 await importOriginal<typeof import("@t3tools/client-runtime/state/pull-requests")>();
30 return {
31 ...actual,
32 createPullRequestEnvironmentAtoms: (
33 ...args: Parameters<typeof actual.createPullRequestEnvironmentAtoms>
34 ) => ({
35 ...actual.createPullRequestEnvironmentAtoms(...args),
36 list: ({ environmentId }: { readonly environmentId: string }) =>
37 listAnswers.get(environmentId),
38 }),
39 };
40});
41
42import {
43 newestPullRequestObservation,
44 observedPullRequestSummary,
45 observePullRequestChecks,
46 observePullRequestMetadata,
47 newestPullRequestSummary,
48 newestDisplayedPullRequestSummary,
49 rememberPullRequestListAnswer,
50 restorePullRequestList,
51 restoredPullRequestList,
52 threadPullRequestLinkToSummary,
53 observeFailedPullRequestList,
54 usePullRequestList,
55} from "./pullRequests";
56
57it("observes both typed list failures without changing their status or replaying cached timestamps", () => {
58 const listResult: PullRequestListResult = {
59 viewers: {},
60 providers: [],
61 entries: [],
62 errors: [],
63 truncated: false,
64 nextCursors: {},
65 };
66 using clock = vi.spyOn(Date, "now").mockReturnValue(100);
67 for (const error of [
68 new PullRequestUnavailableError({ reason: "cli-unauthenticated", listResult }),
69 new PullRequestOperationError({ operation: "list", detail: "HTTP 403", listResult }),
70 ]) {
71 clock.mockReturnValue(100);
72 const failure = AsyncResult.failure<PullRequestListResult, unknown>(Cause.fail(error));
73 expect(observeFailedPullRequestList(failure)).toEqual({ value: listResult, observedAt: 100 });
74 clock.mockReturnValue(200);
75 expect(observeFailedPullRequestList(failure)?.observedAt).toBe(100);
76 expect(failure._tag).toBe("Failure");
77 expect(observeFailedPullRequestList({ ...failure, waiting: true })).toBeUndefined();
78 }
79 expect(
80 observeFailedPullRequestList(
81 AsyncResult.failure(Cause.fail(new PullRequestUnavailableError({ reason: "cli-missing" }))),
82 ),
83 ).toBeUndefined();
84});
85
86function summary(overrides: Partial<PullRequestSummary> = {}): PullRequestSummary {
87 return {
88 provider: SourceControlProviderKind.make("github"),
89 projectId: ProjectId.make("pull-request-cache-test"),
90 repository: "acme/widget",
91 number: 7,
92 title: "Improve widget",
93 url: "https://github.com/acme/widget/pull/7",
94 state: "open",
95 isDraft: false,
96 headBranch: "improve-widget",
97 baseBranch: "main",
98 updatedAt: "2026-09-10T00:00:00Z",
99 author: { login: "oliver", name: null, avatarUrl: null },
100 mergeability: "mergeable",
101 checksState: "passing",
102 ...overrides,
103 };
104}
105
106const observed = (value: PullRequestSummary, observedAt: number) => ({
107 summary: value,
108 observedAt,
109});
110
111describe("pull request summary cache", () => {
112 it("orders same-dated snapshots by the server's read time, not by arrival", () => {
113 const stale = observed(summary({ observedAt: 200 }), 500);
114 const held = observed(
115 summary({ mergeability: "conflicting", checksState: "failing", observedAt: 300 }),
116 100,
117 );
118 expect(newestPullRequestObservation(stale, held)?.summary).toMatchObject({
119 mergeability: "conflicting",
120 checksState: "failing",
121 observedAt: 300,
122 });
123 expect(newestPullRequestObservation(held, stale)).toBe(held);
124 expect(newestPullRequestObservation(held, { ...held, observedAt: 900 })).toBe(held);
125 });
126
127 it("uses arrival order only when neither snapshot carries a server read time", () => {
128 const first = observed(summary(), 100);
129 const later = observed(summary({ checksState: "failing" }), 200);
130 expect(newestPullRequestObservation(first, later)).toMatchObject({ observedAt: 200 });
131 expect(newestPullRequestObservation(later, first)).toBe(later);
132 const stamped = observed(summary({ observedAt: 50 }), 1);
133 expect(newestPullRequestObservation(later, stamped)?.summary.observedAt).toBe(50);
134 expect(newestPullRequestObservation(stamped, later)).toBe(stamped);
135 });
136
137 it("keeps known status when a newer snapshot omits it, and clears it when told to", () => {
138 const list = observed(summary({ reviewDecision: "approved", observedAt: 100 }), 100);
139 const sparse = observed(
140 summary({ checksState: undefined, reviewDecision: undefined, observedAt: 200 }),
141 200,
142 );
143 expect(newestPullRequestObservation(list, sparse)?.summary).toMatchObject({
144 checksState: "passing",
145 reviewDecision: "approved",
146 });
147 const cleared = observed(summary({ checksState: null, observedAt: 300 }), 300);
148 expect(newestPullRequestObservation(list, cleared)?.summary.checksState).toBeNull();
149 });
150
151 it("treats merged as final and otherwise prefers the later host update", () => {
152 const merged = summary({ state: "merged", updatedAt: "2026-09-01T00:00:00Z" });
153 const reopened = summary({ updatedAt: "2026-09-12T00:00:00Z", observedAt: 900 });
154 expect(newestPullRequestSummary(merged, reopened)).toBe(merged);
155 expect(newestPullRequestSummary(reopened, merged)).toBe(merged);
156 const older = summary({ updatedAt: "2026-09-11T00:00:00Z", observedAt: 999 });
157 expect(newestPullRequestSummary(older, reopened)).toBe(reopened);
158 expect(newestPullRequestSummary(reopened, older)).toBe(reopened);
159 const edited = summary({ title: "Accepted title" });
160 expect(newestPullRequestSummary(summary(), edited)).toBe(edited);
161 const loaded = summary();
162 expect(newestDisplayedPullRequestSummary(loaded, false, edited, loaded, [])).toBe(loaded);
163 expect(newestDisplayedPullRequestSummary(summary(), true, edited, loaded, [])).toBe(edited);
164 const titleEdit = { reference: loaded, title: "Pending title" };
165 expect(newestDisplayedPullRequestSummary(loaded, true, null, loaded, [titleEdit])?.title).toBe(
166 "Pending title",
167 );
168 });
169
170 it("reuses saved thread state while detail is stale and lets newer detail replace it", () => {
171 const stale = summary();
172 const link = {
173 host: "github.com",
174 repository: stale.repository,
175 number: stale.number,
176 url: stale.url,
177 source: "manual" as const,
178 linkedAt: stale.updatedAt,
179 stack: null,
180 snapshot: {
181 ...stale,
182 state: "closed" as const,
183 isDraft: false,
184 updatedAt: "2026-09-11T00:00:00Z",
185 syncedAt: "2026-09-12T00:00:00Z",
186 },
187 };
188 const saved = threadPullRequestLinkToSummary(link, stale.projectId);
189 expect(newestPullRequestSummary(stale, saved)?.state).toBe("closed");
190 const fresh = summary({ isDraft: true, updatedAt: "2026-09-13T00:00:00Z" });
191 expect(newestPullRequestSummary(fresh, saved)).toBe(fresh);
192 expect(threadPullRequestLinkToSummary({ ...link, snapshot: null }, stale.projectId)).toBeNull();
193 expect(
194 threadPullRequestLinkToSummary(
195 { ...link, snapshot: { ...link.snapshot, updatedAt: null } },
196 stale.projectId,
197 ),
198 ).toBeNull();
199 });
200});
201
202describe("pull request observations", () => {
203 const fromSummary = (value: PullRequestSummary, observedAt: number) =>
204 observePullRequestMetadata({ metadata: null, checks: null }, observed(value, observedAt));
205 const checksRead = (
206 checksState: "passing" | "failing" | "pending" | null,
207 readAt: number | undefined,
208 observedAt: number,
209 ) => ({ checksState, readAt, observedAt });
210
211 it("keeps a newer list's mergeability when a checks read lands after it", () => {
212 const detail = summary({
213 mergeability: "conflicting",
214 checksState: "pending",
215 observedAt: 100,
216 });
217 let state = fromSummary(detail, 1);
218 state = observePullRequestMetadata(
219 state,
220 observed(summary({ mergeability: "mergeable", checksState: "pending", observedAt: 200 }), 2),
221 );
222 state = observePullRequestChecks(state, checksRead("passing", 300, 3));
223 expect(observedPullRequestSummary(state)).toMatchObject({
224 mergeability: "mergeable",
225 checksState: "passing",
226 });
227 });
228
229 it("keeps a newer checks read when an older list read lands after it", () => {
230 let state = fromSummary(
231 summary({ mergeability: "conflicting", checksState: "pending", observedAt: 100 }),
232 1,
233 );
234 state = observePullRequestChecks(state, checksRead("passing", 300, 2));
235 state = observePullRequestMetadata(
236 state,
237 observed(summary({ mergeability: "mergeable", checksState: "pending", observedAt: 250 }), 3),
238 );
239 expect(observedPullRequestSummary(state)).toMatchObject({
240 mergeability: "mergeable",
241 checksState: "passing",
242 });
243 });
244
245 it("lets a newer read's checks replace an older checks read", () => {
246 let state = fromSummary(summary({ checksState: "pending", observedAt: 100 }), 1);
247 state = observePullRequestChecks(state, checksRead("passing", 300, 2));
248 state = observePullRequestMetadata(
249 state,
250 observed(summary({ checksState: "failing", observedAt: 400 }), 3),
251 );
252 expect(observedPullRequestSummary(state)?.checksState).toBe("failing");
253 });
254
255 it("orders checks by arrival when the server reports no read time", () => {
256 let state = fromSummary(summary({ checksState: "pending" }), 1);
257 state = observePullRequestChecks(state, checksRead("passing", undefined, 2));
258 expect(observedPullRequestSummary(state)?.checksState).toBe("passing");
259 state = observePullRequestChecks(state, checksRead("failing", undefined, 1));
260 expect(observedPullRequestSummary(state)?.checksState).toBe("passing");
261 });
262
263 it("keeps the summary object when a checks reread changes no state", () => {
264 let state = fromSummary(summary({ checksState: "pending", observedAt: 100 }), 1);
265 state = observePullRequestChecks(state, checksRead("passing", 300, 2));
266 const shown = observedPullRequestSummary(state);
267 state = observePullRequestChecks(state, checksRead("passing", 300, 3));
268 expect(observedPullRequestSummary(state)).toBe(shown);
269 state = observePullRequestChecks(state, checksRead("failing", 400, 4));
270 expect(observedPullRequestSummary(state)?.checksState).toBe("failing");
271 });
272
273 it("shows nothing until some read has described the pull request", () => {
274 const state = observePullRequestChecks(
275 { metadata: null, checks: null },
276 checksRead("failing", 1, 1),
277 );
278 expect(observedPullRequestSummary(state)).toBeNull();
279 });
280});
281
282describe("pull request list answers across a reload", () => {
283 const makeStorage = () => {
284 const held = new Map<string, string>();
285 return {
286 held,
287 getItem: (key: string) => held.get(key) ?? null,
288 setItem: (key: string, value: string) => void held.set(key, value),
289 removeItem: (key: string) => void held.delete(key),
290 key: (index: number) => [...held.keys()][index] ?? null,
291 get length() {
292 return held.size;
293 },
294 };
295 };
296 const listEntry = (number: number, updatedAt = "2026-07-02T00:00:00Z") =>
297 ({
298 provider: SourceControlProviderKind.make("github"),
299 host: "github.com",
300 projectId: ProjectId.make("project-1"),
301 projectTitle: "t3code",
302 repository: "pingdotgg/t3code",
303 number,
304 title: `Pull request ${number}`,
305 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
306 author: { login: "octocat", name: null, avatarUrl: null },
307 headBranch: `feat/branch-${number}`,
308 baseBranch: "main",
309 state: "open",
310 isDraft: false,
311 mergeability: "mergeable",
312 additions: 1,
313 deletions: 0,
314 createdAt: "2026-07-01T00:00:00Z",
315 updatedAt,
316 viewerReviewRequested: false,
317 labels: [],
318 }) as PullRequestListEntry;
319 const answer = (entries: ReadonlyArray<PullRequestListEntry>, host = "github.com") =>
320 ({
321 entries,
322 viewers: { [host]: "Bilal" },
323 providers: [
324 {
325 host,
326 kind: SourceControlProviderKind.make("github"),
327 searchesOnHost: true,
328 projectCount: 1,
329 configured: true,
330 detail: null,
331 },
332 ],
333 errors: [{ projectId: ProjectId.make("project-1"), projectTitle: "t3code", message: "boom" }],
334 truncated: true,
335 nextCursors: { "pingdotgg/t3code": "cursor-1" },
336 }) as PullRequestListResult;
337 const local = EnvironmentId.make("env-local");
338 const remote = EnvironmentId.make("env-remote");
339 const input: PullRequestListInput = { state: "open", involvement: "all", limit: 99 };
340
341 it("restores every environment's first page as one merged list without stale failures or cursors", () => {
342 const storage = makeStorage();
343 rememberPullRequestListAnswer(
344 storage,
345 { environmentId: local, input },
346 answer([listEntry(1, "2026-07-01T00:00:00Z")]),
347 );
348 rememberPullRequestListAnswer(
349 storage,
350 { environmentId: remote, input },
351 answer([listEntry(2, "2026-07-03T00:00:00Z")], "gitlab.com"),
352 );
353 const restored = restorePullRequestList(storage, [
354 { environmentId: local, input },
355 { environmentId: remote, input },
356 ]);
357 expect(restored?.entries.map((row) => [row.environmentId, row.number])).toEqual([
358 [remote, 2],
359 [local, 1],
360 ]);
361 expect(restored?.viewers).toEqual({
362 "env-local github.com": "Bilal",
363 "env-remote gitlab.com": "Bilal",
364 });
365 expect(restored?.providers.map((provider) => provider.host)).toEqual([
366 "github.com",
367 "gitlab.com",
368 ]);
369 expect(restored?.errors).toEqual([]);
370 expect(restored?.nextCursors).toEqual({});
371 });
372
373 it("falls back to a fresh read when the browser blocks storage", () => {
374 vi.stubGlobal("window", {
375 get localStorage(): Storage {
376 throw new DOMException("The operation is insecure.", "SecurityError");
377 },
378 });
379 try {
380 expect(restoredPullRequestList([{ environmentId: local, input }])).toBeNull();
381 } finally {
382 vi.unstubAllGlobals();
383 }
384 });
385
386 it("keeps a page of rows and only first-page reads", () => {
387 const storage = makeStorage();
388 const rows = Array.from({ length: 120 }, (_, index) => listEntry(index + 1));
389 rememberPullRequestListAnswer(storage, { environmentId: local, input }, answer(rows));
390 const searched = { ...input, query: "fix" };
391 rememberPullRequestListAnswer(storage, { environmentId: local, input: searched }, answer(rows));
392 const continued = { ...input, cursors: { "pingdotgg/t3code": "cursor-1" } };
393 rememberPullRequestListAnswer(
394 storage,
395 { environmentId: local, input: continued },
396 answer(rows),
397 );
398 expect(
399 restorePullRequestList(storage, [{ environmentId: local, input }])?.entries,
400 ).toHaveLength(99);
401 expect(restorePullRequestList(storage, [{ environmentId: local, input: searched }])).toBeNull();
402 expect(
403 restorePullRequestList(storage, [{ environmentId: local, input: continued }]),
404 ).toBeNull();
405 });
406
407 it("restores answers kept under a project assignment for a cold start that has none yet", () => {
408 const storage = makeStorage();
409 rememberPullRequestListAnswer(
410 storage,
411 {
412 environmentId: local,
413 input: { ...input, projectIds: [ProjectId.make("project-1")] },
414 },
415 answer([listEntry(1)]),
416 );
417 rememberPullRequestListAnswer(
418 storage,
419 {
420 environmentId: remote,
421 input: { ...input, projectIds: [ProjectId.make("project-2")] },
422 },
423 answer([listEntry(2, "2026-07-03T00:00:00Z")]),
424 );
425 const restored = restorePullRequestList(storage, [
426 { environmentId: local, input },
427 { environmentId: remote, input },
428 ]);
429 expect(restored?.entries.map((row) => [row.environmentId, row.number])).toEqual([
430 [remote, 2],
431 [local, 1],
432 ]);
433 });
434
435 it("shows a pull request once when answers from before a reassignment overlap", () => {
436 const storage = makeStorage();
437 rememberPullRequestListAnswer(
438 storage,
439 { environmentId: local, input },
440 answer([listEntry(1, "2026-07-01T00:00:00Z")]),
441 );
442 rememberPullRequestListAnswer(
443 storage,
444 { environmentId: remote, input },
445 answer([listEntry(1, "2026-07-03T00:00:00Z")]),
446 );
447 const restored = restorePullRequestList(storage, [
448 { environmentId: local, input },
449 { environmentId: remote, input },
450 ]);
451 expect(restored?.entries.map((row) => [row.environmentId, row.updatedAt])).toEqual([
452 [local, "2026-07-01T00:00:00Z"],
453 ]);
454 });
455
456 it("keeps a shared repository's rows when it moves to an environment that has not answered yet", () => {
457 const storage = makeStorage();
458 const own = ProjectId.make("project-own");
459 const shared = { ...listEntry(2), projectId: ProjectId.make("project-shared") };
460 rememberPullRequestListAnswer(
461 storage,
462 { environmentId: local, input },
463 answer([{ ...listEntry(1), projectId: own }, shared]),
464 );
465 rememberPullRequestListAnswer(
466 storage,
467 { environmentId: remote, input },
468 answer([listEntry(3, "2026-07-03T00:00:00Z")]),
469 );
470 // The shared repository now belongs to the remote environment, which has not answered yet.
471 rememberPullRequestListAnswer(
472 storage,
473 { environmentId: local, input: { ...input, projectIds: [own] } },
474 answer([{ ...listEntry(1), projectId: own }]),
475 );
476 const restored = restorePullRequestList(storage, [
477 { environmentId: local, input },
478 { environmentId: remote, input },
479 ]);
480 expect(restored?.entries.map((row) => row.number).toSorted()).toEqual([1, 2, 3]);
481 });
482
483 it("keeps one page per environment when retained rows join a partial answer", () => {
484 const storage = makeStorage();
485 const own = ProjectId.make("project-own");
486 const shared = ProjectId.make("project-shared");
487 const rows = (projectId: ProjectId, first: number) =>
488 Array.from({ length: 99 }, (_, index) => ({ ...listEntry(first + index), projectId }));
489 rememberPullRequestListAnswer(
490 storage,
491 { environmentId: local, input },
492 answer(rows(shared, 1)),
493 );
494 rememberPullRequestListAnswer(
495 storage,
496 { environmentId: local, input: { ...input, projectIds: [own] } },
497 answer(rows(own, 101)),
498 );
499 const restored = restorePullRequestList(storage, [{ environmentId: local, input }]);
500 expect(restored?.entries).toHaveLength(99);
501 expect(restored?.entries.every((row) => row.projectId === own)).toBe(true);
502 });
503
504 it("does not keep grown pages", () => {
505 const storage = makeStorage();
506 const grown = { ...input, limit: 198 };
507 rememberPullRequestListAnswer(storage, { environmentId: local, input: grown }, answer([]));
508 expect(restorePullRequestList(storage, [{ environmentId: local, input: grown }])).toBeNull();
509 });
510
511 it("forgets whole scopes, never one environment of a scope that is kept", () => {
512 const storage = makeStorage();
513 const scoped = (projectIndex: number) => ({
514 ...input,
515 projectId: ProjectId.make(`p-${projectIndex}`),
516 });
517 for (let projectIndex = 0; projectIndex < 9; projectIndex++) {
518 for (const [offset, environmentId] of [local, remote].entries()) {
519 rememberPullRequestListAnswer(
520 storage,
521 { environmentId, input: scoped(projectIndex) },
522 answer([listEntry(projectIndex * 2 + offset + 1, `2026-07-0${2 - offset}T00:00:00Z`)]),
523 );
524 }
525 }
526 const restore = (projectIndex: number) =>
527 restorePullRequestList(storage, [
528 { environmentId: local, input: scoped(projectIndex) },
529 { environmentId: remote, input: scoped(projectIndex) },
530 ]);
531 expect(restore(0)).toBeNull();
532 for (let projectIndex = 1; projectIndex < 9; projectIndex++) {
533 expect(restore(projectIndex)?.entries.map((row) => row.environmentId)).toEqual([
534 local,
535 remote,
536 ]);
537 }
538 });
539
540 it("names the environment whose list failed while the others' rows still show", () => {
541 listAnswers.set(local, Atom.make(AsyncResult.success(answer([listEntry(1)]))));
542 listAnswers.set(
543 remote,
544 Atom.make(
545 AsyncResult.failure(
546 Cause.fail(
547 new Error("Relay could not reach the environment endpoint (endpoint_request_failed)."),
548 ),
549 ),
550 ),
551 );
552
553 const view = usePullRequestList([
554 { environmentId: local, input },
555 { environmentId: remote, input },
556 ]);
557
558 expect(view.data?.entries.map((row) => [row.environmentId, row.number])).toEqual([[local, 1]]);
559 expect(view.error).toEqual({
560 environmentId: remote,
561 message: "Relay could not reach the environment endpoint (endpoint_request_failed).",
562 });
563 });
564
565 it("retries only the environment whose list failed, leaving one still loading to finish", () => {
566 const requests: string[] = [];
567 const read = (environmentId: string, answer: Effect.Effect<never, string>) =>
568 Atom.make(
569 Effect.suspend(() => {
570 requests.push(environmentId);
571 return answer;
572 }),
573 );
574 const slow = EnvironmentId.make("env-slow");
575 const failing = EnvironmentId.make("env-failing");
576 const reads = [read(slow, Effect.never), read(failing, Effect.fail("Unreachable"))];
577 listAnswers.set(slow, reads[0]);
578 listAnswers.set(failing, reads[1]);
579 const unmounts = reads.map((atom) => registry.mount(atom));
580 try {
581 const view = usePullRequestList([
582 { environmentId: slow, input },
583 { environmentId: failing, input },
584 ]);
585 expect(view).toMatchObject({ isPending: true, error: { environmentId: failing } });
586
587 view.retry();
588
589 expect(requests).toEqual([slow, failing, failing]);
590 } finally {
591 for (const unmount of unmounts) unmount();
592 }
593 });
594
595 it("removes the composite snapshots it replaced", () => {
596 const storage = makeStorage();
597 storage.held.set("t3.pullRequests.list:env-local,env-remote", "{}");
598 storage.held.set("t3.pullRequests.list:env-local", "{}");
599 storage.held.set("t3.other", "kept");
600 rememberPullRequestListAnswer(storage, { environmentId: local, input }, answer([]));
601 expect(
602 [...storage.held.keys()].filter((key) => key.startsWith("t3.pullRequests.list:")),
603 ).toEqual([]);
604 expect(storage.held.get("t3.other")).toBe("kept");
605 });
606});