Skip to content
TypeScript

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

Julius Marminge071239804e37
diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
index 3c746721d0a..4ea00dbace6 100644
--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
@@ -29,8 +29,6 @@ import {
pullRequestDiffStatKey,
pullRequestEntryKey,
rankPullRequestMatches,
- readPullRequestListSnapshot,
- writePullRequestListSnapshot,
pullRequestStatsRefreshBatches,
pullRequestStatsRequestBatches,
retainVisiblePullRequestStatsBatches,
@@ -103,6 +101,7 @@ import {
pullRequestEnvironment,
usePullRequestList,
usePullRequestListStats,
+ restoredPullRequestList,
usePullRequestTurnRefreshes,
useSharedPullRequestSummary,
type EnvironmentQueryTarget,
@@ -450,20 +449,25 @@ export function PullRequestsPage() {
if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
setSnapshotEnvironmentKey(environmentKey);
if (loaded?.environmentKey !== environmentKey) {
- const snapshot = readPullRequestListSnapshot(
- typeof window === "undefined" ? undefined : window.localStorage,
- environmentKey,
- );
+ const restored = restoredPullRequestList(baselineTargets);
+ const restoredPartition = (involvement: PullRequestInvolvement) =>
+ restoredPullRequestList(
+ baselineTargets.map((target) => ({ ...target, input: { ...target.input, involvement } })),
+ )?.entries;
+ const authored = partitionsWanted ? restoredPartition("authored") : undefined;
+ const reviewing = partitionsWanted ? restoredPartition("reviewing") : undefined;
setLoaded(
- snapshot === null
+ restored === null
? null
: {
environmentKey,
- scope: snapshot.scope,
+ scope: scopeKey,
query: "",
source: null,
- data: snapshot.data,
- ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
+ data: restored,
+ ...(authored === undefined || reviewing === undefined
+ ? {}
+ : { partitions: { authored, reviewing } }),
},
);
}
@@ -507,33 +511,6 @@ export function PullRequestsPage() {
...(nextPartitions === undefined ? {} : { partitions: nextPartitions }),
});
}
- const snapshotToWrite =
- loaded !== null &&
- loaded.source !== null &&
- loaded.environmentKey.length > 0 &&
- loaded.query.length === 0
- ? loaded
- : null;
- const snapshotViewers = baselineQuery.data?.viewers;
- const snapshotProviders = baselineQuery.data?.providers;
- useEffect(() => {
- if (snapshotToWrite === null) return;
- writePullRequestListSnapshot(
- typeof window === "undefined" ? undefined : window.localStorage,
- snapshotToWrite.environmentKey,
- {
- scope: snapshotToWrite.scope,
- data: {
- ...snapshotToWrite.data,
- viewers: snapshotViewers ?? snapshotToWrite.data.viewers,
- providers: snapshotProviders ?? snapshotToWrite.data.providers,
- },
- ...(snapshotToWrite.partitions === undefined
- ? {}
- : { partitions: snapshotToWrite.partitions }),
- },
- );
- }, [snapshotToWrite, snapshotViewers, snapshotProviders]);
const narrowed = (() => {
if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
return null;
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
index 7f3c6bfd0bd..c6c10c7a4c3 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
@@ -22,8 +22,6 @@ import {
pullRequestStatsRefreshBatches,
mergePullRequestDiffStats,
partitionPullRequestsWithPriority,
- readPullRequestListSnapshot,
- writePullRequestListSnapshot,
pullRequestAuthorChoices,
selectedPullRequestAuthor,
pullRequestLabelChoices,
@@ -350,69 +348,6 @@ describe("partitioning with the hosts' own priority reads", () => {
});
});
-describe("the list snapshot across a reload", () => {
- const makeStorage = () => {
- const held = new Map<string, string>();
- return {
- getItem: (key: string) => held.get(key) ?? null,
- setItem: (key: string, value: string) => void held.set(key, value),
- };
- };
- const data = {
- entries: [entry({ number: 1 })],
- viewers: { "github.com": "Bilal" },
- providers: [],
- errors: [{ projectId: "project-1", message: "boom" }],
- truncated: true,
- nextCursors: { "pingdotgg/t3code": "cursor-1" },
- } as never;
-
- it("carries neither stale failures nor stale cursors", () => {
- const storage = makeStorage();
- writePullRequestListSnapshot(storage, "env-1", { scope: "s", data });
- const snapshot = readPullRequestListSnapshot(storage, "env-1");
- expect(snapshot?.data.errors).toEqual([]);
- expect(snapshot?.data.nextCursors).toEqual({});
- });
-
- it("caps the accumulated rows but keeps the whole host set", () => {
- const storage = makeStorage();
- const manyEntries = Array.from({ length: 120 }, (_, index) => entry({ number: index + 1 }));
- const viewers = { "github.com": "Bilal", "gitlab.com": "Bilal" };
- const providers = [
- {
- host: "github.com",
- kind: "github",
- searchesOnHost: true,
- projectCount: 1,
- configured: true,
- detail: null,
- },
- {
- host: "gitlab.com",
- kind: "gitlab",
- searchesOnHost: true,
- projectCount: 1,
- configured: true,
- detail: null,
- },
- ];
- const accumulated = {
- entries: manyEntries,
- viewers,
- providers,
- errors: [],
- truncated: true,
- nextCursors: {},
- } as never;
- writePullRequestListSnapshot(storage, "env-1", { scope: "s", data: accumulated });
- const snapshot = readPullRequestListSnapshot(storage, "env-1");
- expect(snapshot?.data.entries).toHaveLength(99);
- expect(snapshot?.data.viewers).toEqual(viewers);
- expect(snapshot?.data.providers).toEqual(providers);
- });
-});
-
describe("remembered pull request list controls", () => {
const makeStorage = () => {
const held = new Map<string, string>();
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
index 2db366c0e29..37124d8d224 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
@@ -1,14 +1,11 @@
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
-import * as Schema from "effect/Schema";
-import {
+import { resolvePullRequestAuthorFilter } from "@t3tools/contracts";
+import type {
EnvironmentId,
PullRequestListEntry,
PullRequestListProjectError,
PullRequestListResult,
- resolvePullRequestAuthorFilter,
-} from "@t3tools/contracts";
-import type {
ProjectId,
RepositoryIdentity,
PullRequestAction,
@@ -575,100 +572,14 @@ export function mergePullRequestLists(
};
}
-const SNAPSHOT_MAX_ENTRIES = 99;
-
-type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
-
export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
[...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
-const snapshotStorageKey = (environmentSetKey: string) =>
- `t3.pullRequests.list:${environmentSetKey}`;
-
export interface PullRequestPartitionsSnapshot {
readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
}
-export interface PullRequestListSnapshot {
- readonly scope: string;
- readonly data: MergedPullRequestList;
- readonly partitions?: PullRequestPartitionsSnapshot | undefined;
-}
-
-const EnvironmentPullRequestEntrySchema = Schema.Struct({
- ...PullRequestListEntry.fields,
- environmentId: EnvironmentId,
-});
-
-const EnvironmentPullRequestErrorSchema = Schema.Struct({
- ...PullRequestListProjectError.fields,
- environmentId: EnvironmentId,
-});
-
-const decodeSnapshot = Schema.decodeUnknownOption(
- Schema.Struct({
- scope: Schema.String,
- data: Schema.Struct({
- ...PullRequestListResult.fields,
- entries: Schema.Array(EnvironmentPullRequestEntrySchema),
- errors: Schema.Array(EnvironmentPullRequestErrorSchema),
- nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
- truncatedEnvironments: Schema.Array(Schema.String),
- }),
- partitions: Schema.optional(
- Schema.Struct({
- authored: Schema.Array(EnvironmentPullRequestEntrySchema),
- reviewing: Schema.Array(EnvironmentPullRequestEntrySchema),
- }),
- ),
- }),
-);
-
-export function readPullRequestListSnapshot(
- storage: SnapshotStorage | undefined,
- environmentSetKey: string,
-): PullRequestListSnapshot | null {
- try {
- const raw = storage?.getItem(snapshotStorageKey(environmentSetKey));
- if (!raw) return null;
- const decoded = decodeSnapshot(JSON.parse(raw));
- return decoded._tag === "Some" ? decoded.value : null;
- } catch {
- return null;
- }
-}
-
-export function writePullRequestListSnapshot(
- storage: SnapshotStorage | undefined,
- environmentSetKey: string,
- snapshot: PullRequestListSnapshot,
-): void {
- try {
- storage?.setItem(
- snapshotStorageKey(environmentSetKey),
- JSON.stringify({
- scope: snapshot.scope,
- data: {
- ...snapshot.data,
- entries: snapshot.data.entries.slice(0, SNAPSHOT_MAX_ENTRIES),
- errors: [],
- nextCursors: {},
- truncatedEnvironments: [],
- },
- ...(snapshot.partitions === undefined
- ? {}
- : {
- partitions: {
- authored: snapshot.partitions.authored.slice(0, SNAPSHOT_MAX_ENTRIES),
- reviewing: snapshot.partitions.reviewing.slice(0, SNAPSHOT_MAX_ENTRIES),
- },
- }),
- }),
- );
- } catch {}
-}
-
/** Retain project scope during reconnect until projects arrive. */
export function resolveProjectScope<Id extends string>(
projectId: Id | undefined,
diff --git a/apps/web/src/state/pullRequests.test.ts b/apps/web/src/state/pullRequests.test.ts
index d524501740c..87b1483f992 100644
--- a/apps/web/src/state/pullRequests.test.ts
+++ b/apps/web/src/state/pullRequests.test.ts
@@ -1,6 +1,13 @@
import { SourceControlProviderKind } from "@t3tools/contracts";
-import { ProjectId, type PullRequestSummary } from "@t3tools/contracts";
-import { describe, expect, it } from "vite-plus/test";
+import {
+ EnvironmentId,
+ ProjectId,
+ type PullRequestListEntry,
+ type PullRequestListInput,
+ type PullRequestListResult,
+ type PullRequestSummary,
+} from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
import {
newestPullRequestObservation,
@@ -8,6 +15,9 @@ import {
observePullRequestChecks,
observePullRequestMetadata,
newestPullRequestSummary,
+ rememberPullRequestListAnswer,
+ restorePullRequestList,
+ restoredPullRequestList,
threadPullRequestLinkToSummary,
} from "./pullRequests";
@@ -187,3 +197,274 @@ describe("pull request observations", () => {
expect(observedPullRequestSummary(state)).toBeNull();
});
});
+
+describe("pull request list answers across a reload", () => {
+ const makeStorage = () => {
+ const held = new Map<string, string>();
+ return {
+ held,
+ getItem: (key: string) => held.get(key) ?? null,
+ setItem: (key: string, value: string) => void held.set(key, value),
+ removeItem: (key: string) => void held.delete(key),
+ key: (index: number) => [...held.keys()][index] ?? null,
+ get length() {
+ return held.size;
+ },
+ };
+ };
+ const listEntry = (number: number, updatedAt = "2026-07-02T00:00:00Z") =>
+ ({
+ provider: SourceControlProviderKind.make("github"),
+ host: "github.com",
+ projectId: ProjectId.make("project-1"),
+ projectTitle: "t3code",
+ repository: "pingdotgg/t3code",
+ number,
+ title: `Pull request ${number}`,
+ url: `https://github.com/pingdotgg/t3code/pull/${number}`,
+ author: { login: "octocat", name: null, avatarUrl: null },
+ headBranch: `feat/branch-${number}`,
+ baseBranch: "main",
+ state: "open",
+ isDraft: false,
+ mergeability: "mergeable",
+ additions: 1,
+ deletions: 0,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt,
+ viewerReviewRequested: false,
+ labels: [],
+ }) as PullRequestListEntry;
+ const answer = (entries: ReadonlyArray<PullRequestListEntry>, host = "github.com") =>
+ ({
+ entries,
+ viewers: { [host]: "Bilal" },
+ providers: [
+ {
+ host,
+ kind: SourceControlProviderKind.make("github"),
+ searchesOnHost: true,
+ projectCount: 1,
+ configured: true,
+ detail: null,
+ },
+ ],
+ errors: [{ projectId: ProjectId.make("project-1"), projectTitle: "t3code", message: "boom" }],
+ truncated: true,
+ nextCursors: { "pingdotgg/t3code": "cursor-1" },
+ }) as PullRequestListResult;
+ const local = EnvironmentId.make("env-local");
+ const remote = EnvironmentId.make("env-remote");
+ const input: PullRequestListInput = { state: "open", involvement: "all", limit: 99 };
+
+ it("restores every environment's first page as one merged list without stale failures or cursors", () => {
+ const storage = makeStorage();
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input },
+ answer([listEntry(1, "2026-07-01T00:00:00Z")]),
+ );
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: remote, input },
+ answer([listEntry(2, "2026-07-03T00:00:00Z")], "gitlab.com"),
+ );
+ const restored = restorePullRequestList(storage, [
+ { environmentId: local, input },
+ { environmentId: remote, input },
+ ]);
+ expect(restored?.entries.map((row) => [row.environmentId, row.number])).toEqual([
+ [remote, 2],
+ [local, 1],
+ ]);
+ expect(restored?.viewers).toEqual({
+ "env-local github.com": "Bilal",
+ "env-remote gitlab.com": "Bilal",
+ });
+ expect(restored?.providers.map((provider) => provider.host)).toEqual([
+ "github.com",
+ "gitlab.com",
+ ]);
+ expect(restored?.errors).toEqual([]);
+ expect(restored?.nextCursors).toEqual({});
+ });
+
+ it("falls back to a fresh read when the browser blocks storage", () => {
+ vi.stubGlobal("window", {
+ get localStorage(): Storage {
+ throw new DOMException("The operation is insecure.", "SecurityError");
+ },
+ });
+ try {
+ expect(restoredPullRequestList([{ environmentId: local, input }])).toBeNull();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("keeps a page of rows and only first-page reads", () => {
+ const storage = makeStorage();
+ const rows = Array.from({ length: 120 }, (_, index) => listEntry(index + 1));
+ rememberPullRequestListAnswer(storage, { environmentId: local, input }, answer(rows));
+ const searched = { ...input, query: "fix" };
+ rememberPullRequestListAnswer(storage, { environmentId: local, input: searched }, answer(rows));
+ const continued = { ...input, cursors: { "pingdotgg/t3code": "cursor-1" } };
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input: continued },
+ answer(rows),
+ );
+ expect(
+ restorePullRequestList(storage, [{ environmentId: local, input }])?.entries,
+ ).toHaveLength(99);
+ expect(restorePullRequestList(storage, [{ environmentId: local, input: searched }])).toBeNull();
+ expect(
+ restorePullRequestList(storage, [{ environmentId: local, input: continued }]),
+ ).toBeNull();
+ });
+
+ it("restores answers kept under a project assignment for a cold start that has none yet", () => {
+ const storage = makeStorage();
+ rememberPullRequestListAnswer(
+ storage,
+ {
+ environmentId: local,
+ input: { ...input, projectIds: [ProjectId.make("project-1")] },
+ },
+ answer([listEntry(1)]),
+ );
+ rememberPullRequestListAnswer(
+ storage,
+ {
+ environmentId: remote,
+ input: { ...input, projectIds: [ProjectId.make("project-2")] },
+ },
+ answer([listEntry(2, "2026-07-03T00:00:00Z")]),
+ );
+ const restored = restorePullRequestList(storage, [
+ { environmentId: local, input },
+ { environmentId: remote, input },
+ ]);
+ expect(restored?.entries.map((row) => [row.environmentId, row.number])).toEqual([
+ [remote, 2],
+ [local, 1],
+ ]);
+ });
+
+ it("shows a pull request once when answers from before a reassignment overlap", () => {
+ const storage = makeStorage();
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input },
+ answer([listEntry(1, "2026-07-01T00:00:00Z")]),
+ );
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: remote, input },
+ answer([listEntry(1, "2026-07-03T00:00:00Z")]),
+ );
+ const restored = restorePullRequestList(storage, [
+ { environmentId: local, input },
+ { environmentId: remote, input },
+ ]);
+ expect(restored?.entries.map((row) => [row.environmentId, row.updatedAt])).toEqual([
+ [remote, "2026-07-03T00:00:00Z"],
+ ]);
+ });
+
+ it("keeps a shared repository's rows when it moves to an environment that has not answered yet", () => {
+ const storage = makeStorage();
+ const own = ProjectId.make("project-own");
+ const shared = { ...listEntry(2), projectId: ProjectId.make("project-shared") };
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input },
+ answer([{ ...listEntry(1), projectId: own }, shared]),
+ );
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: remote, input },
+ answer([listEntry(3, "2026-07-03T00:00:00Z")]),
+ );
+ // The shared repository now belongs to the remote environment, which has not answered yet.
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input: { ...input, projectIds: [own] } },
+ answer([{ ...listEntry(1), projectId: own }]),
+ );
+ const restored = restorePullRequestList(storage, [
+ { environmentId: local, input },
+ { environmentId: remote, input },
+ ]);
+ expect(restored?.entries.map((row) => row.number).toSorted()).toEqual([1, 2, 3]);
+ });
+
+ it("keeps one page per environment when retained rows join a partial answer", () => {
+ const storage = makeStorage();
+ const own = ProjectId.make("project-own");
+ const shared = ProjectId.make("project-shared");
+ const rows = (projectId: ProjectId, first: number) =>
+ Array.from({ length: 99 }, (_, index) => ({ ...listEntry(first + index), projectId }));
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input },
+ answer(rows(shared, 1)),
+ );
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId: local, input: { ...input, projectIds: [own] } },
+ answer(rows(own, 101)),
+ );
+ const restored = restorePullRequestList(storage, [{ environmentId: local, input }]);
+ expect(restored?.entries).toHaveLength(99);
+ expect(restored?.entries.every((row) => row.projectId === own)).toBe(true);
+ });
+
+ it("does not keep grown pages", () => {
+ const storage = makeStorage();
+ const grown = { ...input, limit: 198 };
+ rememberPullRequestListAnswer(storage, { environmentId: local, input: grown }, answer([]));
+ expect(restorePullRequestList(storage, [{ environmentId: local, input: grown }])).toBeNull();
+ });
+
+ it("forgets whole scopes, never one environment of a scope that is kept", () => {
+ const storage = makeStorage();
+ const scoped = (projectIndex: number) => ({
+ ...input,
+ projectId: ProjectId.make(`p-${projectIndex}`),
+ });
+ for (let projectIndex = 0; projectIndex < 9; projectIndex++) {
+ for (const [offset, environmentId] of [local, remote].entries()) {
+ rememberPullRequestListAnswer(
+ storage,
+ { environmentId, input: scoped(projectIndex) },
+ answer([listEntry(projectIndex * 2 + offset + 1, `2026-07-0${2 - offset}T00:00:00Z`)]),
+ );
+ }
+ }
+ const restore = (projectIndex: number) =>
+ restorePullRequestList(storage, [
+ { environmentId: local, input: scoped(projectIndex) },
+ { environmentId: remote, input: scoped(projectIndex) },
+ ]);
+ expect(restore(0)).toBeNull();
+ for (let projectIndex = 1; projectIndex < 9; projectIndex++) {
+ expect(restore(projectIndex)?.entries.map((row) => row.environmentId)).toEqual([
+ local,
+ remote,
+ ]);
+ }
+ });
+
+ it("removes the composite snapshots it replaced", () => {
+ const storage = makeStorage();
+ storage.held.set("t3.pullRequests.list:env-local,env-remote", "{}");
+ storage.held.set("t3.pullRequests.list:env-local", "{}");
+ storage.held.set("t3.other", "kept");
+ rememberPullRequestListAnswer(storage, { environmentId: local, input }, answer([]));
+ expect(
+ [...storage.held.keys()].filter((key) => key.startsWith("t3.pullRequests.list:")),
+ ).toEqual([]);
+ expect(storage.held.get("t3.other")).toBe("kept");
+ });
+});
diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts
index e8ec9a7a407..bd92bd88e05 100644
--- a/apps/web/src/state/pullRequests.ts
+++ b/apps/web/src/state/pullRequests.ts
@@ -5,17 +5,18 @@ import {
createPullRequestEnvironmentAtoms,
createPullRequestStackAtomFamily,
} from "@t3tools/client-runtime/state/pull-requests";
-import type {
- EnvironmentId,
- ProjectId,
- PullRequestChecksState,
- PullRequestListInput,
- PullRequestFilterOptionsInput,
- PullRequestListStatsInput,
- PullRequestListEntry,
- PullRequestRef,
- PullRequestSummary,
- ThreadPullRequestLink,
+import {
+ PullRequestListResult,
+ type EnvironmentId,
+ type ProjectId,
+ type PullRequestChecksState,
+ type PullRequestListInput,
+ type PullRequestFilterOptionsInput,
+ type PullRequestListStatsInput,
+ type PullRequestListEntry,
+ type PullRequestRef,
+ type PullRequestSummary,
+ type ThreadPullRequestLink,
} from "@t3tools/contracts";
import {
threadPullRequestKeyOf,
@@ -24,6 +25,7 @@ import {
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
import { connectionAtomRuntime } from "../connection/runtime";
@@ -215,14 +217,159 @@ function observePullRequestSummary(
);
}
+// Reading localStorage throws where the browser blocks storage; that must not break the page.
function snapshotStorage(): Storage | undefined {
- return typeof window === "undefined" ? undefined : window.localStorage;
+ if (typeof window === "undefined") return undefined;
+ try {
+ return window.localStorage;
+ } catch {
+ return undefined;
+ }
+}
+
+type ListAnswerStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
+
+const LIST_SCOPE_INDEX_KEY = "t3.pullRequests.listScopes";
+const LIST_SCOPE_KEY_PREFIX = "t3.pullRequests.listScope:";
+const LEGACY_SNAPSHOT_KEY_PREFIX = "t3.pullRequests.list:";
+const LIST_ANSWER_MAX_ENTRIES = 99;
+/**
+ * A scope holds a page of rows per environment, so only the scopes visited most recently are
+ * kept. Eviction drops a whole scope, never one environment's answer, so a restored list is never
+ * missing environments that did answer.
+ */
+const LIST_SCOPE_MAX_KEPT = 8;
+const listScopeCodec = Schema.fromJsonString(
+ Schema.Record(Schema.String, Schema.toCodecJson(PullRequestListResult)),
+);
+const decodeListScope = Schema.decodeUnknownOption(listScopeCodec);
+const encodeListScope = Schema.encodeOption(listScopeCodec);
+const decodeListScopeIndex = Schema.decodeUnknownOption(
+ Schema.fromJsonString(Schema.Array(Schema.String)),
+);
+const sweptStorages = new WeakSet<ListAnswerStorage>();
+
+/**
+ * The project assignment is left out: a cold start asks before the project shells load, when
+ * every environment is asked for all of its projects, while the answers were remembered after
+ * overlapping projects were split between environments. Each environment's answer covers only
+ * its assigned projects, so the scope's answers together still cover the whole scope.
+ */
+const listScopeKey = ({ projectIds: _projectIds, ...scope }: PullRequestListInput) =>
+ `${LIST_SCOPE_KEY_PREFIX}${JSON.stringify(scope)}`;
+
+function readListScope(storage: ListAnswerStorage | undefined, key: string) {
+ let raw: string | null = null;
+ try {
+ raw = storage?.getItem(key) ?? null;
+ } catch {}
+ return Option.getOrElse(decodeListScope(raw), (): Record<string, PullRequestListResult> => ({}));
+}
+
+/** The single composite snapshot this replaced is never read again. */
+function sweepLegacySnapshots(storage: ListAnswerStorage): void {
+ if (sweptStorages.has(storage)) return;
+ sweptStorages.add(storage);
+ const legacy: string[] = [];
+ for (let index = 0; index < storage.length; index++) {
+ const key = storage.key(index);
+ if (key?.startsWith(LEGACY_SNAPSHOT_KEY_PREFIX)) legacy.push(key);
+ }
+ for (const key of legacy) storage.removeItem(key);
+}
+
+/**
+ * Keeps what a cold start can show before the host answers again. Searches, continuation pages
+ * and grown pages are never shown that way, so only first-page reads are kept. Failures and
+ * cursors are dropped: they describe the moment of the read, and a restored list must not
+ * continue from it.
+ */
+export function rememberPullRequestListAnswer(
+ storage: ListAnswerStorage | undefined,
+ target: EnvironmentQueryTarget<PullRequestListInput>,
+ answer: PullRequestListResult,
+): void {
+ const { input } = target;
+ if (storage === undefined || input.query !== undefined || input.cursors !== undefined) return;
+ if (input.limit !== undefined && input.limit > LIST_ANSWER_MAX_ENTRIES) return;
+ const key = listScopeKey(input);
+ try {
+ sweepLegacySnapshots(storage);
+ const scope = readListScope(storage, key);
+ // An answer for some projects replaces only their rows. A repository this environment no
+ // longer owns stays covered until the environment that took it over answers; the next answer
+ // for all of the environment's projects, which every cold start asks for, drops them.
+ const assigned = input.projectIds === undefined ? undefined : new Set(input.projectIds);
+ const retained =
+ assigned === undefined
+ ? []
+ : (scope[target.environmentId]?.entries ?? []).filter(
+ (entry) => !assigned.has(entry.projectId),
+ );
+ const encoded = encodeListScope({
+ ...scope,
+ [target.environmentId]: {
+ ...answer,
+ // The fresh rows come first, so retained rows only fill what is left of the page.
+ entries: [...answer.entries, ...retained].slice(0, LIST_ANSWER_MAX_ENTRIES),
+ errors: [],
+ nextCursors: {},
+ },
+ });
+ if (Option.isNone(encoded)) return;
+ const index = Option.getOrElse(
+ decodeListScopeIndex(storage.getItem(LIST_SCOPE_INDEX_KEY)),
+ () => [],
+ );
+ const kept = [key, ...index.filter((held) => held !== key)];
+ for (const evicted of kept.slice(LIST_SCOPE_MAX_KEPT)) storage.removeItem(evicted);
+ storage.setItem(key, encoded.value);
+ storage.setItem(LIST_SCOPE_INDEX_KEY, JSON.stringify(kept.slice(0, LIST_SCOPE_MAX_KEPT)));
+ } catch {}
+}
+
+/**
+ * The kept answers for these reads, merged the way live answers are. An environment without a
+ * kept answer is left out rather than failing the restore: one whose projects were all assigned
+ * to another environment was never asked, and its pull requests are in that environment's answer.
+ */
+export function restorePullRequestList(
+ storage: ListAnswerStorage | undefined,
+ targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
+): MergedPullRequestList | null {
+ const scopes = new Map<string, Record<string, PullRequestListResult>>();
+ const answers: Array<readonly [EnvironmentId, PullRequestListResult]> = [];
+ for (const target of targets) {
+ const key = listScopeKey(target.input);
+ const scope = scopes.get(key) ?? readListScope(storage, key);
+ scopes.set(key, scope);
+ const answer = scope[target.environmentId];
+ if (answer !== undefined) answers.push([target.environmentId, answer]);
+ }
+ const merged = mergePullRequestLists(answers);
+ if (merged === null) return null;
+ // Answers kept before the projects were reassigned between environments can overlap.
+ const seen = new Set<string>();
+ const entries = merged.entries.filter((entry) => {
+ const key = `${entry.host}:${entry.repository}#${entry.number}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ return { ...merged, entries };
+}
+
+export function restoredPullRequestList(
+ targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
+): MergedPullRequestList | null {
+ return restorePullRequestList(snapshotStorage(), targets);
}
// Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
- list: ({ environmentId }, answer, registry) =>
+ list: ({ environmentId, input }, answer, registry) =>
Effect.map(Clock.currentTimeMillis, (observedAt) => {
+ rememberPullRequestListAnswer(snapshotStorage(), { environmentId, input }, answer);
for (const entry of answer.entries) {
observePullRequestSummary(
registry,