@devries-cameron20 / t3code-1 / commits / 071239804e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(web): pull request list remembers each answer for the next start (#25364)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 04:11 UTC 071239804e375078dd3fae3b14704b4def57e048
5 files changed +459 -208
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+14 -37
@@ -29,8 +29,6 @@ import {
29 pullRequestDiffStatKey,
30 pullRequestEntryKey,
31 rankPullRequestMatches,
32 - readPullRequestListSnapshot,
33 - writePullRequestListSnapshot,
32 pullRequestStatsRefreshBatches,
33 pullRequestStatsRequestBatches,
34 retainVisiblePullRequestStatsBatches,
@@ -103,6 +101,7 @@ import {
101 pullRequestEnvironment,
102 usePullRequestList,
103 usePullRequestListStats,
104 + restoredPullRequestList,
105 usePullRequestTurnRefreshes,
106 useSharedPullRequestSummary,
107 type EnvironmentQueryTarget,
@@ -450,20 +449,25 @@ export function PullRequestsPage() {
449 if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
450 setSnapshotEnvironmentKey(environmentKey);
451 if (loaded?.environmentKey !== environmentKey) {
453 - const snapshot = readPullRequestListSnapshot(
454 - typeof window === "undefined" ? undefined : window.localStorage,
455 - environmentKey,
456 - );
452 + const restored = restoredPullRequestList(baselineTargets);
453 + const restoredPartition = (involvement: PullRequestInvolvement) =>
454 + restoredPullRequestList(
455 + baselineTargets.map((target) => ({ ...target, input: { ...target.input, involvement } })),
456 + )?.entries;
457 + const authored = partitionsWanted ? restoredPartition("authored") : undefined;
458 + const reviewing = partitionsWanted ? restoredPartition("reviewing") : undefined;
459 setLoaded(
458 - snapshot === null
460 + restored === null
461 ? null
462 : {
463 environmentKey,
462 - scope: snapshot.scope,
464 + scope: scopeKey,
465 query: "",
466 source: null,
465 - data: snapshot.data,
466 - ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
467 + data: restored,
468 + ...(authored === undefined || reviewing === undefined
469 + ? {}
470 + : { partitions: { authored, reviewing } }),
471 },
472 );
473 }
@@ -507,33 +511,6 @@ export function PullRequestsPage() {
511 ...(nextPartitions === undefined ? {} : { partitions: nextPartitions }),
512 });
513 }
510 - const snapshotToWrite =
511 - loaded !== null &&
512 - loaded.source !== null &&
513 - loaded.environmentKey.length > 0 &&
514 - loaded.query.length === 0
515 - ? loaded
516 - : null;
517 - const snapshotViewers = baselineQuery.data?.viewers;
518 - const snapshotProviders = baselineQuery.data?.providers;
519 - useEffect(() => {
520 - if (snapshotToWrite === null) return;
521 - writePullRequestListSnapshot(
522 - typeof window === "undefined" ? undefined : window.localStorage,
523 - snapshotToWrite.environmentKey,
524 - {
525 - scope: snapshotToWrite.scope,
526 - data: {
527 - ...snapshotToWrite.data,
528 - viewers: snapshotViewers ?? snapshotToWrite.data.viewers,
529 - providers: snapshotProviders ?? snapshotToWrite.data.providers,
530 - },
531 - ...(snapshotToWrite.partitions === undefined
532 - ? {}
533 - : { partitions: snapshotToWrite.partitions }),
534 - },
535 - );
536 - }, [snapshotToWrite, snapshotViewers, snapshotProviders]);
514 const narrowed = (() => {
515 if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
516 return null;
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
-65
@@ -22,8 +22,6 @@ import {
22 pullRequestStatsRefreshBatches,
23 mergePullRequestDiffStats,
24 partitionPullRequestsWithPriority,
25 - readPullRequestListSnapshot,
26 - writePullRequestListSnapshot,
25 pullRequestAuthorChoices,
26 selectedPullRequestAuthor,
27 pullRequestLabelChoices,
@@ -350,69 +348,6 @@ describe("partitioning with the hosts' own priority reads", () => {
348 });
349 });
350
353 -describe("the list snapshot across a reload", () => {
354 - const makeStorage = () => {
355 - const held = new Map<string, string>();
356 - return {
357 - getItem: (key: string) => held.get(key) ?? null,
358 - setItem: (key: string, value: string) => void held.set(key, value),
359 - };
360 - };
361 - const data = {
362 - entries: [entry({ number: 1 })],
363 - viewers: { "github.com": "Bilal" },
364 - providers: [],
365 - errors: [{ projectId: "project-1", message: "boom" }],
366 - truncated: true,
367 - nextCursors: { "pingdotgg/t3code": "cursor-1" },
368 - } as never;
369 -
370 - it("carries neither stale failures nor stale cursors", () => {
371 - const storage = makeStorage();
372 - writePullRequestListSnapshot(storage, "env-1", { scope: "s", data });
373 - const snapshot = readPullRequestListSnapshot(storage, "env-1");
374 - expect(snapshot?.data.errors).toEqual([]);
375 - expect(snapshot?.data.nextCursors).toEqual({});
376 - });
377 -
378 - it("caps the accumulated rows but keeps the whole host set", () => {
379 - const storage = makeStorage();
380 - const manyEntries = Array.from({ length: 120 }, (_, index) => entry({ number: index + 1 }));
381 - const viewers = { "github.com": "Bilal", "gitlab.com": "Bilal" };
382 - const providers = [
383 - {
384 - host: "github.com",
385 - kind: "github",
386 - searchesOnHost: true,
387 - projectCount: 1,
388 - configured: true,
389 - detail: null,
390 - },
391 - {
392 - host: "gitlab.com",
393 - kind: "gitlab",
394 - searchesOnHost: true,
395 - projectCount: 1,
396 - configured: true,
397 - detail: null,
398 - },
399 - ];
400 - const accumulated = {
401 - entries: manyEntries,
402 - viewers,
403 - providers,
404 - errors: [],
405 - truncated: true,
406 - nextCursors: {},
407 - } as never;
408 - writePullRequestListSnapshot(storage, "env-1", { scope: "s", data: accumulated });
409 - const snapshot = readPullRequestListSnapshot(storage, "env-1");
410 - expect(snapshot?.data.entries).toHaveLength(99);
411 - expect(snapshot?.data.viewers).toEqual(viewers);
412 - expect(snapshot?.data.providers).toEqual(providers);
413 - });
414 -});
415 -
351 describe("remembered pull request list controls", () => {
352 const makeStorage = () => {
353 const held = new Map<string, string>();
apps/web/src/components/pullRequest/pullRequestList.logic.ts
+2 -91
@@ -1,14 +1,11 @@
1 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2 -import * as Schema from "effect/Schema";
2
4 -import {
3 +import { resolvePullRequestAuthorFilter } from "@t3tools/contracts";
4 +import type {
5 EnvironmentId,
6 PullRequestListEntry,
7 PullRequestListProjectError,
8 PullRequestListResult,
9 - resolvePullRequestAuthorFilter,
10 -} from "@t3tools/contracts";
11 -import type {
9 ProjectId,
10 RepositoryIdentity,
11 PullRequestAction,
@@ -575,100 +572,14 @@ export function mergePullRequestLists(
572 };
573 }
574
578 -const SNAPSHOT_MAX_ENTRIES = 99;
579 -
580 -type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
581 -
575 export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
576 [...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
577
585 -const snapshotStorageKey = (environmentSetKey: string) =>
586 - `t3.pullRequests.list:${environmentSetKey}`;
587 -
578 export interface PullRequestPartitionsSnapshot {
579 readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
580 readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
581 }
582
593 -export interface PullRequestListSnapshot {
594 - readonly scope: string;
595 - readonly data: MergedPullRequestList;
596 - readonly partitions?: PullRequestPartitionsSnapshot | undefined;
597 -}
598 -
599 -const EnvironmentPullRequestEntrySchema = Schema.Struct({
600 - ...PullRequestListEntry.fields,
601 - environmentId: EnvironmentId,
602 -});
603 -
604 -const EnvironmentPullRequestErrorSchema = Schema.Struct({
605 - ...PullRequestListProjectError.fields,
606 - environmentId: EnvironmentId,
607 -});
608 -
609 -const decodeSnapshot = Schema.decodeUnknownOption(
610 - Schema.Struct({
611 - scope: Schema.String,
612 - data: Schema.Struct({
613 - ...PullRequestListResult.fields,
614 - entries: Schema.Array(EnvironmentPullRequestEntrySchema),
615 - errors: Schema.Array(EnvironmentPullRequestErrorSchema),
616 - nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
617 - truncatedEnvironments: Schema.Array(Schema.String),
618 - }),
619 - partitions: Schema.optional(
620 - Schema.Struct({
621 - authored: Schema.Array(EnvironmentPullRequestEntrySchema),
622 - reviewing: Schema.Array(EnvironmentPullRequestEntrySchema),
623 - }),
624 - ),
625 - }),
626 -);
627 -
628 -export function readPullRequestListSnapshot(
629 - storage: SnapshotStorage | undefined,
630 - environmentSetKey: string,
631 -): PullRequestListSnapshot | null {
632 - try {
633 - const raw = storage?.getItem(snapshotStorageKey(environmentSetKey));
634 - if (!raw) return null;
635 - const decoded = decodeSnapshot(JSON.parse(raw));
636 - return decoded._tag === "Some" ? decoded.value : null;
637 - } catch {
638 - return null;
639 - }
640 -}
641 -
642 -export function writePullRequestListSnapshot(
643 - storage: SnapshotStorage | undefined,
644 - environmentSetKey: string,
645 - snapshot: PullRequestListSnapshot,
646 -): void {
647 - try {
648 - storage?.setItem(
649 - snapshotStorageKey(environmentSetKey),
650 - JSON.stringify({
651 - scope: snapshot.scope,
652 - data: {
653 - ...snapshot.data,
654 - entries: snapshot.data.entries.slice(0, SNAPSHOT_MAX_ENTRIES),
655 - errors: [],
656 - nextCursors: {},
657 - truncatedEnvironments: [],
658 - },
659 - ...(snapshot.partitions === undefined
660 - ? {}
661 - : {
662 - partitions: {
663 - authored: snapshot.partitions.authored.slice(0, SNAPSHOT_MAX_ENTRIES),
664 - reviewing: snapshot.partitions.reviewing.slice(0, SNAPSHOT_MAX_ENTRIES),
665 - },
666 - }),
667 - }),
668 - );
669 - } catch {}
670 -}
671 -
583 /** Retain project scope during reconnect until projects arrive. */
584 export function resolveProjectScope<Id extends string>(
585 projectId: Id | undefined,
apps/web/src/state/pullRequests.test.ts
+283 -2
@@ -1,6 +1,13 @@
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 -import { ProjectId, type PullRequestSummary } from "@t3tools/contracts";
3 -import { describe, expect, it } from "vite-plus/test";
2 +import {
3 + EnvironmentId,
4 + ProjectId,
5 + type PullRequestListEntry,
6 + type PullRequestListInput,
7 + type PullRequestListResult,
8 + type PullRequestSummary,
9 +} from "@t3tools/contracts";
10 +import { describe, expect, it, vi } from "vite-plus/test";
11
12 import {
13 newestPullRequestObservation,
@@ -8,6 +15,9 @@ import {
15 observePullRequestChecks,
16 observePullRequestMetadata,
17 newestPullRequestSummary,
18 + rememberPullRequestListAnswer,
19 + restorePullRequestList,
20 + restoredPullRequestList,
21 threadPullRequestLinkToSummary,
22 } from "./pullRequests";
23
@@ -187,3 +197,274 @@ describe("pull request observations", () => {
197 expect(observedPullRequestSummary(state)).toBeNull();
198 });
199 });
200 +
201 +describe("pull request list answers across a reload", () => {
202 + const makeStorage = () => {
203 + const held = new Map<string, string>();
204 + return {
205 + held,
206 + getItem: (key: string) => held.get(key) ?? null,
207 + setItem: (key: string, value: string) => void held.set(key, value),
208 + removeItem: (key: string) => void held.delete(key),
209 + key: (index: number) => [...held.keys()][index] ?? null,
210 + get length() {
211 + return held.size;
212 + },
213 + };
214 + };
215 + const listEntry = (number: number, updatedAt = "2026-07-02T00:00:00Z") =>
216 + ({
217 + provider: SourceControlProviderKind.make("github"),
218 + host: "github.com",
219 + projectId: ProjectId.make("project-1"),
220 + projectTitle: "t3code",
221 + repository: "pingdotgg/t3code",
222 + number,
223 + title: `Pull request ${number}`,
224 + url: `https://github.com/pingdotgg/t3code/pull/${number}`,
225 + author: { login: "octocat", name: null, avatarUrl: null },
226 + headBranch: `feat/branch-${number}`,
227 + baseBranch: "main",
228 + state: "open",
229 + isDraft: false,
230 + mergeability: "mergeable",
231 + additions: 1,
232 + deletions: 0,
233 + createdAt: "2026-07-01T00:00:00Z",
234 + updatedAt,
235 + viewerReviewRequested: false,
236 + labels: [],
237 + }) as PullRequestListEntry;
238 + const answer = (entries: ReadonlyArray<PullRequestListEntry>, host = "github.com") =>
239 + ({
240 + entries,
241 + viewers: { [host]: "Bilal" },
242 + providers: [
243 + {
244 + host,
245 + kind: SourceControlProviderKind.make("github"),
246 + searchesOnHost: true,
247 + projectCount: 1,
248 + configured: true,
249 + detail: null,
250 + },
251 + ],
252 + errors: [{ projectId: ProjectId.make("project-1"), projectTitle: "t3code", message: "boom" }],
253 + truncated: true,
254 + nextCursors: { "pingdotgg/t3code": "cursor-1" },
255 + }) as PullRequestListResult;
256 + const local = EnvironmentId.make("env-local");
257 + const remote = EnvironmentId.make("env-remote");
258 + const input: PullRequestListInput = { state: "open", involvement: "all", limit: 99 };
259 +
260 + it("restores every environment's first page as one merged list without stale failures or cursors", () => {
261 + const storage = makeStorage();
262 + rememberPullRequestListAnswer(
263 + storage,
264 + { environmentId: local, input },
265 + answer([listEntry(1, "2026-07-01T00:00:00Z")]),
266 + );
267 + rememberPullRequestListAnswer(
268 + storage,
269 + { environmentId: remote, input },
270 + answer([listEntry(2, "2026-07-03T00:00:00Z")], "gitlab.com"),
271 + );
272 + const restored = restorePullRequestList(storage, [
273 + { environmentId: local, input },
274 + { environmentId: remote, input },
275 + ]);
276 + expect(restored?.entries.map((row) => [row.environmentId, row.number])).toEqual([
277 + [remote, 2],
278 + [local, 1],
279 + ]);
280 + expect(restored?.viewers).toEqual({
281 + "env-local github.com": "Bilal",
282 + "env-remote gitlab.com": "Bilal",
283 + });
284 + expect(restored?.providers.map((provider) => provider.host)).toEqual([
285 + "github.com",
286 + "gitlab.com",
287 + ]);
288 + expect(restored?.errors).toEqual([]);
289 + expect(restored?.nextCursors).toEqual({});
290 + });
291 +
292 + it("falls back to a fresh read when the browser blocks storage", () => {
293 + vi.stubGlobal("window", {
294 + get localStorage(): Storage {
295 + throw new DOMException("The operation is insecure.", "SecurityError");
296 + },
297 + });
298 + try {
299 + expect(restoredPullRequestList([{ environmentId: local, input }])).toBeNull();
300 + } finally {
301 + vi.unstubAllGlobals();
302 + }
303 + });
304 +
305 + it("keeps a page of rows and only first-page reads", () => {
306 + const storage = makeStorage();
307 + const rows = Array.from({ length: 120 }, (_, index) => listEntry(index + 1));
308 + rememberPullRequestListAnswer(storage, { environmentId: local, input }, answer(rows));
309 + const searched = { ...input, query: "fix" };
310 + rememberPullRequestListAnswer(storage, { environmentId: local, input: searched }, answer(rows));
311 + const continued = { ...input, cursors: { "pingdotgg/t3code": "cursor-1" } };
312 + rememberPullRequestListAnswer(
313 + storage,
314 + { environmentId: local, input: continued },
315 + answer(rows),
316 + );
317 + expect(
318 + restorePullRequestList(storage, [{ environmentId: local, input }])?.entries,
319 + ).toHaveLength(99);
320 + expect(restorePullRequestList(storage, [{ environmentId: local, input: searched }])).toBeNull();
321 + expect(
322 + restorePullRequestList(storage, [{ environmentId: local, input: continued }]),
323 + ).toBeNull();
324 + });
325 +
326 + it("restores answers kept under a project assignment for a cold start that has none yet", () => {
327 + const storage = makeStorage();
328 + rememberPullRequestListAnswer(
329 + storage,
330 + {
331 + environmentId: local,
332 + input: { ...input, projectIds: [ProjectId.make("project-1")] },
333 + },
334 + answer([listEntry(1)]),
335 + );
336 + rememberPullRequestListAnswer(
337 + storage,
338 + {
339 + environmentId: remote,
340 + input: { ...input, projectIds: [ProjectId.make("project-2")] },
341 + },
342 + answer([listEntry(2, "2026-07-03T00:00:00Z")]),
343 + );
344 + const restored = restorePullRequestList(storage, [
345 + { environmentId: local, input },
346 + { environmentId: remote, input },
347 + ]);
348 + expect(restored?.entries.map((row) => [row.environmentId, row.number])).toEqual([
349 + [remote, 2],
350 + [local, 1],
351 + ]);
352 + });
353 +
354 + it("shows a pull request once when answers from before a reassignment overlap", () => {
355 + const storage = makeStorage();
356 + rememberPullRequestListAnswer(
357 + storage,
358 + { environmentId: local, input },
359 + answer([listEntry(1, "2026-07-01T00:00:00Z")]),
360 + );
361 + rememberPullRequestListAnswer(
362 + storage,
363 + { environmentId: remote, input },
364 + answer([listEntry(1, "2026-07-03T00:00:00Z")]),
365 + );
366 + const restored = restorePullRequestList(storage, [
367 + { environmentId: local, input },
368 + { environmentId: remote, input },
369 + ]);
370 + expect(restored?.entries.map((row) => [row.environmentId, row.updatedAt])).toEqual([
371 + [remote, "2026-07-03T00:00:00Z"],
372 + ]);
373 + });
374 +
375 + it("keeps a shared repository's rows when it moves to an environment that has not answered yet", () => {
376 + const storage = makeStorage();
377 + const own = ProjectId.make("project-own");
378 + const shared = { ...listEntry(2), projectId: ProjectId.make("project-shared") };
379 + rememberPullRequestListAnswer(
380 + storage,
381 + { environmentId: local, input },
382 + answer([{ ...listEntry(1), projectId: own }, shared]),
383 + );
384 + rememberPullRequestListAnswer(
385 + storage,
386 + { environmentId: remote, input },
387 + answer([listEntry(3, "2026-07-03T00:00:00Z")]),
388 + );
389 + // The shared repository now belongs to the remote environment, which has not answered yet.
390 + rememberPullRequestListAnswer(
391 + storage,
392 + { environmentId: local, input: { ...input, projectIds: [own] } },
393 + answer([{ ...listEntry(1), projectId: own }]),
394 + );
395 + const restored = restorePullRequestList(storage, [
396 + { environmentId: local, input },
397 + { environmentId: remote, input },
398 + ]);
399 + expect(restored?.entries.map((row) => row.number).toSorted()).toEqual([1, 2, 3]);
400 + });
401 +
402 + it("keeps one page per environment when retained rows join a partial answer", () => {
403 + const storage = makeStorage();
404 + const own = ProjectId.make("project-own");
405 + const shared = ProjectId.make("project-shared");
406 + const rows = (projectId: ProjectId, first: number) =>
407 + Array.from({ length: 99 }, (_, index) => ({ ...listEntry(first + index), projectId }));
408 + rememberPullRequestListAnswer(
409 + storage,
410 + { environmentId: local, input },
411 + answer(rows(shared, 1)),
412 + );
413 + rememberPullRequestListAnswer(
414 + storage,
415 + { environmentId: local, input: { ...input, projectIds: [own] } },
416 + answer(rows(own, 101)),
417 + );
418 + const restored = restorePullRequestList(storage, [{ environmentId: local, input }]);
419 + expect(restored?.entries).toHaveLength(99);
420 + expect(restored?.entries.every((row) => row.projectId === own)).toBe(true);
421 + });
422 +
423 + it("does not keep grown pages", () => {
424 + const storage = makeStorage();
425 + const grown = { ...input, limit: 198 };
426 + rememberPullRequestListAnswer(storage, { environmentId: local, input: grown }, answer([]));
427 + expect(restorePullRequestList(storage, [{ environmentId: local, input: grown }])).toBeNull();
428 + });
429 +
430 + it("forgets whole scopes, never one environment of a scope that is kept", () => {
431 + const storage = makeStorage();
432 + const scoped = (projectIndex: number) => ({
433 + ...input,
434 + projectId: ProjectId.make(`p-${projectIndex}`),
435 + });
436 + for (let projectIndex = 0; projectIndex < 9; projectIndex++) {
437 + for (const [offset, environmentId] of [local, remote].entries()) {
438 + rememberPullRequestListAnswer(
439 + storage,
440 + { environmentId, input: scoped(projectIndex) },
441 + answer([listEntry(projectIndex * 2 + offset + 1, `2026-07-0${2 - offset}T00:00:00Z`)]),
442 + );
443 + }
444 + }
445 + const restore = (projectIndex: number) =>
446 + restorePullRequestList(storage, [
447 + { environmentId: local, input: scoped(projectIndex) },
448 + { environmentId: remote, input: scoped(projectIndex) },
449 + ]);
450 + expect(restore(0)).toBeNull();
451 + for (let projectIndex = 1; projectIndex < 9; projectIndex++) {
452 + expect(restore(projectIndex)?.entries.map((row) => row.environmentId)).toEqual([
453 + local,
454 + remote,
455 + ]);
456 + }
457 + });
458 +
459 + it("removes the composite snapshots it replaced", () => {
460 + const storage = makeStorage();
461 + storage.held.set("t3.pullRequests.list:env-local,env-remote", "{}");
462 + storage.held.set("t3.pullRequests.list:env-local", "{}");
463 + storage.held.set("t3.other", "kept");
464 + rememberPullRequestListAnswer(storage, { environmentId: local, input }, answer([]));
465 + expect(
466 + [...storage.held.keys()].filter((key) => key.startsWith("t3.pullRequests.list:")),
467 + ).toEqual([]);
468 + expect(storage.held.get("t3.other")).toBe("kept");
469 + });
470 +});
apps/web/src/state/pullRequests.ts
+160 -13
@@ -5,17 +5,18 @@ import {
5 createPullRequestEnvironmentAtoms,
6 createPullRequestStackAtomFamily,
7 } from "@t3tools/client-runtime/state/pull-requests";
8 -import type {
9 - EnvironmentId,
10 - ProjectId,
11 - PullRequestChecksState,
12 - PullRequestListInput,
13 - PullRequestFilterOptionsInput,
14 - PullRequestListStatsInput,
15 - PullRequestListEntry,
16 - PullRequestRef,
17 - PullRequestSummary,
18 - ThreadPullRequestLink,
8 +import {
9 + PullRequestListResult,
10 + type EnvironmentId,
11 + type ProjectId,
12 + type PullRequestChecksState,
13 + type PullRequestListInput,
14 + type PullRequestFilterOptionsInput,
15 + type PullRequestListStatsInput,
16 + type PullRequestListEntry,
17 + type PullRequestRef,
18 + type PullRequestSummary,
19 + type ThreadPullRequestLink,
20 } from "@t3tools/contracts";
21 import {
22 threadPullRequestKeyOf,
@@ -24,6 +25,7 @@ import {
25 import * as Clock from "effect/Clock";
26 import * as Effect from "effect/Effect";
27 import * as Option from "effect/Option";
28 +import * as Schema from "effect/Schema";
29 import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
30
31 import { connectionAtomRuntime } from "../connection/runtime";
@@ -215,14 +217,159 @@ function observePullRequestSummary(
217 );
218 }
219
220 +// Reading localStorage throws where the browser blocks storage; that must not break the page.
221 function snapshotStorage(): Storage | undefined {
219 - return typeof window === "undefined" ? undefined : window.localStorage;
222 + if (typeof window === "undefined") return undefined;
223 + try {
224 + return window.localStorage;
225 + } catch {
226 + return undefined;
227 + }
228 +}
229 +
230 +type ListAnswerStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
231 +
232 +const LIST_SCOPE_INDEX_KEY = "t3.pullRequests.listScopes";
233 +const LIST_SCOPE_KEY_PREFIX = "t3.pullRequests.listScope:";
234 +const LEGACY_SNAPSHOT_KEY_PREFIX = "t3.pullRequests.list:";
235 +const LIST_ANSWER_MAX_ENTRIES = 99;
236 +/**
237 + * A scope holds a page of rows per environment, so only the scopes visited most recently are
238 + * kept. Eviction drops a whole scope, never one environment's answer, so a restored list is never
239 + * missing environments that did answer.
240 + */
241 +const LIST_SCOPE_MAX_KEPT = 8;
242 +const listScopeCodec = Schema.fromJsonString(
243 + Schema.Record(Schema.String, Schema.toCodecJson(PullRequestListResult)),
244 +);
245 +const decodeListScope = Schema.decodeUnknownOption(listScopeCodec);
246 +const encodeListScope = Schema.encodeOption(listScopeCodec);
247 +const decodeListScopeIndex = Schema.decodeUnknownOption(
248 + Schema.fromJsonString(Schema.Array(Schema.String)),
249 +);
250 +const sweptStorages = new WeakSet<ListAnswerStorage>();
251 +
252 +/**
253 + * The project assignment is left out: a cold start asks before the project shells load, when
254 + * every environment is asked for all of its projects, while the answers were remembered after
255 + * overlapping projects were split between environments. Each environment's answer covers only
256 + * its assigned projects, so the scope's answers together still cover the whole scope.
257 + */
258 +const listScopeKey = ({ projectIds: _projectIds, ...scope }: PullRequestListInput) =>
259 + `${LIST_SCOPE_KEY_PREFIX}${JSON.stringify(scope)}`;
260 +
261 +function readListScope(storage: ListAnswerStorage | undefined, key: string) {
262 + let raw: string | null = null;
263 + try {
264 + raw = storage?.getItem(key) ?? null;
265 + } catch {}
266 + return Option.getOrElse(decodeListScope(raw), (): Record<string, PullRequestListResult> => ({}));
267 +}
268 +
269 +/** The single composite snapshot this replaced is never read again. */
270 +function sweepLegacySnapshots(storage: ListAnswerStorage): void {
271 + if (sweptStorages.has(storage)) return;
272 + sweptStorages.add(storage);
273 + const legacy: string[] = [];
274 + for (let index = 0; index < storage.length; index++) {
275 + const key = storage.key(index);
276 + if (key?.startsWith(LEGACY_SNAPSHOT_KEY_PREFIX)) legacy.push(key);
277 + }
278 + for (const key of legacy) storage.removeItem(key);
279 +}
280 +
281 +/**
282 + * Keeps what a cold start can show before the host answers again. Searches, continuation pages
283 + * and grown pages are never shown that way, so only first-page reads are kept. Failures and
284 + * cursors are dropped: they describe the moment of the read, and a restored list must not
285 + * continue from it.
286 + */
287 +export function rememberPullRequestListAnswer(
288 + storage: ListAnswerStorage | undefined,
289 + target: EnvironmentQueryTarget<PullRequestListInput>,
290 + answer: PullRequestListResult,
291 +): void {
292 + const { input } = target;
293 + if (storage === undefined || input.query !== undefined || input.cursors !== undefined) return;
294 + if (input.limit !== undefined && input.limit > LIST_ANSWER_MAX_ENTRIES) return;
295 + const key = listScopeKey(input);
296 + try {
297 + sweepLegacySnapshots(storage);
298 + const scope = readListScope(storage, key);
299 + // An answer for some projects replaces only their rows. A repository this environment no
300 + // longer owns stays covered until the environment that took it over answers; the next answer
301 + // for all of the environment's projects, which every cold start asks for, drops them.
302 + const assigned = input.projectIds === undefined ? undefined : new Set(input.projectIds);
303 + const retained =
304 + assigned === undefined
305 + ? []
306 + : (scope[target.environmentId]?.entries ?? []).filter(
307 + (entry) => !assigned.has(entry.projectId),
308 + );
309 + const encoded = encodeListScope({
310 + ...scope,
311 + [target.environmentId]: {
312 + ...answer,
313 + // The fresh rows come first, so retained rows only fill what is left of the page.
314 + entries: [...answer.entries, ...retained].slice(0, LIST_ANSWER_MAX_ENTRIES),
315 + errors: [],
316 + nextCursors: {},
317 + },
318 + });
319 + if (Option.isNone(encoded)) return;
320 + const index = Option.getOrElse(
321 + decodeListScopeIndex(storage.getItem(LIST_SCOPE_INDEX_KEY)),
322 + () => [],
323 + );
324 + const kept = [key, ...index.filter((held) => held !== key)];
325 + for (const evicted of kept.slice(LIST_SCOPE_MAX_KEPT)) storage.removeItem(evicted);
326 + storage.setItem(key, encoded.value);
327 + storage.setItem(LIST_SCOPE_INDEX_KEY, JSON.stringify(kept.slice(0, LIST_SCOPE_MAX_KEPT)));
328 + } catch {}
329 +}
330 +
331 +/**
332 + * The kept answers for these reads, merged the way live answers are. An environment without a
333 + * kept answer is left out rather than failing the restore: one whose projects were all assigned
334 + * to another environment was never asked, and its pull requests are in that environment's answer.
335 + */
336 +export function restorePullRequestList(
337 + storage: ListAnswerStorage | undefined,
338 + targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
339 +): MergedPullRequestList | null {
340 + const scopes = new Map<string, Record<string, PullRequestListResult>>();
341 + const answers: Array<readonly [EnvironmentId, PullRequestListResult]> = [];
342 + for (const target of targets) {
343 + const key = listScopeKey(target.input);
344 + const scope = scopes.get(key) ?? readListScope(storage, key);
345 + scopes.set(key, scope);
346 + const answer = scope[target.environmentId];
347 + if (answer !== undefined) answers.push([target.environmentId, answer]);
348 + }
349 + const merged = mergePullRequestLists(answers);
350 + if (merged === null) return null;
351 + // Answers kept before the projects were reassigned between environments can overlap.
352 + const seen = new Set<string>();
353 + const entries = merged.entries.filter((entry) => {
354 + const key = `${entry.host}:${entry.repository}#${entry.number}`;
355 + if (seen.has(key)) return false;
356 + seen.add(key);
357 + return true;
358 + });
359 + return { ...merged, entries };
360 +}
361 +
362 +export function restoredPullRequestList(
363 + targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
364 +): MergedPullRequestList | null {
365 + return restorePullRequestList(snapshotStorage(), targets);
366 }
367
368 // Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
369 export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
224 - list: ({ environmentId }, answer, registry) =>
370 + list: ({ environmentId, input }, answer, registry) =>
371 Effect.map(Clock.currentTimeMillis, (observedAt) => {
372 + rememberPullRequestListAnswer(snapshotStorage(), { environmentId, input }, answer);
373 for (const entry of answer.entries) {
374 observePullRequestSummary(
375 registry,