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