The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 03:15 UTC
perf(pr): pull requests paint from data already held, on web, desktop and mobile (#27798)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>
Bilal Bakr committed
Nov 5, 2026 at 23:53 UTC
0ea3c0243fb5b3c07bb8c2bad01c1d3d0f5fde35
28 files changed
+958
-96
apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+2
@@ -58,6 +58,7 @@ import type { ThreadListFilters } from "../../persistence/mobile-preferences";
58
import { appAtomRegistry } from "../../state/atom-registry";
59
import { useProjects } from "../../state/entities";
60
import { environmentThreadShells } from "../../state/threads";
61
+import { withKnownPullRequestSummary } from "../../state/use-thread-pr";
62
import { mobilePreferencesAtom } from "../../state/preferences";
63
import {
64
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
@@ -589,6 +590,7 @@ function AdaptiveWorkspaceLayoutContent(
590
columns: workspaceTabColumns(Platform.OS, tab, options?.columns ?? layout.usesSplitView),
591
check: workspaceSelectionCheck,
592
overlays,
593
+ seedPullRequest: withKnownPullRequestSummary,
594
},
595
);
596
if (layout.variant === "medium") {
apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx
+7
-4
@@ -1,6 +1,6 @@
1
import { Chip } from "../../components/ui/Chip";
2
import { PullRequestSectionHeading } from "./PullRequestSectionHeading";
3
-import type { PullRequestListEntry } from "@t3tools/contracts";
3
+import type { PullRequestListEntry, PullRequestSummary } from "@t3tools/contracts";
4
import { View } from "react-native";
5
import { PullRequestCardGroup, PullRequestCardRow } from "./PullRequestControls";
6
import { PullRequestStackCard } from "./PullRequestStackCard";
@@ -14,11 +14,14 @@ export function PullRequestOverviewLoading({
14
params,
15
stack,
16
}: {
17
- readonly summary: PullRequestListEntry;
17
+ readonly summary: PullRequestListEntry | PullRequestSummary;
18
readonly params: PullRequestParams;
19
readonly stack: PullRequestStackState;
20
}) {
21
- const review = pullRequestListReviewStatus(summary);
21
+ const review = pullRequestListReviewStatus({
22
+ reviewDecision: summary.reviewDecision ?? undefined,
23
+ viewerReviewRequested: "viewerReviewRequested" in summary && summary.viewerReviewRequested,
24
+ });
25
const conflicting = summary.mergeability === "conflicting";
26
const clean = summary.mergeability === "mergeable";
27
return (
@@ -89,7 +92,7 @@ export function PullRequestOverviewLoading({
92
<View className="h-11 rounded-xl bg-subtle-strong" />
93
</View>
94
</PullRequestCardGroup>
92
- {summary.labels.length ? (
95
+ {"labels" in summary && summary.labels.length ? (
96
<View className="flex-row flex-wrap gap-2">
97
{summary.labels.map((label) => (
98
<Chip key={label.name} label={label.name} size="small" />
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+10
-6
@@ -47,7 +47,11 @@ import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-na
47
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
48
import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
49
import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
50
-import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/contracts";
50
+import {
51
+ type PullRequestDetail,
52
+ type PullRequestListEntry,
53
+ type PullRequestSummary,
54
+} from "@t3tools/contracts";
55
import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading";
56
import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";
57
import { pullRequestStatus } from "./pullRequestStatus";
@@ -180,11 +184,11 @@ function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityF
184
}
185
186
function PullRequestIdentity(props: {
183
- readonly pr: PullRequestDetail | PullRequestListEntry;
187
+ readonly pr: PullRequestDetail | PullRequestListEntry | PullRequestSummary;
188
readonly params: PullRequestParams;
189
}) {
190
const { pr } = props;
187
- const status = pullRequestStatus(pr);
191
+ const status = pullRequestStatus({ state: pr.state, isDraft: pr.isDraft === true });
192
return (
193
<View className="gap-3">
194
<View className="flex-row flex-wrap items-center gap-2">
@@ -196,8 +200,8 @@ function PullRequestIdentity(props: {
200
<Text className={`text-xs font-t3-medium ${status.text}`}>{status.label}</Text>
201
</View>
202
)}
199
- <PullRequestDiffStats additions={pr.additions} deletions={pr.deletions} compact />
200
- {"changedFiles" in pr ? (
203
+ <PullRequestDiffStats additions={pr.additions ?? 0} deletions={pr.deletions ?? 0} compact />
204
+ {"changedFiles" in pr && pr.changedFiles !== undefined ? (
205
<Text className="text-2xs text-foreground-muted">
206
{pr.changedFiles} {pr.changedFiles === 1 ? "file" : "files"}
207
</Text>
@@ -209,7 +213,7 @@ function PullRequestIdentity(props: {
213
{pr.title}
214
</Text>
215
<View className="flex-row items-center gap-2">
212
- <PullRequestAvatar actor={pr.author} size={20} />
216
+ <PullRequestAvatar actor={pr.author ?? null} size={20} />
217
<Text className="min-w-0 flex-1 text-xs font-t3-medium" numberOfLines={1}>
218
{pr.author?.login ?? "Unknown author"}
219
</Text>
apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx
+4
-1
@@ -9,6 +9,7 @@ import { pullRequestStatus } from "./pullRequestStatus";
9
import type { PullRequestParams } from "./usePullRequestDiff";
10
import type { PullRequestStackState } from "./usePullRequestStack";
11
import { PullRequestGlyph } from "./pullRequestGlyphs";
12
+import { withKnownPullRequestSummary } from "../../state/use-thread-pr";
13
14
export function PullRequestStackCard(props: {
15
readonly params: PullRequestParams;
@@ -67,7 +68,9 @@ export function PullRequestStackCard(props: {
68
selected
69
? undefined
70
: () => {
70
- const params = pullRequestLayerParams(props.params, layer.number);
71
+ const params = withKnownPullRequestSummary(
72
+ pullRequestLayerParams(props.params, layer.number),
73
+ );
74
if (Platform.OS === "android")
75
selectDetail({ name: "PullRequest", params });
76
else navigation.dispatch(StackActions.push("PullRequest", params));
apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+7
-2
@@ -1,5 +1,10 @@
1
import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
2
-import { EnvironmentId, ProjectId, type PullRequestListEntry } from "@t3tools/contracts";
2
+import {
3
+ EnvironmentId,
4
+ ProjectId,
5
+ type PullRequestListEntry,
6
+ type PullRequestSummary,
7
+} from "@t3tools/contracts";
8
import { useAtomRefresh } from "@effect/atom-react";
9
import { useLayoutEffect, useMemo, useState } from "react";
10
@@ -18,7 +23,7 @@ export type PullRequestParams = {
23
readonly repository: string;
24
readonly number: number;
25
readonly host?: string;
21
- readonly initialSummary?: PullRequestListEntry;
26
+ readonly initialSummary?: PullRequestListEntry | PullRequestSummary;
27
};
28
29
export type PullRequestDiffParams = PullRequestParams & { readonly commit?: string };
apps/mobile/src/features/workspace/workspace-tab-navigation.ts
+8
-2
@@ -150,6 +150,7 @@ function detailRoute(
150
tab: "threads" | "pullRequests",
151
selections: WorkspaceSelections,
152
check: WorkspaceSelectionCheck,
153
+ seedPullRequest?: (identity: Omit<PullRequestSelection, "key">) => object,
154
): RouteLike | undefined {
155
if (tab === "threads") {
156
const draft = selections.threadsDraft;
@@ -184,7 +185,11 @@ function detailRoute(
185
(route) =>
186
route.name === "PullRequest" &&
187
samePullRequest(pullRequestSelection(route.params), pullRequest),
187
- ) ?? { key: pullRequest.key, name: "PullRequest", params: identityOf(pullRequest) }
188
+ ) ?? {
189
+ key: pullRequest.key,
190
+ name: "PullRequest",
191
+ params: seedPullRequest?.(identityOf(pullRequest)) ?? identityOf(pullRequest),
192
+ }
193
);
194
}
195
@@ -204,6 +209,7 @@ export function workspaceTabNavigationState<
209
readonly columns: boolean;
210
readonly check: WorkspaceSelectionCheck;
211
readonly overlays?: readonly RouteLike[];
212
+ readonly seedPullRequest?: (identity: Omit<PullRequestSelection, "key">) => object;
213
},
214
) {
215
const overlays = options.overlays ?? [];
@@ -221,7 +227,7 @@ export function workspaceTabNavigationState<
227
const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };
228
const detail =
229
options.columns && tab !== "usage"
224
- ? detailRoute(state, tab, selections, options.check)
230
+ ? detailRoute(state, tab, selections, options.check, options.seedPullRequest)
231
: undefined;
232
const routes = [...[home, ...(detail ? [detail] : [])].map(keyed), ...overlays];
233
return { ...state, index: routes.length - 1, routes };
apps/mobile/src/native/useOpenPullRequest.ts
+4
-2
@@ -7,6 +7,7 @@ import { useProjects, useThreadShell } from "../state/entities";
7
import { tryOpenExternalUrl } from "../lib/openExternalUrl";
8
import { appAtomRegistry } from "../state/atom-registry";
9
import { environmentServerConfigsAtom } from "../state/server";
10
+import { withKnownPullRequestSummary } from "../state/use-thread-pr";
11
12
type PullRequestContext = { readonly environmentId: string; readonly projectId: string };
13
@@ -19,10 +20,11 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean
20
return async (url: string, context: PullRequestContext | null) => {
21
// Read at press time so a config push does not hand every link a new handler.
22
const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
22
- const params = nativePullRequestDestination(url, context, projects, (environmentId) =>
23
+ const destination = nativePullRequestDestination(url, context, projects, (environmentId) =>
24
serverConfigs.has(environmentId),
25
);
25
- if (!params) return tryOpenExternalUrl(url, "pull-request");
26
+ if (!destination) return tryOpenExternalUrl(url, "pull-request");
27
+ const params = withKnownPullRequestSummary(destination);
28
// Android shows one page at a time; iOS opens it over the current page, so Back returns.
29
if (Platform.OS === "android") selectDetail({ name: "PullRequest", params });
30
else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
apps/mobile/src/state/thread-pr-presentation.ts
+58
-1
@@ -1,13 +1,20 @@
1
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2
-import type { ThreadPullRequestLink, VcsStatusResult } from "@t3tools/contracts";
2
+import type {
3
+ PullRequestSummary,
4
+ ThreadPullRequestKey,
5
+ ThreadPullRequestLink,
6
+ VcsStatusResult,
7
+} from "@t3tools/contracts";
8
import {
9
sourceControlClients,
10
type ChangeRequestTerminology,
11
} from "@t3tools/client-runtime/source-control-clients";
12
13
import {
14
+ legacyThreadPullRequestKey,
15
resolveThreadCurrentPullRequestLink,
16
resolveThreadPullRequestBadge,
17
+ threadPullRequestKeyOf,
18
} from "@t3tools/client-runtime/thread-pull-requests";
19
20
export type ThreadPr = NonNullable<VcsStatusResult["pr"]>;
@@ -142,3 +149,53 @@ export function rememberBounded<V>(
149
}
150
return next;
151
}
152
+
153
+/** The newest summary held for `pullRequest`, matched strictly by host, repository and number. */
154
+export function knownPullRequestSummary(
155
+ pullRequest: ThreadPullRequestKey,
156
+ threads: Iterable<Pick<EnvironmentThreadShell, "projectId" | "pullRequests">>,
157
+ summaries: Iterable<PullRequestSummary>,
158
+): PullRequestSummary | undefined {
159
+ const key = threadPullRequestKeyOf(pullRequest);
160
+ let newest:
161
+ | { readonly summary: PullRequestSummary; readonly updatedAt: number; readonly readAt: number }
162
+ | undefined;
163
+ // Checks and reviews change without moving `updatedAt`, so equal versions prefer the later read.
164
+ const consider = (summary: PullRequestSummary, readAt = Number.NEGATIVE_INFINITY) => {
165
+ const updatedAt = Date.parse(summary.updatedAt);
166
+ if (
167
+ newest === undefined ||
168
+ updatedAt > newest.updatedAt ||
169
+ (updatedAt === newest.updatedAt && readAt > newest.readAt)
170
+ ) {
171
+ newest = { summary, updatedAt, readAt };
172
+ }
173
+ };
174
+ for (const summary of summaries) {
175
+ if (threadPullRequestKeyOf(legacyThreadPullRequestKey(summary)) === key) {
176
+ consider(summary, summary.observedAt);
177
+ }
178
+ }
179
+ for (const thread of threads) {
180
+ for (const link of thread.pullRequests) {
181
+ const snapshot = link.snapshot;
182
+ if (snapshot?.updatedAt == null || threadPullRequestKeyOf(link) !== key) continue;
183
+ consider(
184
+ {
185
+ ...snapshot,
186
+ updatedAt: snapshot.updatedAt,
187
+ provider: (
188
+ sourceControlClients.findByChangeRequestUrl(link.url) ??
189
+ sourceControlClients.get(undefined)
190
+ ).kind,
191
+ projectId: thread.projectId,
192
+ repository: link.repository,
193
+ number: link.number,
194
+ url: link.url,
195
+ },
196
+ Date.parse(snapshot.syncedAt),
197
+ );
198
+ }
199
+ }
200
+ return newest?.summary;
201
+}
apps/mobile/src/state/use-thread-pr.test.ts
+50
-1
@@ -1,7 +1,13 @@
1
-import { ProjectId, type ThreadPullRequestLink } from "@t3tools/contracts";
1
+import {
2
+ ProjectId,
3
+ type PullRequestSummary,
4
+ SourceControlProviderKind,
5
+ type ThreadPullRequestLink,
6
+} from "@t3tools/contracts";
7
import { describe, expect, it } from "vite-plus/test";
8
9
import {
10
+ knownPullRequestSummary,
11
presentThreadLinkedPullRequests,
12
rememberBounded,
13
resolveThreadPrSource,
@@ -113,6 +119,49 @@ describe("resolveThreadPrSource compatibility", () => {
119
});
120
});
121
122
+describe("knownPullRequestSummary", () => {
123
+ it("seeds from the newest summary of the same pull request, never another's", () => {
124
+ const projectId = ProjectId.make("project");
125
+ const link = linkedPr(7);
126
+ const threads = [
127
+ {
128
+ projectId,
129
+ pullRequests: [
130
+ { ...link, snapshot: { ...link.snapshot!, updatedAt: "2026-09-08T00:00:00.000Z" } },
131
+ ],
132
+ },
133
+ ];
134
+ const listed: PullRequestSummary = {
135
+ provider: SourceControlProviderKind.make("github"),
136
+ projectId,
137
+ repository: "t3tools/t3code",
138
+ number: 7,
139
+ title: "Listed title",
140
+ url: "https://github.com/t3tools/t3code/pull/7",
141
+ state: "open",
142
+ headBranch: "change-7",
143
+ baseBranch: "main",
144
+ updatedAt: "2026-09-09T00:00:00.000Z",
145
+ };
146
+ const lookup = (host: string, number: number, summaries = [listed]) =>
147
+ knownPullRequestSummary({ host, repository: "t3tools/t3code", number }, threads, summaries);
148
+
149
+ expect(lookup("github.com", 7, [])?.title).toBe("Change 7");
150
+ expect(lookup("github.com", 7)?.title).toBe("Listed title");
151
+ expect(lookup("github.com", 8)).toBeUndefined();
152
+ expect(lookup("gitlab.com", 7)).toBeUndefined();
153
+
154
+ const sameVersion = { ...listed, updatedAt: "2026-09-08T00:00:00.000Z" };
155
+ const syncedAt = Date.parse(link.snapshot!.syncedAt);
156
+ expect(lookup("github.com", 7, [{ ...sameVersion, observedAt: syncedAt - 1 }])?.title).toBe(
157
+ "Change 7",
158
+ );
159
+ expect(lookup("github.com", 7, [{ ...sameVersion, observedAt: syncedAt + 1 }])?.title).toBe(
160
+ "Listed title",
161
+ );
162
+ });
163
+});
164
+
165
describe("rememberBounded", () => {
166
it("moves a re-answered entry to the newest slot and evicts the oldest past the limit", () => {
167
let snapshots: ReadonlyMap<string, number> = new Map();
apps/mobile/src/state/use-thread-pr.ts
+18
@@ -10,10 +10,13 @@ import { Atom } from "effect/reactivity";
10
import { use, useMemo } from "react";
11
12
import { connectionAtomRuntime } from "../connection/runtime";
13
+import { appAtomRegistry } from "./atom-registry";
14
import { serverEnvironment } from "./server";
15
+import { environmentThreadShells } from "./threads";
16
import { useEnvironmentQuery } from "./query";
17
import { ThreadPrDemandContext } from "./thread-pr-demand";
18
import {
19
+ knownPullRequestSummary,
20
rememberBounded,
21
resolveThreadPrSource,
22
presentThreadPr,
@@ -59,6 +62,21 @@ const pullRequestSummaryAtom = createLinkedPullRequestSummaryAtomFamily(
62
63
export { type ThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation";
64
65
+/** Seeds a pull request page with a summary already in memory, never another pull request's. */
66
+export function withKnownPullRequestSummary<
67
+ Params extends { readonly host?: string; readonly repository: string; readonly number: number },
68
+>(params: Params) {
69
+ const initialSummary =
70
+ params.host === undefined
71
+ ? undefined
72
+ : knownPullRequestSummary(
73
+ { host: params.host, repository: params.repository, number: params.number },
74
+ appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
75
+ appAtomRegistry.get(pullRequestSnapshotsAtom).values(),
76
+ );
77
+ return initialSummary === undefined ? params : { ...params, initialSummary };
78
+}
79
+
80
export function useThreadPr(thread: EnvironmentThreadShell): ThreadPrPresentation | null {
81
const demand = use(ThreadPrDemandContext);
82
const supportsLinks = useAtomValue(
apps/server/src/pullRequest/PullRequestService.test.ts
+67
@@ -202,6 +202,73 @@ it.effect("does not wait for an in-flight detail read to display a preview", ()
202
}),
203
);
204
205
+it.effect("shows a listed pull request's preview without asking the host again", () =>
206
+ Effect.gen(function* () {
207
+ let previewReads = 0;
208
+ const service = yield* makeService({
209
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })],
210
+ providers: [
211
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
212
+ listChangeRequests: () =>
213
+ Effect.succeed({
214
+ items: [changeRequest(1, "2026-07-02T00:00:00Z")],
215
+ truncated: false,
216
+ continues: false,
217
+ }),
218
+ getChangeRequestPreview: () =>
219
+ Effect.sync(() => {
220
+ previewReads++;
221
+ return { ...changeRequest(1, "2026-07-02T00:00:00Z"), title: "Renamed" };
222
+ }),
223
+ }),
224
+ ],
225
+ });
226
+ const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
227
+ yield* service.list({ state: "open" });
228
+ assert.strictEqual((yield* service.preview(ref)).title, "Change request 1");
229
+ assert.strictEqual(previewReads, 0);
230
+ yield* service.refreshAfterTurn(ref.projectId);
231
+ assert.strictEqual((yield* service.preview(ref)).title, "Renamed");
232
+ assert.strictEqual(previewReads, 1);
233
+ yield* service.list({ state: "open", limit: 1 });
234
+ assert.strictEqual((yield* service.preview(ref)).title, "Renamed");
235
+ }),
236
+);
237
+
238
+it.effect("a list read under a pinned account leaves the shared preview to the host", () =>
239
+ Effect.gen(function* () {
240
+ let previewReads = 0;
241
+ const service = yield* makeService({
242
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })],
243
+ providers: [
244
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
245
+ getRoutingIdentity: () => Effect.succeed({ accountId: "101", viewer: "octocat" }),
246
+ withVerifiedCredential: (_, use) =>
247
+ use({ accountId: "101", viewer: "octocat", credentialFingerprint: "pinned" }),
248
+ listChangeRequests: () =>
249
+ Effect.succeed({
250
+ items: [{ ...changeRequest(1, "2026-07-02T00:00:00Z"), title: "Pinned view" }],
251
+ truncated: false,
252
+ continues: false,
253
+ }),
254
+ getChangeRequestPreview: () =>
255
+ Effect.sync(() => {
256
+ previewReads++;
257
+ return changeRequest(1, "2026-07-02T00:00:00Z");
258
+ }),
259
+ }),
260
+ ],
261
+ });
262
+ const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
263
+ yield* service.withRoutingCredential(
264
+ { ...ref, host: "github.com", expectedAccountId: "101" },
265
+ service.list({ state: "open" }),
266
+ );
267
+ assert.strictEqual((yield* service.preview(ref)).title, "Change request 1");
268
+ assert.strictEqual(previewReads, 1);
269
+ }),
270
+);
271
+
272
function unusable(provider: SourceControlProviderKind, reason: "missing-tool" | "unauthenticated") {
273
return new PullRequestProviderError({
274
provider,
apps/server/src/pullRequest/PullRequestService.ts
+16
-3
@@ -1262,6 +1262,7 @@ export const make = Effect.gen(function* () {
1262
"PullRequestService.listUncached",
1263
)(function* (input) {
1264
const involvement = input.involvement ?? "all";
1265
+ const epochAtStart = epochCounter;
1266
const continuation = yield* decodeCursors(input.cursors);
1267
const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input);
1268
const projectCounts = new Map<string, number>();
@@ -1549,13 +1550,25 @@ export const make = Effect.gen(function* () {
1550
for (const batch of batches) {
1551
if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor;
1552
}
1553
+ const entries = batches
1554
+ .flatMap((batch) => batch.entries)
1555
+ .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
1556
+ // Hover cards on listed rows read from here. A pinned account or a mid-read refresh is another
1557
+ // scope; half the cache stays free for previews read directly.
1558
+ if ((yield* routingCredential) === null && epochCounter === epochAtStart) {
1559
+ const seeds = entries
1560
+ .slice(0, DETAIL_CACHE_CAPACITY / 2)
1561
+ .map((entry) => [refCacheKey(entry), previewFields(entry)] as const)
1562
+ .toReversed();
1563
+ for (const [key, value] of seeds) {
1564
+ if (!(yield* Cache.has(previewCache, key))) yield* Cache.set(previewCache, key, value);
1565
+ }
1566
+ }
1567
1568
return {
1569
viewers: viewers as PullRequestListResult["viewers"],
1570
providers,
1556
- entries: batches
1557
- .flatMap((batch) => batch.entries)
1558
- .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
1571
+ entries,
1572
errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)],
1573
truncated: batches.some((batch) => batch.truncated),
1574
nextCursors,
apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx
new
+92
@@ -0,0 +1,92 @@
1
+import { EnvironmentId, ProjectId, type PullRequestSummary } from "@t3tools/contracts";
2
+import { expect, it, vi } from "vite-plus/test";
3
+import { page, userEvent } from "vite-plus/test/browser";
4
+
5
+const known = vi.hoisted(
6
+ () =>
7
+ ({
8
+ provider: "github",
9
+ projectId: "project",
10
+ repository: "owner/repo",
11
+ number: 1,
12
+ title: "Known title",
13
+ url: "https://github.com/owner/repo/pull/1",
14
+ state: "open",
15
+ headBranch: "feature",
16
+ baseBranch: "main",
17
+ updatedAt: "2026-09-01T00:00:00Z",
18
+ }) as PullRequestSummary,
19
+);
20
+const state = vi.hoisted(() => ({ restoredPreview: null as unknown }));
21
+vi.mock(import("~/state/query"), async (original) => ({
22
+ ...(await original()),
23
+ // The host has not answered the preview read yet.
24
+ useEnvironmentQuery: ((atom: unknown) => ({
25
+ data: state.restoredPreview,
26
+ dataUpdatedAt: 0,
27
+ error: null,
28
+ failure: null,
29
+ isPending: atom !== null,
30
+ isSuccess: false,
31
+ refresh: () => undefined,
32
+ })) as never,
33
+}));
34
+vi.mock(import("~/state/pullRequests"), async (original) => ({
35
+ ...(await original()),
36
+ useSharedPullRequestSummary: (() => known) as never,
37
+}));
38
+
39
+import { render } from "../../../test/render";
40
+import { PullRequestLinkPreview } from "./PullRequestLinkPreview";
41
+
42
+function renderPreview() {
43
+ return render(
44
+ <PullRequestLinkPreview
45
+ link={<a href={known.url}>#1</a>}
46
+ originalUrl={known.url}
47
+ target={{
48
+ environmentId: EnvironmentId.make("environment"),
49
+ input: { projectId: ProjectId.make("project"), repository: "owner/repo", number: 1 },
50
+ }}
51
+ />,
52
+ );
53
+}
54
+
55
+it("keeps a refreshing preview's state and title over an older known summary", async () => {
56
+ state.restoredPreview = {
57
+ projectId: "project",
58
+ repository: "owner/repo",
59
+ number: 1,
60
+ title: "Renamed title",
61
+ url: known.url,
62
+ author: { login: "octocat" },
63
+ state: "closed",
64
+ isDraft: false,
65
+ createdAt: "2026-08-01T00:00:00Z",
66
+ };
67
+ await using screen = await renderPreview();
68
+
69
+ await userEvent.hover(screen.getByRole("link"));
70
+
71
+ await expect.element(page.getByText("Renamed title")).toBeVisible();
72
+ await expect.element(page.getByText("Closed", { exact: true })).toBeVisible();
73
+ expect(page.getByText("Known title").query()).toBeNull();
74
+});
75
+
76
+it("shows the known summary while the preview loads", async () => {
77
+ state.restoredPreview = null;
78
+ await using screen = await render(
79
+ <PullRequestLinkPreview
80
+ link={<a href={known.url}>#1</a>}
81
+ originalUrl={known.url}
82
+ target={{
83
+ environmentId: EnvironmentId.make("environment"),
84
+ input: { projectId: ProjectId.make("project"), repository: "owner/repo", number: 1 },
85
+ }}
86
+ />,
87
+ );
88
+
89
+ await userEvent.hover(screen.getByRole("link"));
90
+
91
+ await expect.element(page.getByText("Known title")).toBeVisible();
92
+});
apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx
+31
-20
@@ -12,7 +12,7 @@ import {
12
} from "react";
13
14
import { RelativeTime } from "~/components/RelativeTime";
15
-import { pullRequestEnvironment } from "~/state/pullRequests";
15
+import { pullRequestEnvironment, useSharedPullRequestSummary } from "~/state/pullRequests";
16
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
17
import { useEnvironmentQuery } from "~/state/query";
18
@@ -57,6 +57,10 @@ export function PullRequestLinkPreview({
57
})
58
: null,
59
);
60
+ const summary = useSharedPullRequestSummary(
61
+ open ? target.environmentId : null,
62
+ open ? target.input : null,
63
+ );
64
const readPreview = useAtomQueryRunner(pullRequestEnvironment.preview, {
65
reportFailure: false,
66
reportDefect: false,
@@ -85,18 +89,19 @@ export function PullRequestLinkPreview({
89
})
90
: link;
91
const preview = previewQuery.data;
88
- const showCard = preview !== null || (previewQuery.error !== null && fallback !== undefined);
92
+ const card = preview ?? summary;
93
+ const showCard = card !== null || (previewQuery.error !== null && fallback !== undefined);
94
const showUrlTooltip = open && previewQuery.error !== null && !showCard;
95
const state =
91
- preview === null
96
+ card === null
97
? null
93
- : resolvePullRequestState({ state: preview.state, isDraft: preview.isDraft });
98
+ : resolvePullRequestState({ state: card.state, isDraft: card.isDraft ?? false });
99
const authorLabel =
95
- preview?.author === null
100
+ card?.author === null
101
? "ghost"
97
- : preview?.author.name && preview.author.name !== preview.author.login
98
- ? `${preview.author.name} (@${preview.author.login})`
99
- : (preview?.author.login ?? null);
102
+ : card?.author?.name && card.author.name !== card.author.login
103
+ ? `${card.author.name} (@${card.author.login})`
104
+ : (card?.author?.login ?? null);
105
106
return (
107
<PreviewCard open={open} onOpenChange={setOpen} actionsRef={previewActionsRef}>
@@ -116,13 +121,13 @@ export function PullRequestLinkPreview({
121
{showCard ? (
122
<PreviewCardPopup align="center" className="w-80 max-w-[calc(100vw-2rem)]">
123
<div className="p-3">
119
- {preview === null ? (
124
+ {card === null ? (
125
fallback
126
) : (
127
<div className="min-w-0">
128
<div className="flex min-w-0 items-center gap-1.5 text-2xs text-muted-foreground">
124
- <span className="min-w-0 truncate">{preview.repository}</span>
125
- <span className="shrink-0">#{preview.number}</span>
129
+ <span className="min-w-0 truncate">{card.repository}</span>
130
+ <span className="shrink-0">#{card.number}</span>
131
<span aria-hidden>·</span>
132
{state === null ? null : (
133
<span className="inline-flex shrink-0 items-center gap-1">
@@ -132,16 +137,22 @@ export function PullRequestLinkPreview({
137
)}
138
</div>
139
<p className="mt-1 text-sm font-medium leading-snug text-foreground text-pretty">
135
- {preview.title}
140
+ {card.title}
141
</p>
137
- <div className="mt-2 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
138
- <PullRequestActorAvatar actor={preview.author} className="size-4" />
139
- <span className="min-w-0 truncate">{authorLabel}</span>
140
- <span aria-hidden>·</span>
141
- <span className="shrink-0">
142
- opened <RelativeTime timestamp={preview.createdAt} />
143
- </span>
144
- </div>
142
+ {card.author === undefined ? null : (
143
+ <div className="mt-2 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
144
+ <PullRequestActorAvatar actor={card.author} className="size-4" />
145
+ <span className="min-w-0 truncate">{authorLabel}</span>
146
+ {preview === null ? null : (
147
+ <>
148
+ <span aria-hidden>·</span>
149
+ <span className="shrink-0">
150
+ opened <RelativeTime timestamp={preview.createdAt} />
151
+ </span>
152
+ </>
153
+ )}
154
+ </div>
155
+ )}
156
</div>
157
)}
158
</div>
apps/web/src/components/pullRequest/PullRequestListGroups.tsx
+31
-5
@@ -1,6 +1,6 @@
1
import type { EnvironmentId, PullRequestAction } from "@t3tools/contracts";
2
import { EyeIcon, LayersIcon, PenLineIcon, UsersIcon, type LucideIcon } from "lucide-react";
3
-import type { RefCallback } from "react";
3
+import { useDeferredValue, type RefCallback } from "react";
4
5
import { cn } from "~/lib/utils";
6
import { Separator } from "../ui/separator";
@@ -23,18 +23,32 @@ const GROUP_ICONS: Record<string, LucideIcon> = {
23
};
24
25
const MATCHED_ELSEWHERE_SCORE = 10;
26
+const FIRST_PAINT_ROWS = 24;
27
+
28
+function firstPaintGroups<Group extends { entries: ReadonlyArray<unknown> }>(
29
+ groups: ReadonlyArray<Group>,
30
+): ReadonlyArray<Group> {
31
+ let left = FIRST_PAINT_ROWS;
32
+ return groups.flatMap((group) => {
33
+ const entries = group.entries.slice(0, left);
34
+ left -= entries.length;
35
+ return entries.length === 0 ? [] : [{ ...group, entries }];
36
+ });
37
+}
38
39
function PullRequestGroupHeader({
40
group,
41
+ count,
42
}: {
30
- group: { key: string; label: string; entries: ReadonlyArray<unknown> };
43
+ group: { key: string; label: string };
44
+ count: number;
45
}) {
46
const Icon = GROUP_ICONS[group.key] ?? LayersIcon;
47
return (
48
<div className="flex items-center gap-2 px-3 pb-1 text-xs font-medium text-muted-foreground/70">
49
<Icon aria-hidden className="size-3.5 shrink-0" />
50
<h2 className="shrink-0">{group.label}</h2>
37
- <span className="shrink-0 tabular-nums text-muted-foreground/50">{group.entries.length}</span>
51
+ <span className="shrink-0 tabular-nums text-muted-foreground/50">{count}</span>
52
<Separator className="min-w-2 flex-1" />
53
</div>
54
);
@@ -48,6 +62,7 @@ export function PullRequestListGroups({
62
showProvider,
63
statsRef,
64
onSelect,
65
+ onIntent,
66
hostActionsOf,
67
onActed,
68
closingKeys,
@@ -67,18 +82,28 @@ export function PullRequestListGroups({
82
showProvider: boolean;
83
statsRef: RefCallback<HTMLDivElement>;
84
onSelect: (entry: PullRequestRowTarget) => void;
85
+ onIntent: (entry: PullRequestRowTarget | null) => void;
86
hostActionsOf: (entry: EnvironmentPullRequestEntry) => ReadonlySet<PullRequestAction>;
87
onActed: (result: PullRequestSpeedActionResult) => void;
88
closingKeys: ReadonlySet<string>;
89
sweepingKeys: ReadonlySet<string>;
90
onCloseSweepStart: (entry: EnvironmentPullRequestEntry, event: PointerEvent) => void;
91
}) {
92
+ // Every row mounts tooltips and actions; painting a first screenful before the rest keeps
93
+ // opening the page from blocking on the whole list.
94
+ const shownGroups = useDeferredValue(groups, firstPaintGroups(groups));
95
+ const counts = new Map(groups.map((group) => [group.key, group.entries.length]));
96
return (
97
<PullRequestSpeedModeProvider>
98
<div className={cn("space-y-3", sweepingKeys.size > 0 && "**:pointer-events-none")}>
79
- {groups.map((group) => (
99
+ {shownGroups.map((group) => (
100
<div key={group.key} className="space-y-0.5">
81
- {group.label ? <PullRequestGroupHeader group={group} /> : null}
101
+ {group.label ? (
102
+ <PullRequestGroupHeader
103
+ group={group}
104
+ count={counts.get(group.key) ?? group.entries.length}
105
+ />
106
+ ) : null}
107
{group.entries.map((entry) => {
108
const entryKey = pullRequestEntryKey(entry);
109
const environmentLabel = environmentLabels?.get(entry.environmentId);
@@ -102,6 +127,7 @@ export function PullRequestListGroups({
127
selected.number === entry.number
128
}
129
onSelect={onSelect}
130
+ onIntent={onIntent}
131
hostActions={hostActionsOf(entry)}
132
onActed={onActed}
133
closing={closingKeys.has(entryKey)}
apps/web/src/components/pullRequest/PullRequestRow.tsx
+11
@@ -78,6 +78,7 @@ function PullRequestRowImpl({
78
statsKey,
79
statsRef,
80
onSelect,
81
+ onIntent,
82
hostActions,
83
onActed,
84
closing = false,
@@ -94,6 +95,8 @@ function PullRequestRowImpl({
95
statsKey?: string;
96
statsRef?: RefCallback<HTMLDivElement>;
97
onSelect: (entry: PullRequestRowTarget) => void;
98
+ /** The row the pointer or focus rests on, or null when it leaves. */
99
+ onIntent?: (entry: PullRequestRowTarget | null) => void;
100
hostActions: ReadonlySet<PullRequestAction>;
101
onActed: (result: PullRequestSpeedActionResult) => void;
102
closing?: boolean;
@@ -115,6 +118,14 @@ function PullRequestRowImpl({
118
type="button"
119
aria-current={selected ? "true" : undefined}
120
onClick={() => onSelect(entry)}
121
+ onPointerEnter={() => onIntent?.(entry)}
122
+ onPointerLeave={(event) => {
123
+ if (event.currentTarget !== document.activeElement) onIntent?.(null);
124
+ }}
125
+ onFocus={() => onIntent?.(entry)}
126
+ onBlur={(event) => {
127
+ if (!event.currentTarget.matches(":hover")) onIntent?.(null);
128
+ }}
129
className={cn(
130
PULL_REQUEST_ROW_CLASS,
131
PAGE_ROW_CLASS,
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+9
-7
@@ -64,6 +64,8 @@ import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu";
64
import { INVOLVEMENT_TABS, SORT_OPTIONS, STATE_TABS } from "./pullRequestListOptions";
65
import { PullRequestsColumn } from "./PullRequestsColumn";
66
import { PullRequestListGroups } from "./PullRequestListGroups";
67
+import { pullRequestPanelReference } from "./usePullRequestDetail";
68
+import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch";
69
import {
70
usePullRequestDisplayGroups,
71
usePullRequestQueryFilters,
@@ -1080,6 +1082,9 @@ export function PullRequestsPage() {
1082
),
1083
);
1084
1085
+ const prefetchEntry = usePullRequestIntentPrefetch((entry) =>
1086
+ listedPullRequestsBySurface.has(pullRequestListEntryId(entry)),
1087
+ );
1088
const selectEntry = (entry: PullRequestRowTarget) => {
1089
if (rightPanelRef === null) return;
1090
useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
@@ -1184,6 +1189,7 @@ export function PullRequestsPage() {
1189
showProvider={showProvider}
1190
statsRef={registerStatsRow}
1191
onSelect={selectEntry}
1192
+ onIntent={prefetchEntry}
1193
hostActionsOf={hostActionsOf}
1194
onActed={onSpeedAction}
1195
closingKeys={closingKeys}
@@ -1528,14 +1534,10 @@ export function PullRequestsPage() {
1534
selectedEnvironmentId: panelEnvironmentId,
1535
});
1536
}}
1531
- reference={{
1537
+ reference={pullRequestPanelReference({
1538
+ ...renderedPullRequestSurface,
1539
projectId: renderedPullRequestSurface.projectId as ProjectId,
1533
- repository: renderedPullRequestSurface.repository,
1534
- number: renderedPullRequestSurface.number,
1535
- ...(renderedPullRequestSurface.host
1536
- ? { host: renderedPullRequestSurface.host }
1537
- : {}),
1538
- }}
1540
+ })}
1541
listEntry={
1542
listedPullRequestsBySurface.get(
1543
pullRequestListEntryId(renderedPullRequestSurface),
apps/web/src/components/pullRequest/usePullRequestDetail.ts
+16
@@ -4,6 +4,7 @@ import {
4
type EnvironmentId,
5
type PullRequestListEntry,
6
type PullRequestRef,
7
+ type ProjectId,
8
} from "@t3tools/contracts";
9
import { useState } from "react";
10
@@ -22,6 +23,21 @@ import {
23
resolveDisplayedPullRequestDetail,
24
} from "./pullRequestDetail.logic";
25
26
+// Query atoms key on JSON order, so the panel and the row prefetch must build the ref here.
27
+export function pullRequestPanelReference(target: {
28
+ readonly projectId: ProjectId;
29
+ readonly repository: string;
30
+ readonly number: number;
31
+ readonly host?: string | undefined;
32
+}): PullRequestRef {
33
+ return {
34
+ projectId: target.projectId,
35
+ repository: target.repository,
36
+ number: target.number,
37
+ ...(target.host ? { host: target.host } : {}),
38
+ };
39
+}
40
+
41
export function pullRequestRefKey(reference: PullRequestRef) {
42
return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
43
}
apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx
new
+86
@@ -0,0 +1,86 @@
1
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2
+import { expect, it, vi } from "vite-plus/test";
3
+
4
+const state = vi.hoisted(() => ({ reads: [] as Array<unknown> }));
5
+vi.mock(import("~/state/pullRequests"), async (original) => {
6
+ const actual = await original();
7
+ return {
8
+ ...actual,
9
+ pullRequestEnvironment: {
10
+ ...actual.pullRequestEnvironment,
11
+ detail: ((target: unknown) => target) as never,
12
+ },
13
+ };
14
+});
15
+vi.mock(import("~/state/query"), async (original) => ({
16
+ ...(await original()),
17
+ useEnvironmentQuery: ((target: unknown) => {
18
+ if (target !== null || state.reads.length > 0) state.reads.push(target);
19
+ return {};
20
+ }) as never,
21
+}));
22
+
23
+import { act, fakeTimers, render } from "../../../test/render";
24
+import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch";
25
+
26
+const environmentId = EnvironmentId.make("environment");
27
+const row = {
28
+ environmentId,
29
+ projectId: ProjectId.make("project"),
30
+ host: "GitHub.com",
31
+ repository: "owner/repo",
32
+ number: 7,
33
+};
34
+
35
+function Rows() {
36
+ const prefetch = usePullRequestIntentPrefetch(() => true);
37
+ return (
38
+ <>
39
+ <button type="button" onClick={() => prefetch(row)}>
40
+ rest
41
+ </button>
42
+ <button type="button" onClick={() => prefetch(null)}>
43
+ leave
44
+ </button>
45
+ </>
46
+ );
47
+}
48
+
49
+it("reads the panel's detail once intent rests on a row for 150 ms", async () => {
50
+ state.reads = [];
51
+ await using screen = await render(<Rows />, {
52
+ // A bare hook probe; nothing here navigates.
53
+ router: false,
54
+ });
55
+ using _timers = fakeTimers({ now: 0 });
56
+ const rest = screen.getByRole("button", { name: "rest" }).element() as HTMLElement;
57
+ const leave = screen.getByRole("button", { name: "leave" }).element() as HTMLElement;
58
+
59
+ await act(() => {
60
+ rest.click();
61
+ leave.click();
62
+ });
63
+ await act(() => vi.advanceTimersByTime(1_000));
64
+ expect(state.reads).toEqual([]);
65
+
66
+ await act(() => rest.click());
67
+ await act(() => vi.advanceTimersByTime(149));
68
+ expect(state.reads).toEqual([]);
69
+ await act(() => vi.advanceTimersByTime(1));
70
+ // Query atoms key on JSON order: this is the order the PRs page panel reads.
71
+ expect(JSON.stringify(state.reads.at(-1))).toBe(
72
+ JSON.stringify({
73
+ environmentId,
74
+ input: {
75
+ projectId: row.projectId,
76
+ repository: "owner/repo",
77
+ number: 7,
78
+ host: "github.com",
79
+ allowStale: false,
80
+ },
81
+ }),
82
+ );
83
+
84
+ await act(() => leave.click());
85
+ expect(state.reads.at(-1)).toBeNull();
86
+});
apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts
new
+51
@@ -0,0 +1,51 @@
1
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
2
+import { useRef, useState } from "react";
3
+
4
+import { useStableCallback } from "~/hooks/useStableCallback";
5
+import { pullRequestEnvironment } from "~/state/pullRequests";
6
+import { useEnvironmentQuery } from "~/state/query";
7
+
8
+import { pullRequestPanelReference } from "./usePullRequestDetail";
9
+
10
+const INTENT_DELAY_MS = 150;
11
+
12
+interface PullRequestIntentTarget {
13
+ readonly environmentId: EnvironmentId;
14
+ readonly projectId: ProjectId;
15
+ readonly host: string;
16
+ readonly repository: string;
17
+ readonly number: number;
18
+}
19
+
20
+/**
21
+ * Reads the detail a row's panel will ask for once the pointer or focus rests on it, so the
22
+ * click paints from it. Passing over rows asks the host nothing, and leaving a row stops reading it.
23
+ */
24
+export function usePullRequestIntentPrefetch(
25
+ isListed: (target: PullRequestIntentTarget) => boolean,
26
+) {
27
+ const [target, setTarget] = useState<PullRequestIntentTarget | null>(null);
28
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
29
+ // A removed row fires no leave event.
30
+ const listed = target !== null && isListed(target);
31
+ if (target !== null && !listed) setTarget(null);
32
+ useEnvironmentQuery(
33
+ target === null || !listed
34
+ ? null
35
+ : pullRequestEnvironment.detail({
36
+ environmentId: target.environmentId,
37
+ input: {
38
+ ...pullRequestPanelReference({ ...target, host: target.host.toLowerCase() }),
39
+ allowStale: false,
40
+ },
41
+ }),
42
+ );
43
+ return useStableCallback((next: PullRequestIntentTarget | null) => {
44
+ clearTimeout(timer.current);
45
+ if (next === null) {
46
+ setTarget(null);
47
+ return;
48
+ }
49
+ timer.current = setTimeout(() => setTarget(next), INTENT_DELAY_MS);
50
+ });
51
+}
apps/web/src/connection/storage.browser.test.ts
new
+72
@@ -0,0 +1,72 @@
1
+import { Persistence } from "@t3tools/client-runtime/platform";
2
+import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence";
3
+import { EnvironmentId } from "@t3tools/contracts";
4
+import { describe, expect, it } from "@effect/vitest";
5
+import * as Context from "effect/Context";
6
+import * as Effect from "effect/Effect";
7
+import * as Layer from "effect/Layer";
8
+import * as Option from "effect/Option";
9
+import { TestClock } from "effect/testing";
10
+
11
+import * as ConnectionStorage from "./storage";
12
+
13
+describe("IndexedDB query cache", () => {
14
+ it.effect("round trips per environment and clears with the environment", () =>
15
+ Effect.gen(function* () {
16
+ const store = (yield* EnvironmentQueryStore)!;
17
+ const first = EnvironmentId.make("query-first");
18
+ yield* store.save(first, "pr", "cached");
19
+ expect(yield* store.load(first, "pr")).toEqual(Option.some("cached"));
20
+ expect(yield* store.load(EnvironmentId.make("query-second"), "pr")).toEqual(Option.none());
21
+ yield* (yield* Persistence.EnvironmentCacheStore).clear(first);
22
+ expect(yield* store.load(first, "pr")).toEqual(Option.none());
23
+ }).pipe(Effect.provide(ConnectionStorage.layer)),
24
+ );
25
+
26
+ it.effect("two tabs' bursts of saves end within 256 rows and 32 MiB", () =>
27
+ Effect.gen(function* () {
28
+ const openTab = Layer.build(Layer.fresh(ConnectionStorage.layer)).pipe(
29
+ Effect.map((context) => Context.get(context, EnvironmentQueryStore)!),
30
+ );
31
+ const tabs = [yield* openTab, yield* openTab];
32
+ const environmentId = EnvironmentId.make("query-bounded");
33
+ const saveAll = (keys: ReadonlyArray<string>, payload: (key: string) => string) =>
34
+ Effect.forEach(keys, (key, index) =>
35
+ tabs[index % 2]!.save(environmentId, key, payload(key)).pipe(
36
+ Effect.andThen(TestClock.adjust("1 millis")),
37
+ ),
38
+ );
39
+ const loadAll = (keys: ReadonlyArray<string>) =>
40
+ Effect.forEach(keys, (key) => tabs[0]!.load(environmentId, key)).pipe(
41
+ Effect.map((loaded) => loaded.filter(Option.isSome).map((stored) => stored.value)),
42
+ );
43
+
44
+ const rows = Array.from({ length: 300 }, (_, index) => `row-${index}`);
45
+ yield* saveAll(rows, (key) => key);
46
+ const keptRows = yield* loadAll(rows);
47
+ expect(keptRows.length).toBeLessThanOrEqual(256);
48
+ expect(keptRows).not.toContain("row-0");
49
+ expect(keptRows).toContain("row-299");
50
+
51
+ const answer = "x".repeat(4 * 1024 * 1024);
52
+ const large = Array.from({ length: 9 }, (_, index) => `large-${index}`);
53
+ yield* saveAll(large, () => answer);
54
+ const keptBytes = (yield* loadAll([...rows, ...large])).reduce(
55
+ (total, payload) => total + payload.length,
56
+ 0,
57
+ );
58
+ expect(keptBytes).toBeLessThanOrEqual(32 * 1024 * 1024);
59
+ expect(yield* tabs[1]!.load(environmentId, "large-8")).toEqual(Option.some(answer));
60
+ }).pipe(Effect.scoped),
61
+ );
62
+
63
+ it.effect("drops the older copy when an answer grows too large to keep", () =>
64
+ Effect.gen(function* () {
65
+ const store = (yield* EnvironmentQueryStore)!;
66
+ const environmentId = EnvironmentId.make("query-oversize");
67
+ yield* store.save(environmentId, "diff", "small");
68
+ yield* store.save(environmentId, "diff", "x".repeat(4 * 1024 * 1024 + 1));
69
+ expect(yield* store.load(environmentId, "diff")).toEqual(Option.none());
70
+ }).pipe(Effect.provide(ConnectionStorage.layer)),
71
+ );
72
+});
apps/web/src/connection/storage.ts
+134
-1
@@ -28,7 +28,9 @@ import {
28
pullRequestRoutingConnectionKey,
29
pullRequestRoutingPermissionFor,
30
} from "@t3tools/client-runtime/connection";
31
+import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence";
32
import { EnvironmentId, ServerConfig, ThreadId, VcsListRefsResult } from "@t3tools/contracts";
33
+import * as Clock from "effect/Clock";
34
import * as Context from "effect/Context";
35
import * as Effect from "effect/Effect";
36
import * as Layer from "effect/Layer";
@@ -41,12 +43,23 @@ import * as Stream from "effect/Stream";
43
import { projectFaviconCache } from "../assets/projectFaviconCache";
44
45
const DATABASE_NAME = "t3code:connection-runtime";
44
-const DATABASE_VERSION = 4;
46
+const DATABASE_VERSION = 5;
47
const CATALOG_STORE_NAME = "catalog";
48
const SHELL_STORE_NAME = "shell";
49
const THREAD_STORE_NAME = "thread";
50
const SERVER_CONFIG_STORE_NAME = "server-config";
51
const VCS_REFS_STORE_NAME = "vcs-refs";
52
+const QUERY_STORE_NAME = "query";
53
+const QUERY_UPDATED_INDEX_NAME = "environment-updated";
54
+const QUERY_MAX_ROWS = 256;
55
+const QUERY_MAX_BYTES = 32 * 1024 * 1024;
56
+const QUERY_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
57
+const QUERY_MAX_AGE_MS = 30 * 24 * 60 * 60_000;
58
+// A stats answer saves one row per listed PR, so the bounds index is walked once per batch of
59
+// saves. Each walk trims a batch below the caps, so the caps hold between walks. The batch count
60
+// lives in the database, so tabs sharing it share one count.
61
+const QUERY_PRUNE_BATCH_ROWS = 32;
62
+const QUERY_PRUNE_BATCH_BYTES = 1024 * 1024;
63
const CATALOG_KEY = "document";
64
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
65
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
@@ -65,6 +78,10 @@ const StoredVcsRefs = Schema.Struct({
78
refs: VcsListRefsResult,
79
});
80
const StoredVcsRefsJson = Schema.fromJsonString(StoredVcsRefs);
81
+const isStoredQuery = Schema.is(
82
+ Schema.Struct({ environmentId: Schema.String, payload: Schema.String, updatedAt: Schema.Number }),
83
+);
84
+const isQueryBatch = Schema.is(Schema.Struct({ rows: Schema.Number, bytes: Schema.Number }));
85
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
86
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
87
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
@@ -137,6 +154,11 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* (
154
if (!request.result.objectStoreNames.contains(VCS_REFS_STORE_NAME)) {
155
request.result.createObjectStore(VCS_REFS_STORE_NAME);
156
}
157
+ if (!request.result.objectStoreNames.contains(QUERY_STORE_NAME)) {
158
+ request.result
159
+ .createObjectStore(QUERY_STORE_NAME)
160
+ .createIndex(QUERY_UPDATED_INDEX_NAME, ["environmentId", "updatedAt", "bytes"]);
161
+ }
162
});
163
request.addEventListener("error", () => {
164
resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
@@ -326,6 +348,75 @@ function removeDatabaseValuesInRangeOnConnection(
348
}).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
349
}
350
351
+// Mirrors mobile's pull-request cache bounds, per environment.
352
+function saveQueryOnConnection(
353
+ database: IDBDatabase,
354
+ environmentId: EnvironmentId,
355
+ key: string,
356
+ payload: string,
357
+ updatedAt: number,
358
+) {
359
+ return Effect.callback<void, ConnectionTransientError>((resume) => {
360
+ try {
361
+ const bytes = new TextEncoder().encode(payload).length;
362
+ const transaction = database.transaction(QUERY_STORE_NAME, "readwrite");
363
+ transaction.addEventListener("abort", () => {
364
+ resume(
365
+ Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
366
+ );
367
+ });
368
+ transaction.addEventListener("complete", () => {
369
+ resume(Effect.void);
370
+ });
371
+ const store = transaction.objectStore(QUERY_STORE_NAME);
372
+ // An answer too large to keep must not leave its older copy to paint on the next start.
373
+ if (bytes > QUERY_MAX_PAYLOAD_BYTES) {
374
+ store.delete(queryCacheKey(environmentId, key));
375
+ return;
376
+ }
377
+ store.put({ environmentId, payload, updatedAt, bytes }, queryCacheKey(environmentId, key));
378
+ const batchKey = queryBatchKey(environmentId);
379
+ const batchRequest = store.get(batchKey);
380
+ batchRequest.addEventListener("success", () => {
381
+ const batch: unknown = batchRequest.result;
382
+ const rows = (isQueryBatch(batch) ? batch.rows : 0) + 1;
383
+ const written = (isQueryBatch(batch) ? batch.bytes : 0) + bytes;
384
+ if (
385
+ isQueryBatch(batch) &&
386
+ rows < QUERY_PRUNE_BATCH_ROWS &&
387
+ written < QUERY_PRUNE_BATCH_BYTES
388
+ ) {
389
+ store.put({ rows, bytes: written }, batchKey);
390
+ return;
391
+ }
392
+ store.put({ rows: 0, bytes: 0 }, batchKey);
393
+ const request = store
394
+ .index(QUERY_UPDATED_INDEX_NAME)
395
+ .openKeyCursor(IDBKeyRange.bound([environmentId], [environmentId, []]), "prev");
396
+ let kept = 0;
397
+ let totalBytes = 0;
398
+ request.addEventListener("success", () => {
399
+ const cursor = request.result;
400
+ if (cursor === null) return;
401
+ const [, rowUpdatedAt, rowBytes] = cursor.key as [string, number, number];
402
+ kept += 1;
403
+ totalBytes += rowBytes;
404
+ if (
405
+ kept > QUERY_MAX_ROWS - QUERY_PRUNE_BATCH_ROWS ||
406
+ totalBytes > QUERY_MAX_BYTES - QUERY_PRUNE_BATCH_BYTES ||
407
+ rowUpdatedAt < updatedAt - QUERY_MAX_AGE_MS
408
+ ) {
409
+ store.delete(cursor.primaryKey);
410
+ }
411
+ cursor.continue();
412
+ });
413
+ });
414
+ } catch (cause) {
415
+ resume(Effect.fail(catalogError("write", cause)));
416
+ }
417
+ }).pipe(Effect.withSpan("web.connectionStorage.saveQuery"));
418
+}
419
+
420
function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
421
return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
422
}
@@ -361,6 +452,14 @@ function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
452
return `${environmentId}:${threadId}`;
453
}
454
455
+function queryCacheKey(environmentId: EnvironmentId, key: string) {
456
+ return `${environmentId}:v1:${key}`;
457
+}
458
+
459
+function queryBatchKey(environmentId: EnvironmentId) {
460
+ return `${environmentId}:batch`;
461
+}
462
+
463
function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
464
return `${environmentId}:${cwd}`;
465
}
@@ -955,12 +1054,45 @@ export const layer = Layer.effectContext(
1054
VCS_REFS_STORE_NAME,
1055
IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1056
),
1057
+ removeDatabaseValuesInRange(
1058
+ database,
1059
+ QUERY_STORE_NAME,
1060
+ IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
1061
+ ),
1062
],
1063
{ concurrency: "unbounded", discard: true },
1064
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
1065
}),
1066
});
1067
1068
+ const queryStore: NonNullable<typeof EnvironmentQueryStore.Service> = {
1069
+ load: Effect.fn("EnvironmentQueryStore.load")(
1070
+ function* (environmentId, key) {
1071
+ const stored = yield* readDatabaseValue(
1072
+ database,
1073
+ QUERY_STORE_NAME,
1074
+ queryCacheKey(environmentId, key),
1075
+ );
1076
+ const now = yield* Clock.currentTimeMillis;
1077
+ return isStoredQuery(stored) &&
1078
+ stored.environmentId === environmentId &&
1079
+ stored.updatedAt >= now - QUERY_MAX_AGE_MS
1080
+ ? Option.some(stored.payload)
1081
+ : Option.none();
1082
+ },
1083
+ Effect.catch(() => Effect.succeedNone),
1084
+ ),
1085
+ save: (environmentId, key, payload) =>
1086
+ Clock.currentTimeMillis.pipe(
1087
+ Effect.flatMap((now) =>
1088
+ withDatabase(database, (opened) =>
1089
+ saveQueryOnConnection(opened, environmentId, key, payload, now),
1090
+ ),
1091
+ ),
1092
+ Effect.catch(() => Effect.logWarning("Offline query database save failed")),
1093
+ ),
1094
+ };
1095
+
1096
return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
1097
Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
1098
Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
@@ -968,6 +1100,7 @@ export const layer = Layer.effectContext(
1100
Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
1101
Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
1102
Context.add(Persistence.EnvironmentCacheStore, cacheStore),
1103
+ Context.add(EnvironmentQueryStore, queryStore),
1104
);
1105
}),
1106
);
packages/client-runtime/src/state/pullRequestStatsPersistence.ts
+4
-2
@@ -19,8 +19,10 @@ export function persistPullRequestStats(): QueryPersistence<PullRequestListStats
19
load: Effect.fn("pullRequestStatsPersistence.load")(
20
function* (environmentId, key) {
21
const [, input] = yield* Schema.decodeEffect(requestKey)(key);
22
- const rows = yield* Effect.forEach(input.refs, (ref) =>
23
- row.load(environmentId, statKey(ref)),
22
+ const rows = yield* Effect.forEach(
23
+ input.refs,
24
+ (ref) => row.load(environmentId, statKey(ref)),
25
+ { concurrency: "unbounded" },
26
);
27
const stats = rows.flatMap((value) => (Option.isSome(value) ? [value.value] : []));
28
return stats.length ? Option.some({ stats }) : Option.none();
packages/client-runtime/src/state/pullRequests.ts
+2
-1
@@ -21,7 +21,7 @@ import {
21
type PullRequestRef,
22
type PullRequestMergeMethod,
23
PullRequestOperationError,
24
- type PullRequestSummary,
24
+ PullRequestSummary,
25
type VcsStatusResult,
26
} from "@t3tools/contracts";
27
import * as Effect from "effect/Effect";
@@ -147,6 +147,7 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
147
const routedRequest = createPullRequestRouter();
148
return createEnvironmentRpcQueryAtomFamily(runtime, {
149
label: "environment-data:pull-requests:linked-summary",
150
+ persistence: persistQuery(PullRequestSummary),
151
tag: WS_METHODS.pullRequestsSummary,
152
execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
153
staleTimeMs: 60_000,
packages/client-runtime/src/state/runtime.test.ts
+29
-3
@@ -1370,19 +1370,20 @@ describe("persisted environment queries", () => {
1370
Effect.scoped(
1371
Effect.gen(function* () {
1372
let saved = Option.none<string>();
1373
+ const saves = yield* Queue.unbounded<string>();
1374
const persistence: QueryPersistence<string> = {
1375
load: () => Effect.sync(() => saved),
1376
save: (_environmentId, _key, value) =>
1377
Effect.sync(() => {
1378
saved = Option.some(value);
1378
- }),
1379
+ }).pipe(Effect.andThen(Queue.offer(saves, value))),
1380
};
1381
const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1382
persistence,
1383
});
1384
const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1385
expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1385
- expect(saved).toEqual(Option.some("first"));
1386
+ expect(yield* Queue.take(saves)).toBe("first");
1387
1388
const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1389
persistence,
@@ -1393,11 +1394,36 @@ describe("persisted environment queries", () => {
1394
yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1395
yield* Effect.yieldNow;
1396
expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1396
- expect(saved).toEqual(Option.some("updated"));
1397
+ expect(yield* Queue.take(saves)).toBe("updated");
1398
}),
1399
),
1400
);
1401
1402
+ it.effect("answers readers while its save is pending, and ends the save with the query", () =>
1403
+ Effect.scoped(
1404
+ Effect.gen(function* () {
1405
+ const saveEnded = Latch.makeUnsafe();
1406
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), {
1407
+ persistence: {
1408
+ load: () => Effect.succeedNone,
1409
+ // The registry's scheduler stops on dispose, so signal synchronously.
1410
+ save: () =>
1411
+ Effect.never.pipe(
1412
+ Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe())),
1413
+ ),
1414
+ },
1415
+ });
1416
+ yield* Effect.scoped(
1417
+ Effect.gen(function* () {
1418
+ const registry = yield* mountEnvironmentQuery(harness.atom);
1419
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1420
+ }),
1421
+ );
1422
+ yield* saveEnded.await;
1423
+ }),
1424
+ ),
1425
+ );
1426
+
1427
it.effect("hands each server answer to onAnswer before readers see it", () =>
1428
Effect.scoped(
1429
Effect.gen(function* () {
packages/client-runtime/src/state/runtime.ts
+5
-1
@@ -781,8 +781,12 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
781
return cached.value;
782
}
783
if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
784
+ // Readers must not wait on the disk: web saves one IndexedDB row per listed PR's stats.
785
+ // The save ends with the query, so a removed environment's cache stays cleared.
786
return yield* answer().pipe(
785
- Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
787
+ Effect.tap((value) =>
788
+ persistence.save(target.environmentId, cacheKey, value).pipe(Effect.forkScoped),
789
+ ),
790
);
791
});
792
})
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+80
-5
@@ -820,6 +820,74 @@ layer("GitHubPullRequestApi.layer", (it) => {
820
}),
821
);
822
823
+ it.effect("reads commit stats alongside later activity pages", () =>
824
+ Effect.gen(function* () {
825
+ const laterPageStarted = yield* Deferred.make<void>();
826
+ const statsStarted = yield* Deferred.make<void>();
827
+ const activityPage = (head: boolean) => ({
828
+ data: {
829
+ repository: {
830
+ pullRequest: {
831
+ ...(head
832
+ ? {
833
+ author: null,
834
+ commits: {
835
+ nodes: [
836
+ {
837
+ commit: {
838
+ id: "node-regular",
839
+ oid: "regular",
840
+ messageHeadline: "regular",
841
+ committedDate: "2026-07-05T00:00:00Z",
842
+ parents: { totalCount: 1 },
843
+ authors: { nodes: [] },
844
+ },
845
+ },
846
+ ],
847
+ },
848
+ }
849
+ : {}),
850
+ comments: {
851
+ nodes: [],
852
+ pageInfo: head ? { hasNextPage: true, endCursor: "c1" } : lastPage,
853
+ },
854
+ reviews: { nodes: [], pageInfo: lastPage },
855
+ },
856
+ },
857
+ },
858
+ });
859
+ mockedExecute.mockImplementation((call) => {
860
+ if (matches(call, "PullRequestCommitStats")) {
861
+ return Deferred.succeed(statsStarted, undefined).pipe(
862
+ Effect.andThen(Deferred.await(laterPageStarted)),
863
+ Effect.as(
864
+ output(
865
+ encodeJson({
866
+ data: {
867
+ nodes: [{ __typename: "Commit", oid: "regular", additions: 3, deletions: 1 }],
868
+ },
869
+ }),
870
+ ),
871
+ ),
872
+ );
873
+ }
874
+ const head = call.kind === "graphql" && call.variables?.["head"] === true;
875
+ return head
876
+ ? Effect.succeed(output(encodeJson(activityPage(true))))
877
+ : Deferred.succeed(laterPageStarted, undefined).pipe(
878
+ Effect.andThen(Deferred.await(statsStarted)),
879
+ Effect.as(output(encodeJson(activityPage(false)))),
880
+ );
881
+ });
882
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
883
+
884
+ const activity = yield* cli.getPullRequestActivity(pullRequestInput);
885
+
886
+ expect(activity.commits[0]).toMatchObject({ additions: 3, deletions: 1 });
887
+ expect(mockedExecute).toHaveBeenCalledTimes(3);
888
+ }),
889
+ );
890
+
891
it.effect("loads the complete hover card with one GraphQL request", () =>
892
Effect.gen(function* () {
893
mockedExecute.mockReturnValueOnce(
@@ -3299,7 +3367,10 @@ layer("GitHubPullRequestApi.layer", (it) => {
3367
Effect.succeed(output(reviewThreadsPage([thread("T3", "c3")], null))),
3368
);
3369
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3302
- const read = cli.listReviewThreadComments(pullRequestInput);
3370
+ const read = cli.listReviewThreadComments({
3371
+ ...pullRequestInput,
3372
+ repository: `acme/refused-threads-${later}`,
3373
+ });
3374
const conversation = yield* read;
3375
expect(
3376
variablesOf("ReviewThreads").map((v) => [v["after"], v["requestedReviewers"]]),
@@ -3327,7 +3398,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3398
yield* read;
3399
expect(variablesOf("ReviewThreads").at(-1)).toMatchObject({
3400
after: null,
3330
- requestedReviewers: 50,
3401
+ requestedReviewers: 0,
3402
});
3403
}),
3404
);
@@ -3460,7 +3531,10 @@ layer("GitHubPullRequestApi.layer", (it) => {
3531
),
3532
);
3533
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3463
- const read = cli.getPullRequestDetail(pullRequestInput);
3534
+ const read = cli.getPullRequestDetail({
3535
+ ...pullRequestInput,
3536
+ repository: `acme/refused-checks-${refused}`,
3537
+ });
3538
const detail = yield* read;
3539
expect(detail.reviewRequestLogins).toEqual([]);
3540
expect(detail.reviewRequestTeams).toEqual([]);
@@ -3480,7 +3554,8 @@ layer("GitHubPullRequestApi.layer", (it) => {
3554
if (refused) {
3555
mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(coreResponse()))));
3556
yield* read;
3483
- expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 100 });
3557
+ expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 0 });
3558
+ expect(mockedExecute).toHaveBeenCalledTimes(4);
3559
}
3560
}),
3561
);
@@ -3514,7 +3589,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3589
const error = yield* Effect.flip(
3590
cli.getPullRequestDetail({
3591
cwd: "/w",
3517
- repository: "acme/web",
3592
+ repository: `acme/head-changed-${refused}`,
3593
host: "github.com",
3594
number: 7,
3595
}),
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+54
-29
@@ -1422,6 +1422,31 @@ export const make = Effect.gen(function* () {
1422
};
1423
});
1424
1425
+ // GitHub refuses a requested-reviewer list holding a team the viewer cannot see. Remember the
1426
+ // refusal so later reads of that pull request skip straight to the read without reviewers.
1427
+ const refusedReviewers = yield* Cache.make({
1428
+ capacity: 512,
1429
+ timeToLive: "10 minutes",
1430
+ lookup: (_key: string) => Effect.void,
1431
+ });
1432
+ const readRequestedReviewers = Effect.fn("GitHubPullRequestApi.readRequestedReviewers")(
1433
+ function* <A, E, R>(
1434
+ input: { readonly host: string; readonly repository: string; readonly number: number },
1435
+ wanted: number,
1436
+ read: (requestedReviewers: number) => Effect.Effect<A, E, R>,
1437
+ ) {
1438
+ const host = normalizeHost(input.host);
1439
+ const { fingerprint } = yield* api.credential(host);
1440
+ const key = `${fingerprint}\0${host}\0${input.repository.toLowerCase()}\0${input.number}`;
1441
+ if (yield* Cache.has(refusedReviewers, key)) return yield* read(0);
1442
+ return yield* read(wanted).pipe(
1443
+ Effect.catchIf(isRefusedRequestedReviewersOnly, () =>
1444
+ Cache.set(refusedReviewers, key, undefined).pipe(Effect.andThen(read(0))),
1445
+ ),
1446
+ );
1447
+ },
1448
+ );
1449
+
1450
const getPullRequestDetail: GitHubPullRequestApi["Service"]["getPullRequestDetail"] = (input) => {
1451
const { owner, name } = parseRepositorySelector(input.repository);
1452
const operation = "getPullRequestDetail";
@@ -1436,8 +1461,7 @@ export const make = Effect.gen(function* () {
1461
});
1462
return SourceControlRateLimit.Interactive.pipe(
1463
Effect.flatMap((allowReserve) =>
1439
- read(100).pipe(
1440
- Effect.catchIf(isRefusedRequestedReviewersOnly, () => read(0)),
1464
+ readRequestedReviewers(input, 100, read).pipe(
1465
graphql({ ...input, operation, allowReserve }),
1466
Effect.map(toPullRequestCore),
1467
Effect.flatMap(found({ ...input, operation })),
@@ -2031,7 +2055,9 @@ export const make = Effect.gen(function* () {
2055
let withComments = true;
2056
let withReviews = true;
2057
const target = { ...input, operation: "getPullRequestActivity" };
2034
- for (let page = 0; page < REVIEW_THREAD_PAGES && (withComments || withReviews); page++) {
2058
+ const readPage = Effect.fn("GitHubPullRequestApi.readActivityPage")(function* (
2059
+ page: number,
2060
+ ) {
2061
const read: GitHubPullRequestActivityPage = yield* client
2062
.PullRequestActivity({
2063
owner,
@@ -2058,16 +2084,28 @@ export const make = Effect.gen(function* () {
2084
reviewsAfter = read.nextReviewsCursor;
2085
withComments = withComments && commentsAfter !== null;
2086
withReviews = withReviews && reviewsAfter !== null;
2061
- }
2087
+ });
2088
+ yield* readPage(0);
2089
+ const laterPages = Effect.gen(function* () {
2090
+ for (let page = 1; page < REVIEW_THREAD_PAGES; page++) {
2091
+ if (!withComments && !withReviews) return;
2092
+ yield* readPage(page);
2093
+ }
2094
+ });
2095
const emptyStats = toPullRequestCommitStats({ nodes: [] });
2063
- const commitStats =
2064
- nonMergeCommitIds.length === 0
2065
- ? emptyStats
2066
- : yield* client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe(
2067
- graphql(target),
2068
- Effect.map(toPullRequestCommitStats),
2069
- Effect.orElseSucceed(() => emptyStats),
2070
- );
2096
+ const [, commitStats] = yield* Effect.all(
2097
+ [
2098
+ laterPages,
2099
+ nonMergeCommitIds.length === 0
2100
+ ? Effect.succeed(emptyStats)
2101
+ : client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe(
2102
+ graphql(target),
2103
+ Effect.map(toPullRequestCommitStats),
2104
+ Effect.orElseSucceed(() => emptyStats),
2105
+ ),
2106
+ ],
2107
+ { concurrency: 2 },
2108
+ );
2109
return {
2110
author,
2111
comments: remarks.toSorted((left, right) =>
@@ -2157,25 +2195,12 @@ export const make = Effect.gen(function* () {
2195
function* (input) {
2196
const { owner, name } = parseRepositorySelector(input.repository);
2197
const target = { ...input, operation: "listReviewThreadComments" };
2160
- let requestedReviewers = 50;
2198
const threadPage = (
2199
after: string | null,
2163
- ): Effect.Effect<GitHubReviewThreadPage, GitHubPullRequestApiError> => {
2164
- const read = () =>
2165
- client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers });
2166
- return read().pipe(
2167
- Effect.catchIf(
2168
- (error) => requestedReviewers > 0 && isRefusedRequestedReviewersOnly(error),
2169
- () => {
2170
- requestedReviewers = 0;
2171
- return read();
2172
- },
2173
- ),
2174
- graphql(target),
2175
- Effect.map(toReviewThreadPage),
2176
- Effect.flatMap(found(target)),
2177
- );
2178
- };
2200
+ ): Effect.Effect<GitHubReviewThreadPage, GitHubPullRequestApiError> =>
2201
+ readRequestedReviewers(input, 50, (requestedReviewers) =>
2202
+ client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers }),
2203
+ ).pipe(graphql(target), Effect.map(toReviewThreadPage), Effect.flatMap(found(target)));
2204
const entries: GitHubReviewThreadEntry[] = [];
2205
const avatarsByLogin = new Map<string, string>();
2206
const botLogins = new Set<string>();