0 && "**:pointer-events-none")}>
- {groups.map((group) => (
+ {shownGroups.map((group) => (
- {group.label ?
: null}
+ {group.label ? (
+
+ ) : null}
{group.entries.map((entry) => {
const entryKey = pullRequestEntryKey(entry);
const environmentLabel = environmentLabels?.get(entry.environmentId);
@@ -102,6 +127,7 @@ export function PullRequestListGroups({
selected.number === entry.number
}
onSelect={onSelect}
+ onIntent={onIntent}
hostActions={hostActionsOf(entry)}
onActed={onActed}
closing={closingKeys.has(entryKey)}
diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx
index 3b4d1f84c01d9..71fbf1100d554 100644
--- a/apps/web/src/components/pullRequest/PullRequestRow.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx
@@ -78,6 +78,7 @@ function PullRequestRowImpl({
statsKey,
statsRef,
onSelect,
+ onIntent,
hostActions,
onActed,
closing = false,
@@ -94,6 +95,8 @@ function PullRequestRowImpl({
statsKey?: string;
statsRef?: RefCallback
;
onSelect: (entry: PullRequestRowTarget) => void;
+ /** The row the pointer or focus rests on, or null when it leaves. */
+ onIntent?: (entry: PullRequestRowTarget | null) => void;
hostActions: ReadonlySet;
onActed: (result: PullRequestSpeedActionResult) => void;
closing?: boolean;
@@ -115,6 +118,14 @@ function PullRequestRowImpl({
type="button"
aria-current={selected ? "true" : undefined}
onClick={() => onSelect(entry)}
+ onPointerEnter={() => onIntent?.(entry)}
+ onPointerLeave={(event) => {
+ if (event.currentTarget !== document.activeElement) onIntent?.(null);
+ }}
+ onFocus={() => onIntent?.(entry)}
+ onBlur={(event) => {
+ if (!event.currentTarget.matches(":hover")) onIntent?.(null);
+ }}
className={cn(
PULL_REQUEST_ROW_CLASS,
PAGE_ROW_CLASS,
diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
index 1b3d1bc74c186..0fc32bce3257a 100644
--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
@@ -64,6 +64,8 @@ import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu";
import { INVOLVEMENT_TABS, SORT_OPTIONS, STATE_TABS } from "./pullRequestListOptions";
import { PullRequestsColumn } from "./PullRequestsColumn";
import { PullRequestListGroups } from "./PullRequestListGroups";
+import { pullRequestPanelReference } from "./usePullRequestDetail";
+import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch";
import {
usePullRequestDisplayGroups,
usePullRequestQueryFilters,
@@ -1080,6 +1082,9 @@ export function PullRequestsPage() {
),
);
+ const prefetchEntry = usePullRequestIntentPrefetch((entry) =>
+ listedPullRequestsBySurface.has(pullRequestListEntryId(entry)),
+ );
const selectEntry = (entry: PullRequestRowTarget) => {
if (rightPanelRef === null) return;
useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
@@ -1184,6 +1189,7 @@ export function PullRequestsPage() {
showProvider={showProvider}
statsRef={registerStatsRow}
onSelect={selectEntry}
+ onIntent={prefetchEntry}
hostActionsOf={hostActionsOf}
onActed={onSpeedAction}
closingKeys={closingKeys}
@@ -1528,14 +1534,10 @@ export function PullRequestsPage() {
selectedEnvironmentId: panelEnvironmentId,
});
}}
- reference={{
+ reference={pullRequestPanelReference({
+ ...renderedPullRequestSurface,
projectId: renderedPullRequestSurface.projectId as ProjectId,
- repository: renderedPullRequestSurface.repository,
- number: renderedPullRequestSurface.number,
- ...(renderedPullRequestSurface.host
- ? { host: renderedPullRequestSurface.host }
- : {}),
- }}
+ })}
listEntry={
listedPullRequestsBySurface.get(
pullRequestListEntryId(renderedPullRequestSurface),
diff --git a/apps/web/src/components/pullRequest/usePullRequestDetail.ts b/apps/web/src/components/pullRequest/usePullRequestDetail.ts
index 7451ee38c5fee..7d6ab0c7a6154 100644
--- a/apps/web/src/components/pullRequest/usePullRequestDetail.ts
+++ b/apps/web/src/components/pullRequest/usePullRequestDetail.ts
@@ -4,6 +4,7 @@ import {
type EnvironmentId,
type PullRequestListEntry,
type PullRequestRef,
+ type ProjectId,
} from "@t3tools/contracts";
import { useState } from "react";
@@ -22,6 +23,21 @@ import {
resolveDisplayedPullRequestDetail,
} from "./pullRequestDetail.logic";
+// Query atoms key on JSON order, so the panel and the row prefetch must build the ref here.
+export function pullRequestPanelReference(target: {
+ readonly projectId: ProjectId;
+ readonly repository: string;
+ readonly number: number;
+ readonly host?: string | undefined;
+}): PullRequestRef {
+ return {
+ projectId: target.projectId,
+ repository: target.repository,
+ number: target.number,
+ ...(target.host ? { host: target.host } : {}),
+ };
+}
+
export function pullRequestRefKey(reference: PullRequestRef) {
return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
}
diff --git a/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx
new file mode 100644
index 0000000000000..366fb4cfe76e4
--- /dev/null
+++ b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx
@@ -0,0 +1,86 @@
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { expect, it, vi } from "vite-plus/test";
+
+const state = vi.hoisted(() => ({ reads: [] as Array }));
+vi.mock(import("~/state/pullRequests"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ pullRequestEnvironment: {
+ ...actual.pullRequestEnvironment,
+ detail: ((target: unknown) => target) as never,
+ },
+ };
+});
+vi.mock(import("~/state/query"), async (original) => ({
+ ...(await original()),
+ useEnvironmentQuery: ((target: unknown) => {
+ if (target !== null || state.reads.length > 0) state.reads.push(target);
+ return {};
+ }) as never,
+}));
+
+import { act, fakeTimers, render } from "../../../test/render";
+import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch";
+
+const environmentId = EnvironmentId.make("environment");
+const row = {
+ environmentId,
+ projectId: ProjectId.make("project"),
+ host: "GitHub.com",
+ repository: "owner/repo",
+ number: 7,
+};
+
+function Rows() {
+ const prefetch = usePullRequestIntentPrefetch(() => true);
+ return (
+ <>
+
+
+ >
+ );
+}
+
+it("reads the panel's detail once intent rests on a row for 150 ms", async () => {
+ state.reads = [];
+ await using screen = await render(, {
+ // A bare hook probe; nothing here navigates.
+ router: false,
+ });
+ using _timers = fakeTimers({ now: 0 });
+ const rest = screen.getByRole("button", { name: "rest" }).element() as HTMLElement;
+ const leave = screen.getByRole("button", { name: "leave" }).element() as HTMLElement;
+
+ await act(() => {
+ rest.click();
+ leave.click();
+ });
+ await act(() => vi.advanceTimersByTime(1_000));
+ expect(state.reads).toEqual([]);
+
+ await act(() => rest.click());
+ await act(() => vi.advanceTimersByTime(149));
+ expect(state.reads).toEqual([]);
+ await act(() => vi.advanceTimersByTime(1));
+ // Query atoms key on JSON order: this is the order the PRs page panel reads.
+ expect(JSON.stringify(state.reads.at(-1))).toBe(
+ JSON.stringify({
+ environmentId,
+ input: {
+ projectId: row.projectId,
+ repository: "owner/repo",
+ number: 7,
+ host: "github.com",
+ allowStale: false,
+ },
+ }),
+ );
+
+ await act(() => leave.click());
+ expect(state.reads.at(-1)).toBeNull();
+});
diff --git a/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts
new file mode 100644
index 0000000000000..a078ce2c94ff7
--- /dev/null
+++ b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts
@@ -0,0 +1,51 @@
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { useRef, useState } from "react";
+
+import { useStableCallback } from "~/hooks/useStableCallback";
+import { pullRequestEnvironment } from "~/state/pullRequests";
+import { useEnvironmentQuery } from "~/state/query";
+
+import { pullRequestPanelReference } from "./usePullRequestDetail";
+
+const INTENT_DELAY_MS = 150;
+
+interface PullRequestIntentTarget {
+ readonly environmentId: EnvironmentId;
+ readonly projectId: ProjectId;
+ readonly host: string;
+ readonly repository: string;
+ readonly number: number;
+}
+
+/**
+ * Reads the detail a row's panel will ask for once the pointer or focus rests on it, so the
+ * click paints from it. Passing over rows asks the host nothing, and leaving a row stops reading it.
+ */
+export function usePullRequestIntentPrefetch(
+ isListed: (target: PullRequestIntentTarget) => boolean,
+) {
+ const [target, setTarget] = useState(null);
+ const timer = useRef | undefined>(undefined);
+ // A removed row fires no leave event.
+ const listed = target !== null && isListed(target);
+ if (target !== null && !listed) setTarget(null);
+ useEnvironmentQuery(
+ target === null || !listed
+ ? null
+ : pullRequestEnvironment.detail({
+ environmentId: target.environmentId,
+ input: {
+ ...pullRequestPanelReference({ ...target, host: target.host.toLowerCase() }),
+ allowStale: false,
+ },
+ }),
+ );
+ return useStableCallback((next: PullRequestIntentTarget | null) => {
+ clearTimeout(timer.current);
+ if (next === null) {
+ setTarget(null);
+ return;
+ }
+ timer.current = setTimeout(() => setTarget(next), INTENT_DELAY_MS);
+ });
+}
diff --git a/apps/web/src/connection/storage.browser.test.ts b/apps/web/src/connection/storage.browser.test.ts
new file mode 100644
index 0000000000000..2b36f9827c84f
--- /dev/null
+++ b/apps/web/src/connection/storage.browser.test.ts
@@ -0,0 +1,72 @@
+import { Persistence } from "@t3tools/client-runtime/platform";
+import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence";
+import { EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it } from "@effect/vitest";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { TestClock } from "effect/testing";
+
+import * as ConnectionStorage from "./storage";
+
+describe("IndexedDB query cache", () => {
+ it.effect("round trips per environment and clears with the environment", () =>
+ Effect.gen(function* () {
+ const store = (yield* EnvironmentQueryStore)!;
+ const first = EnvironmentId.make("query-first");
+ yield* store.save(first, "pr", "cached");
+ expect(yield* store.load(first, "pr")).toEqual(Option.some("cached"));
+ expect(yield* store.load(EnvironmentId.make("query-second"), "pr")).toEqual(Option.none());
+ yield* (yield* Persistence.EnvironmentCacheStore).clear(first);
+ expect(yield* store.load(first, "pr")).toEqual(Option.none());
+ }).pipe(Effect.provide(ConnectionStorage.layer)),
+ );
+
+ it.effect("two tabs' bursts of saves end within 256 rows and 32 MiB", () =>
+ Effect.gen(function* () {
+ const openTab = Layer.build(Layer.fresh(ConnectionStorage.layer)).pipe(
+ Effect.map((context) => Context.get(context, EnvironmentQueryStore)!),
+ );
+ const tabs = [yield* openTab, yield* openTab];
+ const environmentId = EnvironmentId.make("query-bounded");
+ const saveAll = (keys: ReadonlyArray, payload: (key: string) => string) =>
+ Effect.forEach(keys, (key, index) =>
+ tabs[index % 2]!.save(environmentId, key, payload(key)).pipe(
+ Effect.andThen(TestClock.adjust("1 millis")),
+ ),
+ );
+ const loadAll = (keys: ReadonlyArray) =>
+ Effect.forEach(keys, (key) => tabs[0]!.load(environmentId, key)).pipe(
+ Effect.map((loaded) => loaded.filter(Option.isSome).map((stored) => stored.value)),
+ );
+
+ const rows = Array.from({ length: 300 }, (_, index) => `row-${index}`);
+ yield* saveAll(rows, (key) => key);
+ const keptRows = yield* loadAll(rows);
+ expect(keptRows.length).toBeLessThanOrEqual(256);
+ expect(keptRows).not.toContain("row-0");
+ expect(keptRows).toContain("row-299");
+
+ const answer = "x".repeat(4 * 1024 * 1024);
+ const large = Array.from({ length: 9 }, (_, index) => `large-${index}`);
+ yield* saveAll(large, () => answer);
+ const keptBytes = (yield* loadAll([...rows, ...large])).reduce(
+ (total, payload) => total + payload.length,
+ 0,
+ );
+ expect(keptBytes).toBeLessThanOrEqual(32 * 1024 * 1024);
+ expect(yield* tabs[1]!.load(environmentId, "large-8")).toEqual(Option.some(answer));
+ }).pipe(Effect.scoped),
+ );
+
+ it.effect("drops the older copy when an answer grows too large to keep", () =>
+ Effect.gen(function* () {
+ const store = (yield* EnvironmentQueryStore)!;
+ const environmentId = EnvironmentId.make("query-oversize");
+ yield* store.save(environmentId, "diff", "small");
+ yield* store.save(environmentId, "diff", "x".repeat(4 * 1024 * 1024 + 1));
+ expect(yield* store.load(environmentId, "diff")).toEqual(Option.none());
+ }).pipe(Effect.provide(ConnectionStorage.layer)),
+ );
+});
diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.ts
index 7d9db4afdc494..78b01fc6d4695 100644
--- a/apps/web/src/connection/storage.ts
+++ b/apps/web/src/connection/storage.ts
@@ -28,7 +28,9 @@ import {
pullRequestRoutingConnectionKey,
pullRequestRoutingPermissionFor,
} from "@t3tools/client-runtime/connection";
+import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence";
import { EnvironmentId, ServerConfig, ThreadId, VcsListRefsResult } from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -41,12 +43,23 @@ import * as Stream from "effect/Stream";
import { projectFaviconCache } from "../assets/projectFaviconCache";
const DATABASE_NAME = "t3code:connection-runtime";
-const DATABASE_VERSION = 4;
+const DATABASE_VERSION = 5;
const CATALOG_STORE_NAME = "catalog";
const SHELL_STORE_NAME = "shell";
const THREAD_STORE_NAME = "thread";
const SERVER_CONFIG_STORE_NAME = "server-config";
const VCS_REFS_STORE_NAME = "vcs-refs";
+const QUERY_STORE_NAME = "query";
+const QUERY_UPDATED_INDEX_NAME = "environment-updated";
+const QUERY_MAX_ROWS = 256;
+const QUERY_MAX_BYTES = 32 * 1024 * 1024;
+const QUERY_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
+const QUERY_MAX_AGE_MS = 30 * 24 * 60 * 60_000;
+// A stats answer saves one row per listed PR, so the bounds index is walked once per batch of
+// saves. Each walk trims a batch below the caps, so the caps hold between walks. The batch count
+// lives in the database, so tabs sharing it share one count.
+const QUERY_PRUNE_BATCH_ROWS = 32;
+const QUERY_PRUNE_BATCH_BYTES = 1024 * 1024;
const CATALOG_KEY = "document";
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
@@ -65,6 +78,10 @@ const StoredVcsRefs = Schema.Struct({
refs: VcsListRefsResult,
});
const StoredVcsRefsJson = Schema.fromJsonString(StoredVcsRefs);
+const isStoredQuery = Schema.is(
+ Schema.Struct({ environmentId: Schema.String, payload: Schema.String, updatedAt: Schema.Number }),
+);
+const isQueryBatch = Schema.is(Schema.Struct({ rows: Schema.Number, bytes: Schema.Number }));
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
@@ -137,6 +154,11 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* (
if (!request.result.objectStoreNames.contains(VCS_REFS_STORE_NAME)) {
request.result.createObjectStore(VCS_REFS_STORE_NAME);
}
+ if (!request.result.objectStoreNames.contains(QUERY_STORE_NAME)) {
+ request.result
+ .createObjectStore(QUERY_STORE_NAME)
+ .createIndex(QUERY_UPDATED_INDEX_NAME, ["environmentId", "updatedAt", "bytes"]);
+ }
});
request.addEventListener("error", () => {
resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
@@ -326,6 +348,75 @@ function removeDatabaseValuesInRangeOnConnection(
}).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));
}
+// Mirrors mobile's pull-request cache bounds, per environment.
+function saveQueryOnConnection(
+ database: IDBDatabase,
+ environmentId: EnvironmentId,
+ key: string,
+ payload: string,
+ updatedAt: number,
+) {
+ return Effect.callback((resume) => {
+ try {
+ const bytes = new TextEncoder().encode(payload).length;
+ const transaction = database.transaction(QUERY_STORE_NAME, "readwrite");
+ transaction.addEventListener("abort", () => {
+ resume(
+ Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")),
+ );
+ });
+ transaction.addEventListener("complete", () => {
+ resume(Effect.void);
+ });
+ const store = transaction.objectStore(QUERY_STORE_NAME);
+ // An answer too large to keep must not leave its older copy to paint on the next start.
+ if (bytes > QUERY_MAX_PAYLOAD_BYTES) {
+ store.delete(queryCacheKey(environmentId, key));
+ return;
+ }
+ store.put({ environmentId, payload, updatedAt, bytes }, queryCacheKey(environmentId, key));
+ const batchKey = queryBatchKey(environmentId);
+ const batchRequest = store.get(batchKey);
+ batchRequest.addEventListener("success", () => {
+ const batch: unknown = batchRequest.result;
+ const rows = (isQueryBatch(batch) ? batch.rows : 0) + 1;
+ const written = (isQueryBatch(batch) ? batch.bytes : 0) + bytes;
+ if (
+ isQueryBatch(batch) &&
+ rows < QUERY_PRUNE_BATCH_ROWS &&
+ written < QUERY_PRUNE_BATCH_BYTES
+ ) {
+ store.put({ rows, bytes: written }, batchKey);
+ return;
+ }
+ store.put({ rows: 0, bytes: 0 }, batchKey);
+ const request = store
+ .index(QUERY_UPDATED_INDEX_NAME)
+ .openKeyCursor(IDBKeyRange.bound([environmentId], [environmentId, []]), "prev");
+ let kept = 0;
+ let totalBytes = 0;
+ request.addEventListener("success", () => {
+ const cursor = request.result;
+ if (cursor === null) return;
+ const [, rowUpdatedAt, rowBytes] = cursor.key as [string, number, number];
+ kept += 1;
+ totalBytes += rowBytes;
+ if (
+ kept > QUERY_MAX_ROWS - QUERY_PRUNE_BATCH_ROWS ||
+ totalBytes > QUERY_MAX_BYTES - QUERY_PRUNE_BATCH_BYTES ||
+ rowUpdatedAt < updatedAt - QUERY_MAX_AGE_MS
+ ) {
+ store.delete(cursor.primaryKey);
+ }
+ cursor.continue();
+ });
+ });
+ } catch (cause) {
+ resume(Effect.fail(catalogError("write", cause)));
+ }
+ }).pipe(Effect.withSpan("web.connectionStorage.saveQuery"));
+}
+
function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) {
return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key));
}
@@ -361,6 +452,14 @@ function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) {
return `${environmentId}:${threadId}`;
}
+function queryCacheKey(environmentId: EnvironmentId, key: string) {
+ return `${environmentId}:v1:${key}`;
+}
+
+function queryBatchKey(environmentId: EnvironmentId) {
+ return `${environmentId}:batch`;
+}
+
function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) {
return `${environmentId}:${cwd}`;
}
@@ -955,12 +1054,45 @@ export const layer = Layer.effectContext(
VCS_REFS_STORE_NAME,
IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
),
+ removeDatabaseValuesInRange(
+ database,
+ QUERY_STORE_NAME,
+ IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
+ ),
],
{ concurrency: "unbounded", discard: true },
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
}),
});
+ const queryStore: NonNullable = {
+ load: Effect.fn("EnvironmentQueryStore.load")(
+ function* (environmentId, key) {
+ const stored = yield* readDatabaseValue(
+ database,
+ QUERY_STORE_NAME,
+ queryCacheKey(environmentId, key),
+ );
+ const now = yield* Clock.currentTimeMillis;
+ return isStoredQuery(stored) &&
+ stored.environmentId === environmentId &&
+ stored.updatedAt >= now - QUERY_MAX_AGE_MS
+ ? Option.some(stored.payload)
+ : Option.none();
+ },
+ Effect.catch(() => Effect.succeedNone),
+ ),
+ save: (environmentId, key, payload) =>
+ Clock.currentTimeMillis.pipe(
+ Effect.flatMap((now) =>
+ withDatabase(database, (opened) =>
+ saveQueryOnConnection(opened, environmentId, key, payload, now),
+ ),
+ ),
+ Effect.catch(() => Effect.logWarning("Offline query database save failed")),
+ ),
+ };
+
return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions),
Context.add(Persistence.ConnectionRegistrationStore, registrationStore),
@@ -968,6 +1100,7 @@ export const layer = Layer.effectContext(
Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
Context.add(Persistence.EnvironmentCacheStore, cacheStore),
+ Context.add(EnvironmentQueryStore, queryStore),
);
}),
);
diff --git a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts b/packages/client-runtime/src/state/pullRequestStatsPersistence.ts
index 2d97ce23d1c7d..75cba63031a2f 100644
--- a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts
+++ b/packages/client-runtime/src/state/pullRequestStatsPersistence.ts
@@ -19,8 +19,10 @@ export function persistPullRequestStats(): QueryPersistence
- row.load(environmentId, statKey(ref)),
+ const rows = yield* Effect.forEach(
+ input.refs,
+ (ref) => row.load(environmentId, statKey(ref)),
+ { concurrency: "unbounded" },
);
const stats = rows.flatMap((value) => (Option.isSome(value) ? [value.value] : []));
return stats.length ? Option.some({ stats }) : Option.none();
diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts
index 64ae5ae3df56e..b92f00c8a3695 100644
--- a/packages/client-runtime/src/state/pullRequests.ts
+++ b/packages/client-runtime/src/state/pullRequests.ts
@@ -21,7 +21,7 @@ import {
type PullRequestRef,
type PullRequestMergeMethod,
PullRequestOperationError,
- type PullRequestSummary,
+ PullRequestSummary,
type VcsStatusResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -147,6 +147,7 @@ export function createLinkedPullRequestSummaryAtomFamily(
const routedRequest = createPullRequestRouter();
return createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:pull-requests:linked-summary",
+ persistence: persistQuery(PullRequestSummary),
tag: WS_METHODS.pullRequestsSummary,
execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
staleTimeMs: 60_000,
diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts
index 381623f23207a..f79f00cdaa80e 100644
--- a/packages/client-runtime/src/state/runtime.test.ts
+++ b/packages/client-runtime/src/state/runtime.test.ts
@@ -1370,19 +1370,20 @@ describe("persisted environment queries", () => {
Effect.scoped(
Effect.gen(function* () {
let saved = Option.none();
+ const saves = yield* Queue.unbounded();
const persistence: QueryPersistence = {
load: () => Effect.sync(() => saved),
save: (_environmentId, _key, value) =>
Effect.sync(() => {
saved = Option.some(value);
- }),
+ }).pipe(Effect.andThen(Queue.offer(saves, value))),
};
const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
persistence,
});
const firstRegistry = yield* mountEnvironmentQuery(first.atom);
expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
- expect(saved).toEqual(Option.some("first"));
+ expect(yield* Queue.take(saves)).toBe("first");
const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
persistence,
@@ -1393,11 +1394,36 @@ describe("persisted environment queries", () => {
yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
yield* Effect.yieldNow;
expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
- expect(saved).toEqual(Option.some("updated"));
+ expect(yield* Queue.take(saves)).toBe("updated");
}),
),
);
+ it.effect("answers readers while its save is pending, and ends the save with the query", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const saveEnded = Latch.makeUnsafe();
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), {
+ persistence: {
+ load: () => Effect.succeedNone,
+ // The registry's scheduler stops on dispose, so signal synchronously.
+ save: () =>
+ Effect.never.pipe(
+ Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe())),
+ ),
+ },
+ });
+ yield* Effect.scoped(
+ Effect.gen(function* () {
+ const registry = yield* mountEnvironmentQuery(harness.atom);
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
+ }),
+ );
+ yield* saveEnded.await;
+ }),
+ ),
+ );
+
it.effect("hands each server answer to onAnswer before readers see it", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts
index 58c37070fd8d6..78e0cec6437a3 100644
--- a/packages/client-runtime/src/state/runtime.ts
+++ b/packages/client-runtime/src/state/runtime.ts
@@ -781,8 +781,12 @@ export function createEnvironmentQueryAtomFamily(
return cached.value;
}
if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
+ // Readers must not wait on the disk: web saves one IndexedDB row per listed PR's stats.
+ // The save ends with the query, so a removed environment's cache stays cleared.
return yield* answer().pipe(
- Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
+ Effect.tap((value) =>
+ persistence.save(target.environmentId, cacheKey, value).pipe(Effect.forkScoped),
+ ),
);
});
})
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
index 5a5c46f28d99a..b676a91f0cab4 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
@@ -820,6 +820,74 @@ layer("GitHubPullRequestApi.layer", (it) => {
}),
);
+ it.effect("reads commit stats alongside later activity pages", () =>
+ Effect.gen(function* () {
+ const laterPageStarted = yield* Deferred.make();
+ const statsStarted = yield* Deferred.make();
+ const activityPage = (head: boolean) => ({
+ data: {
+ repository: {
+ pullRequest: {
+ ...(head
+ ? {
+ author: null,
+ commits: {
+ nodes: [
+ {
+ commit: {
+ id: "node-regular",
+ oid: "regular",
+ messageHeadline: "regular",
+ committedDate: "2026-07-05T00:00:00Z",
+ parents: { totalCount: 1 },
+ authors: { nodes: [] },
+ },
+ },
+ ],
+ },
+ }
+ : {}),
+ comments: {
+ nodes: [],
+ pageInfo: head ? { hasNextPage: true, endCursor: "c1" } : lastPage,
+ },
+ reviews: { nodes: [], pageInfo: lastPage },
+ },
+ },
+ },
+ });
+ mockedExecute.mockImplementation((call) => {
+ if (matches(call, "PullRequestCommitStats")) {
+ return Deferred.succeed(statsStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(laterPageStarted)),
+ Effect.as(
+ output(
+ encodeJson({
+ data: {
+ nodes: [{ __typename: "Commit", oid: "regular", additions: 3, deletions: 1 }],
+ },
+ }),
+ ),
+ ),
+ );
+ }
+ const head = call.kind === "graphql" && call.variables?.["head"] === true;
+ return head
+ ? Effect.succeed(output(encodeJson(activityPage(true))))
+ : Deferred.succeed(laterPageStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(statsStarted)),
+ Effect.as(output(encodeJson(activityPage(false)))),
+ );
+ });
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+
+ const activity = yield* cli.getPullRequestActivity(pullRequestInput);
+
+ expect(activity.commits[0]).toMatchObject({ additions: 3, deletions: 1 });
+ expect(mockedExecute).toHaveBeenCalledTimes(3);
+ }),
+ );
+
it.effect("loads the complete hover card with one GraphQL request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
@@ -3299,7 +3367,10 @@ layer("GitHubPullRequestApi.layer", (it) => {
Effect.succeed(output(reviewThreadsPage([thread("T3", "c3")], null))),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
- const read = cli.listReviewThreadComments(pullRequestInput);
+ const read = cli.listReviewThreadComments({
+ ...pullRequestInput,
+ repository: `acme/refused-threads-${later}`,
+ });
const conversation = yield* read;
expect(
variablesOf("ReviewThreads").map((v) => [v["after"], v["requestedReviewers"]]),
@@ -3327,7 +3398,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
yield* read;
expect(variablesOf("ReviewThreads").at(-1)).toMatchObject({
after: null,
- requestedReviewers: 50,
+ requestedReviewers: 0,
});
}),
);
@@ -3460,7 +3531,10 @@ layer("GitHubPullRequestApi.layer", (it) => {
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
- const read = cli.getPullRequestDetail(pullRequestInput);
+ const read = cli.getPullRequestDetail({
+ ...pullRequestInput,
+ repository: `acme/refused-checks-${refused}`,
+ });
const detail = yield* read;
expect(detail.reviewRequestLogins).toEqual([]);
expect(detail.reviewRequestTeams).toEqual([]);
@@ -3480,7 +3554,8 @@ layer("GitHubPullRequestApi.layer", (it) => {
if (refused) {
mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(coreResponse()))));
yield* read;
- expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 100 });
+ expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 0 });
+ expect(mockedExecute).toHaveBeenCalledTimes(4);
}
}),
);
@@ -3514,7 +3589,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
const error = yield* Effect.flip(
cli.getPullRequestDetail({
cwd: "/w",
- repository: "acme/web",
+ repository: `acme/head-changed-${refused}`,
host: "github.com",
number: 7,
}),
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
index 2defbb6684919..cb96b97d8556c 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
@@ -1422,6 +1422,31 @@ export const make = Effect.gen(function* () {
};
});
+ // GitHub refuses a requested-reviewer list holding a team the viewer cannot see. Remember the
+ // refusal so later reads of that pull request skip straight to the read without reviewers.
+ const refusedReviewers = yield* Cache.make({
+ capacity: 512,
+ timeToLive: "10 minutes",
+ lookup: (_key: string) => Effect.void,
+ });
+ const readRequestedReviewers = Effect.fn("GitHubPullRequestApi.readRequestedReviewers")(
+ function* (
+ input: { readonly host: string; readonly repository: string; readonly number: number },
+ wanted: number,
+ read: (requestedReviewers: number) => Effect.Effect,
+ ) {
+ const host = normalizeHost(input.host);
+ const { fingerprint } = yield* api.credential(host);
+ const key = `${fingerprint}\0${host}\0${input.repository.toLowerCase()}\0${input.number}`;
+ if (yield* Cache.has(refusedReviewers, key)) return yield* read(0);
+ return yield* read(wanted).pipe(
+ Effect.catchIf(isRefusedRequestedReviewersOnly, () =>
+ Cache.set(refusedReviewers, key, undefined).pipe(Effect.andThen(read(0))),
+ ),
+ );
+ },
+ );
+
const getPullRequestDetail: GitHubPullRequestApi["Service"]["getPullRequestDetail"] = (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
const operation = "getPullRequestDetail";
@@ -1436,8 +1461,7 @@ export const make = Effect.gen(function* () {
});
return SourceControlRateLimit.Interactive.pipe(
Effect.flatMap((allowReserve) =>
- read(100).pipe(
- Effect.catchIf(isRefusedRequestedReviewersOnly, () => read(0)),
+ readRequestedReviewers(input, 100, read).pipe(
graphql({ ...input, operation, allowReserve }),
Effect.map(toPullRequestCore),
Effect.flatMap(found({ ...input, operation })),
@@ -2031,7 +2055,9 @@ export const make = Effect.gen(function* () {
let withComments = true;
let withReviews = true;
const target = { ...input, operation: "getPullRequestActivity" };
- for (let page = 0; page < REVIEW_THREAD_PAGES && (withComments || withReviews); page++) {
+ const readPage = Effect.fn("GitHubPullRequestApi.readActivityPage")(function* (
+ page: number,
+ ) {
const read: GitHubPullRequestActivityPage = yield* client
.PullRequestActivity({
owner,
@@ -2058,16 +2084,28 @@ export const make = Effect.gen(function* () {
reviewsAfter = read.nextReviewsCursor;
withComments = withComments && commentsAfter !== null;
withReviews = withReviews && reviewsAfter !== null;
- }
+ });
+ yield* readPage(0);
+ const laterPages = Effect.gen(function* () {
+ for (let page = 1; page < REVIEW_THREAD_PAGES; page++) {
+ if (!withComments && !withReviews) return;
+ yield* readPage(page);
+ }
+ });
const emptyStats = toPullRequestCommitStats({ nodes: [] });
- const commitStats =
- nonMergeCommitIds.length === 0
- ? emptyStats
- : yield* client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe(
- graphql(target),
- Effect.map(toPullRequestCommitStats),
- Effect.orElseSucceed(() => emptyStats),
- );
+ const [, commitStats] = yield* Effect.all(
+ [
+ laterPages,
+ nonMergeCommitIds.length === 0
+ ? Effect.succeed(emptyStats)
+ : client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe(
+ graphql(target),
+ Effect.map(toPullRequestCommitStats),
+ Effect.orElseSucceed(() => emptyStats),
+ ),
+ ],
+ { concurrency: 2 },
+ );
return {
author,
comments: remarks.toSorted((left, right) =>
@@ -2157,25 +2195,12 @@ export const make = Effect.gen(function* () {
function* (input) {
const { owner, name } = parseRepositorySelector(input.repository);
const target = { ...input, operation: "listReviewThreadComments" };
- let requestedReviewers = 50;
const threadPage = (
after: string | null,
- ): Effect.Effect => {
- const read = () =>
- client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers });
- return read().pipe(
- Effect.catchIf(
- (error) => requestedReviewers > 0 && isRefusedRequestedReviewersOnly(error),
- () => {
- requestedReviewers = 0;
- return read();
- },
- ),
- graphql(target),
- Effect.map(toReviewThreadPage),
- Effect.flatMap(found(target)),
- );
- };
+ ): Effect.Effect =>
+ readRequestedReviewers(input, 50, (requestedReviewers) =>
+ client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers }),
+ ).pipe(graphql(target), Effect.map(toReviewThreadPage), Effect.flatMap(found(target)));
const entries: GitHubReviewThreadEntry[] = [];
const avatarsByLogin = new Map();
const botLogins = new Set();