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