Skip to content
TypeScript

fix(mobile): reduce diff entry and source highlighting delays (#24770)

Julius Marminge15702a9f2862
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
index ef2743a34d5..6c2cb8f0d3a 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.test.ts
@@ -58,17 +58,24 @@ const failureKeys = [
["function", () => () => SOURCE],
] as const;
-it.each(failureKeys)("bounds transient retries for a %s key", async (_name, createKey) => {
- const key = createKey();
- const fetch = vi.fn(async () => {
- throw new Error("Offline");
- });
- const load = createNativeReviewDiffSourceLoader(fetch);
- await expect(load(key)).rejects.toThrow("Offline");
- expect(await load(key)).toBeNull();
- expect(await load(key)).toBeNull();
- expect(fetch).toHaveBeenCalledTimes(2);
-});
+it.each(failureKeys)(
+ "recovers after two transient failures on a later load for a %s key",
+ async (_name, createKey) => {
+ const key = createKey();
+ const fetch = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Offline"))
+ .mockRejectedValueOnce(new Error("Still offline"))
+ .mockResolvedValue(SOURCE);
+ const load = createNativeReviewDiffSourceLoader(fetch);
+ await expect(load(key)).rejects.toThrow("Offline");
+ await expect(load(key)).rejects.toThrow("Still offline");
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(await load(key)).toBe(SOURCE);
+ expect(await load(key)).toBe(SOURCE);
+ expect(fetch).toHaveBeenCalledTimes(3);
+ },
+);
it.each(failureKeys)(
"remembers permanent unavailability for a %s key",
diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
index 8dc30c71825..7f503239c21 100644
--- a/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSource.ts
@@ -5,7 +5,6 @@ const MAX_SOURCE_FILES = 4;
// Bound retained UTF-16 text across files without discarding an already-fetched
// authoritative source just because it is large. Provider response limits still apply.
const MAX_CACHED_SOURCE_CHARACTERS = 8_000_000;
-const MAX_SOURCE_ATTEMPTS = 2;
function isWeakKey(value: unknown): value is object {
return (typeof value === "object" && value !== null) || typeof value === "function";
@@ -158,12 +157,12 @@ export function createNativeReviewDiffSourceLoader<FileId>(
permanent,
reason: reason ?? "transient",
});
- if (permanent || attempt >= MAX_SOURCE_ATTEMPTS) {
+ if (permanent) {
failure.unavailable = true;
traceDiffHighlight("source-unavailable", {
loader,
file,
- reason: permanent ? "permanent-error" : "attempts",
+ reason: "permanent-error",
});
return null;
}
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index e988da1a0af..190d707cc8c 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
@@ -43,6 +43,7 @@ import {
import { usePullRequestDiffHighlightFiles } from "./usePullRequestDiffHighlightFiles";
import { isPullRequestTestFile } from "./pullRequestFileFilters";
import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";
+import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/contracts";
@@ -88,7 +89,7 @@ import {
type NativeReviewDiffViewProps,
} from "../diffs/nativeReviewDiffSurface";
import {
- buildNativeReviewDiffData,
+ getCachedNativeReviewDiffData,
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
} from "../review/nativeReviewDiffAdapter";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
@@ -99,6 +100,7 @@ import { PullRequestActionToolbar, PullRequestCardGroup } from "./PullRequestCon
import {
pullRequestTarget as requestTarget,
usePullRequestDiff,
+ usePullRequestDiffEntry,
type PullRequestDiffParams,
type PullRequestParams,
} from "./usePullRequestDiff";
@@ -847,16 +849,35 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
);
}
-export function PullRequestFileRouteScreen({
- route,
-}: StaticScreenProps<
+type PullRequestFileRouteProps = StaticScreenProps<
PullRequestDiffParams & {
readonly path: string;
readonly fileSelectionId?: string;
readonly replacingDraftId?: string;
readonly focus?: GuideDiffFocus;
}
->) {
+>;
+
+export function PullRequestFileRouteScreen(props: PullRequestFileRouteProps) {
+ const navigation =
+ useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "PullRequestFile">>();
+ const ready = usePullRequestDiffEntry(navigation);
+ if (ready) return <PullRequestFileRouteContent {...props} />;
+ const title = props.route.params.commit ? "Commit changes" : "Changes";
+ return (
+ <View className="flex-1 bg-screen">
+ <NativeStackScreenOptions options={{ title, headerTitle: title }} />
+ {Platform.OS === "android" ? (
+ <AndroidScreenHeader title={title} onBack={() => navigation.goBack()} />
+ ) : null}
+ <View className="flex-1 items-center justify-center">
+ <AppActivityIndicator accessibilityLabel="Loading changes" />
+ </View>
+ </View>
+ );
+}
+
+function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
const { layout } = useAdaptiveWorkspaceLayout();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
@@ -894,7 +915,7 @@ export function PullRequestFileRouteScreen({
!result.isPending &&
!result.error;
const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
- const baseData = useMemo(() => buildNativeReviewDiffData(parsed), [parsed]);
+ const baseData = useMemo(() => getCachedNativeReviewDiffData({ parsedDiff: parsed }), [parsed]);
const highlightFiles = usePullRequestDiffHighlightFiles(route.params, parsed, baseData.files);
const data = useMemo(
() =>
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts
index 3d419f262da..b48933573f3 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.test.ts
@@ -265,8 +265,12 @@ it.each(["permanent", "transient"])(
fetch.mockRejectedValueOnce(error);
if (failure === "transient") fetch.mockRejectedValueOnce(error);
const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
- if (failure === "transient") await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
- expect(await first[1]!.loadContents!()).toBeNull();
+ if (failure === "transient") {
+ await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
+ await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
+ } else {
+ expect(await first[1]!.loadContents!()).toBeNull();
+ }
const second = createPullRequestDiffHighlightFiles(
{ target },
{ ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },
@@ -275,8 +279,8 @@ it.each(["permanent", "transient"])(
cache,
);
expect(await second[1]!.loadContents!()).toBe(contents);
- expect(await first[1]!.loadContents!()).toBeNull();
- expect(fetch).toHaveBeenCalledTimes(failure === "permanent" ? 2 : 3);
+ expect(await first[1]!.loadContents!()).toBe(failure === "permanent" ? null : contents);
+ expect(fetch).toHaveBeenCalledTimes(failure === "permanent" ? 2 : 4);
},
);
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
index a2d06d06ca0..ee5f0244307 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts
@@ -1,8 +1,13 @@
-import { describe, expect, it } from "vite-plus/test";
+import { describe, expect, it, vi } from "vite-plus/test";
import type { PullRequestDiffResult } from "@t3tools/contracts";
import type { ReviewParsedDiff } from "../review/reviewModel";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
-import { combinePullRequestDiffPages, retainPullRequestDiffPage } from "./pullRequestDiffPages";
+import * as reviewModel from "../review/reviewModel";
+import {
+ combinePullRequestDiffPages,
+ getCachedPullRequestDiffPages,
+ retainPullRequestDiffPage,
+} from "./pullRequestDiffPages";
const GITHUB = sourceControlClients.get("github").changeRequest;
@@ -24,6 +29,65 @@ function withheldDiff(): PullRequestDiffResult {
}
describe("paged mobile pull request diffs", () => {
+ it("isolates scopes, cursors, and provider terminology for the same result", () => {
+ const result = withheldDiff();
+ const pages = [{ cursor: null, result }];
+ const first = getCachedPullRequestDiffPages(pages, "first", GITHUB);
+ const otherScope = getCachedPullRequestDiffPages(pages, "second", GITHUB);
+ const otherCursor = getCachedPullRequestDiffPages(
+ [{ cursor: "next", result }],
+ "first",
+ GITHUB,
+ );
+ const otherProvider = getCachedPullRequestDiffPages(
+ pages,
+ "first",
+ sourceControlClients.get("gitlab").changeRequest,
+ );
+ expect(otherScope).not.toBe(first);
+ expect(otherCursor).not.toBe(first);
+ expect(otherProvider).not.toBe(first);
+ if (first.kind !== "files" || otherScope.kind !== "files" || otherProvider.kind !== "files")
+ throw new Error("Expected structured files");
+ expect(otherScope.files[0]?.id).not.toBe(first.files[0]?.id);
+ expect(first.notice).toContain("pull request");
+ expect(otherProvider.notice).toContain("merge request");
+ expect(getCachedPullRequestDiffPages(pages, "first", GITHUB)).toBe(first);
+ });
+
+ it("reuses earlier pages on append and invalidates changed continuation results", () => {
+ using parse = vi.spyOn(reviewModel, "buildReviewParsedDiff");
+ const firstPage = { cursor: null, result: diff("first.ts") };
+ const first = getCachedPullRequestDiffPages([firstPage], "append", GITHUB);
+ const nextPage = { cursor: "next", result: withheldDiff() };
+ const combined = getCachedPullRequestDiffPages([firstPage, nextPage], "append", GITHUB);
+ expect(parse).toHaveBeenCalledTimes(2);
+ if (first.kind !== "files" || combined.kind !== "files") throw new Error("Expected files");
+ expect(combined.files[0]).toBe(first.files[0]);
+ expect(combined.files.map((file) => file.path)).toEqual(["first.ts", "large.ts"]);
+ expect(getCachedPullRequestDiffPages([firstPage, nextPage], "append", GITHUB)).toBe(combined);
+ const refreshed = getCachedPullRequestDiffPages(
+ [
+ firstPage,
+ {
+ ...nextPage,
+ result: {
+ ...nextPage.result,
+ omittedFileStats: [{ path: "large.ts", additions: 4000, deletions: 2000 }],
+ },
+ },
+ ],
+ "append",
+ GITHUB,
+ );
+ expect(parse).toHaveBeenCalledTimes(3);
+ expect(refreshed).not.toBe(combined);
+ if (refreshed.kind !== "files") throw new Error("Expected refreshed files");
+ expect(refreshed.files[0]).toBe(first.files[0]);
+ expect(refreshed.files[1]).toMatchObject({ additions: 4000, deletions: 2000 });
+ expect(combined.files[1]?.additions).toBe(3000);
+ });
+
it("withheld PR hunks must retain provider line counts", () => {
const result = withheldDiff();
const cache = new WeakMap<PullRequestDiffResult, ReviewParsedDiff>();
diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
index c30f3a3198a..9abf7cfc0c0 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts
@@ -7,6 +7,46 @@ export interface PullRequestDiffPage {
readonly result: PullRequestDiffResult;
}
+interface CachedPullRequestDiffPages {
+ readonly pages: readonly PullRequestDiffPage[];
+ readonly cache: WeakMap<PullRequestDiffResult, ReviewParsedDiff>;
+ readonly parsed: ReviewParsedDiff;
+}
+
+// Keep only the latest combination per scoped first page; query results own its lifetime.
+const parsedSnapshots = new WeakMap<
+ PullRequestDiffResult,
+ Map<string, CachedPullRequestDiffPages>
+>();
+
+export function getCachedPullRequestDiffPages(
+ pages: readonly PullRequestDiffPage[],
+ scope: string,
+ terminology: ChangeRequestTerminology,
+): ReviewParsedDiff {
+ const first = pages[0];
+ if (!first) return { kind: "empty" };
+ const key = JSON.stringify([scope, terminology.singular, first.cursor]);
+ let snapshots = parsedSnapshots.get(first.result);
+ if (!snapshots) {
+ snapshots = new Map();
+ parsedSnapshots.set(first.result, snapshots);
+ }
+ const previous = snapshots.get(key);
+ if (
+ previous?.pages.length === pages.length &&
+ pages.every((page, index) => {
+ const cached = previous.pages[index];
+ return cached?.cursor === page.cursor && cached.result === page.result;
+ })
+ )
+ return previous.parsed;
+ const cache = previous?.cache ?? new WeakMap<PullRequestDiffResult, ReviewParsedDiff>();
+ const parsed = combinePullRequestDiffPages(pages, cache, scope, terminology);
+ snapshots.set(key, { pages, cache, parsed });
+ return parsed;
+}
+
/** A changed page invalidates later cursors, which belong to the previous patch. */
export function retainPullRequestDiffPage(
pages: readonly PullRequestDiffPage[],
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
index 0548cbb2419..3000efb9633 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
@@ -3,14 +3,16 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli
import type { PullRequestDiffResult } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { Atom, AtomRegistry } from "effect/reactivity";
-import { act, useLayoutEffect } from "react";
+import { act, useLayoutEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({ diff: vi.fn() }));
vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } }));
-import { usePullRequestDiff } from "./usePullRequestDiff";
+import { usePullRequestDiff, usePullRequestDiffEntry } from "./usePullRequestDiff";
+import * as reviewModel from "../review/reviewModel";
+import { getCachedNativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
function patch(path: string, nextCursor: string | null = null): PullRequestDiffResult {
return {
@@ -67,6 +69,15 @@ function setup() {
);
return {
requests,
+ remount() {
+ act(() =>
+ root.render(
+ <RegistryContext.Provider value={registry}>
+ <Probe key="new-route" />
+ </RegistryContext.Provider>,
+ ),
+ );
+ },
get current() {
return current;
},
@@ -87,6 +98,123 @@ function setup() {
};
}
+it("reuses the parsed snapshot when a new route reads the same query result", async () => {
+ using parse = vi.spyOn(reviewModel, "buildReviewParsedDiff");
+ using screen = setup();
+ await screen.succeed(0, patch("first.ts"));
+ const parsed = screen.current.parsed;
+ const parses = parse.mock.calls.length;
+ screen.remount();
+ expect(screen.current.parsed).toBe(parsed);
+ expect(parse).toHaveBeenCalledTimes(parses);
+ expect(screen.requests).toHaveLength(1);
+});
+
+function setupEntry() {
+ vi.useFakeTimers();
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const frames = new Map<number, FrameRequestCallback>();
+ let frameId = 0;
+ const requestFrame = vi
+ .spyOn(globalThis, "requestAnimationFrame")
+ .mockImplementation((callback) => {
+ frames.set(++frameId, callback);
+ return frameId;
+ });
+ const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
+ if (id != null) frames.delete(id);
+ });
+ const listeners = new Map<string, (event: { data: { closing: boolean } }) => void>();
+ const navigation = {
+ addListener(
+ type: "transitionStart" | "transitionEnd",
+ listener: (event: { data: { closing: boolean } }) => void,
+ ) {
+ listeners.set(type, listener);
+ return () => {
+ listeners.delete(type);
+ };
+ },
+ };
+ const events: string[] = [];
+ const prepare = vi.fn(() => {
+ events.push("prepare");
+ return getCachedNativeReviewDiffData({
+ parsedDiff: reviewModel.buildReviewParsedDiff(
+ patch("first.ts").patch + patch("neighbor.ts").patch,
+ "entry",
+ ),
+ });
+ });
+ function Body() {
+ const [data] = useState(prepare);
+ return <div>{data.files.map((file) => file.path).join(",")}</div>;
+ }
+ function Entry() {
+ const ready = usePullRequestDiffEntry(navigation);
+ useLayoutEffect(() => {
+ events.push(ready ? "body-commit" : "shell-commit");
+ }, [ready]);
+ return ready ? <Body /> : <div>Opening changes</div>;
+ }
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => root.render(<Entry />));
+ return {
+ prepare,
+ events,
+ container,
+ frame() {
+ const pending = [...frames.values()];
+ frames.clear();
+ act(() => {
+ for (const callback of pending) callback(0);
+ });
+ },
+ event(type: "transitionStart" | "transitionEnd", closing = false) {
+ act(() => listeners.get(type)?.({ data: { closing } }));
+ },
+ fallback() {
+ act(() => vi.runAllTimers());
+ },
+ [Symbol.dispose]() {
+ act(() => root.unmount());
+ requestFrame.mockRestore();
+ cancelFrame.mockRestore();
+ vi.useRealTimers();
+ },
+ };
+}
+
+it("commits the loading shell and waits for the opening transition before building the diff", () => {
+ using screen = setupEntry();
+ expect(screen.events).toEqual(["shell-commit"]);
+ screen.event("transitionStart");
+ screen.frame();
+ screen.frame();
+ screen.event("transitionEnd", true);
+ expect(screen.prepare).not.toHaveBeenCalled();
+ screen.event("transitionEnd");
+ expect(screen.events).toEqual(["shell-commit", "prepare", "body-commit"]);
+ expect(screen.container.textContent).toBe("first.ts,neighbor.ts");
+});
+
+it.each(["unanimated", "missing-completion"] as const)(
+ "opens the diff after a %s presentation without stranding the shell",
+ (presentation) => {
+ using screen = setupEntry();
+ if (presentation === "missing-completion") screen.event("transitionStart");
+ screen.frame();
+ expect(screen.prepare).not.toHaveBeenCalled();
+ screen.frame();
+ if (presentation === "missing-completion") {
+ expect(screen.prepare).not.toHaveBeenCalled();
+ screen.fallback();
+ }
+ expect(screen.prepare).toHaveBeenCalledOnce();
+ },
+);
+
it("retries a failed continuation without discarding loaded files or restarting page one", async () => {
using screen = setup();
await screen.succeed(0, patch("first.ts", "second"));
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
index 2b33c86871a..c3c25b85919 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
@@ -1,19 +1,13 @@
import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
-import {
- EnvironmentId,
- ProjectId,
- type PullRequestDiffResult,
- type PullRequestListEntry,
-} from "@t3tools/contracts";
+import { EnvironmentId, ProjectId, type PullRequestListEntry } from "@t3tools/contracts";
import { useAtomRefresh } from "@effect/atom-react";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useLayoutEffect, useMemo, useState } from "react";
import { composerPullRequests } from "../../state/pull-requests";
import { useEnvironmentQuery } from "../../state/query";
import { usePullToRefresh } from "../../state/use-pull-to-refresh";
-import type { ReviewParsedDiff } from "../review/reviewModel";
import {
- combinePullRequestDiffPages,
+ getCachedPullRequestDiffPages,
retainPullRequestDiffPage,
type PullRequestDiffPage,
} from "./pullRequestDiffPages";
@@ -43,6 +37,46 @@ export function pullRequestTarget(params: PullRequestParams) {
const NO_PAGES: readonly PullRequestDiffPage[] = [];
+export function usePullRequestDiffEntry(navigation: {
+ readonly addListener: (
+ type: "transitionStart" | "transitionEnd",
+ listener: (event: { readonly data: { readonly closing: boolean } }) => void,
+ ) => () => void;
+}) {
+ const [ready, setReady] = useState(false);
+ useLayoutEffect(() => {
+ if (ready) return;
+ let opening = false;
+ let closing = false;
+ const finish = () => {
+ if (!closing) setReady(true);
+ };
+ const removeStart = navigation.addListener("transitionStart", ({ data }) => {
+ closing = data.closing;
+ if (!closing) opening = true;
+ });
+ const removeEnd = navigation.addListener("transitionEnd", ({ data }) => {
+ closing = data.closing;
+ if (!closing) finish();
+ });
+ // Initial and unanimated presentations may have no transition events; let the shell paint first.
+ let frame = requestAnimationFrame(() => {
+ frame = requestAnimationFrame(() => {
+ if (!opening) finish();
+ });
+ });
+ // A missing native completion must not strand the route on its loading state.
+ const fallback = setTimeout(finish, 1_000);
+ return () => {
+ removeStart();
+ removeEnd();
+ cancelAnimationFrame(frame);
+ clearTimeout(fallback);
+ };
+ }, [navigation, ready]);
+ return ready;
+}
+
export function usePullRequestDiff(
params: PullRequestDiffParams,
terminology: ChangeRequestTerminology,
@@ -74,10 +108,9 @@ export function usePullRequestDiff(
}, [cursor, key, query.data, state.key, state.pages]);
if (state.key !== key || state.pages !== pages) setState({ key, cursor, pages });
- const [parseCache] = useState(() => new WeakMap<PullRequestDiffResult, ReviewParsedDiff>());
const parsed = useMemo(
- () => combinePullRequestDiffPages(pages, parseCache, key, terminology),
- [key, pages, parseCache, terminology],
+ () => getCachedPullRequestDiffPages(pages, key, terminology),
+ [key, pages, terminology],
);
const patch = useMemo(() => pages.map((page) => page.result.patch).join("\n"), [pages]);
const nextCursor = pages.at(-1)?.result.nextCursor ?? null;
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index a17347d8347..b3984ea1054 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -3981,6 +3981,132 @@ it.effect("pauses uncached activity on a host after one activity read is rate li
}),
);
+it.effect("authorizes cold source reads with paginated paths without fetching patch hunks", () =>
+ Effect.gen(function* () {
+ const pages: Array<string | undefined> = [];
+ const contents: Array<string> = [];
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ getDiff: () => Effect.die("Membership must not fetch patch hunks"),
+ getDiffFilePaths: (input) =>
+ Effect.sync(() => {
+ pages.push(input.cursor);
+ return input.cursor === undefined
+ ? { files: [{ oldPath: "before.ts", newPath: "after.ts" }], nextCursor: "next" }
+ : { files: [{ oldPath: "gone.ts", newPath: "gone.ts" }], nextCursor: null };
+ }),
+ getDiffFileContents: (input) =>
+ Effect.sync(() => {
+ contents.push(`${input.oldPath}->${input.newPath}`);
+ return { oldContents: "before", newContents: "after" };
+ }),
+ }),
+ ],
+ });
+ const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ yield* service.diffFileContents({
+ ...ref,
+ changeType: "rename-changed",
+ oldPath: "before.ts",
+ newPath: "after.ts",
+ });
+ yield* service.diffFileContents({
+ ...ref,
+ changeType: "deleted",
+ oldPath: "gone.ts",
+ newPath: "gone.ts",
+ });
+ for (const [oldPath, newPath] of [
+ [".env", ".env"],
+ ["../after.ts", "../after.ts"],
+ ["secret.ts", "after.ts"],
+ ] as const) {
+ const error = yield* service
+ .diffFileContents({ ...ref, changeType: "change", oldPath, newPath })
+ .pipe(Effect.flip);
+ assert.strictEqual(error.reason, "not-found");
+ }
+ assert.deepStrictEqual(pages, [undefined, "next"]);
+ assert.deepStrictEqual(contents, ["before.ts->after.ts", "gone.ts->gone.ts"]);
+ }),
+);
+
+it.effect.each(["commit", "credential", "expiry", "refresh"] as const)(
+ "keeps cold metadata membership in its original scope through an in-flight %s",
+ (boundary) =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ let credential = "broad";
+ let pathReads = 0;
+ let contentReads = 0;
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ withVerifiedCredential: (_, use) =>
+ Effect.suspend(() =>
+ use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }),
+ ),
+ getDiff: () => Effect.die("Membership must not fetch patch hunks"),
+ getDiffFilePaths: (input) =>
+ Effect.gen(function* () {
+ assert.strictEqual(input.cwd, "/a");
+ assert.strictEqual(input.host, "github.com");
+ assert.strictEqual(input.repository, "acme/web");
+ if (++pathReads !== 1) return { files: [], nextCursor: null };
+ assert.strictEqual(
+ input.commit,
+ boundary === "commit" ? "a".repeat(40) : undefined,
+ );
+ yield* Deferred.succeed(started, undefined);
+ yield* Deferred.await(release);
+ return {
+ files: [{ oldPath: "private.ts", newPath: "private.ts" }],
+ nextCursor: null,
+ };
+ }),
+ getDiffFileContents: () =>
+ Effect.sync(() => {
+ contentReads += 1;
+ return { oldContents: "old", newContents: "new" };
+ }),
+ }),
+ ],
+ });
+ const input = {
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ host: "github.com",
+ expectedAccountId: "101",
+ changeType: "change" as const,
+ oldPath: "private.ts",
+ newPath: "private.ts",
+ };
+ const initial = boundary === "commit" ? { ...input, commit: "a".repeat(40) } : input;
+ const loading = yield* Effect.forkChild(
+ service.withRoutingCredential(initial, service.diffFileContents(initial)),
+ );
+ yield* Deferred.await(started);
+ if (boundary === "expiry") yield* TestClock.adjust("61 seconds");
+ if (boundary === "refresh") yield* service.invalidate({ reference: input });
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(loading);
+ if (boundary === "credential") credential = "restricted";
+ const error = yield* service
+ .withRoutingCredential(input, service.diffFileContents(input))
+ .pipe(Effect.flip);
+ assert.strictEqual(error.reason, "not-found");
+ assert.strictEqual(pathReads, 2);
+ assert.strictEqual(contentReads, 1);
+ }),
+);
+
it.effect(
"reuses loaded oversized diff slices to expand only files the change request changes",
() =>
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 437f8ab4e52..b37cf7d5766 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -86,6 +86,7 @@ import type { SourceControlProviderContext } from "@t3tools/source-control-core/
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import {
type ProviderChangeRequest,
+ type ProviderDiffFilePaths,
type ProviderFilterOptionPage,
type ProviderListCursor,
type ProviderChangeRequestWatchFingerprint,
@@ -543,6 +544,9 @@ function withRateLimitBackoff(
}),
getViewerPermissions: interactive("getViewerPermissions", api.getViewerPermissions),
getDiff: wrap("getDiff", api.getDiff),
+ ...(api.getDiffFilePaths === undefined
+ ? {}
+ : { getDiffFilePaths: wrap("getDiffFilePaths", api.getDiffFilePaths) }),
...(api.getDiffFileContents === undefined
? {}
: { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }),
@@ -3475,14 +3479,10 @@ export const make = Effect.gen(function* () {
const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]);
const sliceKey = (input: PullRequestDiffInput) =>
JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]);
- const record = (key: string, slice: PullRequestDiffResult, at: number) => {
+ const recordPaths = (key: string, slice: ProviderDiffFilePaths, at: number) => {
const entry = {
at,
- files: new Set(
- parseDiffFilePaths(slice.patch).map((file) =>
- fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),
- ),
- ),
+ files: new Set(slice.files.map((file) => fileKey(file.oldPath, file.newPath))),
nextCursor: slice.nextCursor,
};
held.delete(key);
@@ -3493,11 +3493,37 @@ export const make = Effect.gen(function* () {
held.set(key, entry);
return entry;
};
+ const record = (key: string, slice: PullRequestDiffResult, at: number) =>
+ recordPaths(
+ key,
+ {
+ files: parseDiffFilePaths(slice.patch).map((file) => ({
+ oldPath: file.oldPath ?? file.newPath ?? "",
+ newPath: file.newPath ?? file.oldPath ?? "",
+ })),
+ nextCursor: slice.nextCursor,
+ },
+ at,
+ );
const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {
const key = sliceKey(input);
const now = yield* Clock.currentTimeMillis;
const cached = held.get(key);
if (cached !== undefined && now - cached.at <= ttlMs) return cached;
+ const project = yield* requireProject(input);
+ if (project.api.capabilities.diff && project.api.getDiffFilePaths) {
+ const slice = yield* project.api
+ .getDiffFilePaths({
+ cwd: project.project.workspaceRoot,
+ repository: project.repository,
+ host: project.host,
+ number: input.number,
+ ...(input.cursor === undefined ? {} : { cursor: input.cursor }),
+ ...(input.commit === undefined ? {} : { commit: input.commit }),
+ })
+ .pipe(Effect.mapError(toPullRequestError("diffFileContents")));
+ return recordPaths(key, slice, now);
+ }
const slice = yield* diff(input);
return record(key, slice, now);
});
diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts
index ae64bda0395..ce1a72c1aed 100644
--- a/packages/source-control-core/src/server/PullRequestProvider.ts
+++ b/packages/source-control-core/src/server/PullRequestProvider.ts
@@ -223,6 +223,11 @@ export interface ProviderDiffFileContents {
readonly newContents: string;
}
+export interface ProviderDiffFilePaths {
+ readonly files: ReadonlyArray<{ readonly oldPath: string; readonly newPath: string }>;
+ readonly nextCursor: string | null;
+}
+
export interface ProviderFilesViewed {
readonly files: ReadonlyArray<PullRequestFileViewed>;
/** More files exist; missing entries are unknown, not "unviewed". */
@@ -394,6 +399,15 @@ export interface PullRequestProviderApi {
},
) => Effect.Effect<ProviderDiffSlice, PullRequestProviderError>;
+ /** Exact changed path pairs, including renames, without fetching patch contents. */
+ readonly getDiffFilePaths?: (
+ input: ProviderRepositoryRef & {
+ readonly number: number;
+ readonly cursor?: string | undefined;
+ readonly commit?: string | undefined;
+ },
+ ) => Effect.Effect<ProviderDiffFilePaths, PullRequestProviderError>;
+
readonly getDiffFileContents?: (
input: ProviderRepositoryRef & {
readonly number: number;
diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
index 40430ab2f15..d787b2ba62a 100644
--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.test.ts
@@ -164,6 +164,124 @@ const assertRequestId = (body: unknown) =>
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
);
+describe("GitCafePullRequestProvider changed paths", () => {
+ const snapshot = { version: pull.version, headOid, comparisonBaseOid: baseOid };
+
+ it.effect("pages changed paths without fetching diff-file hunks", () => {
+ const server = fakeGitCafe({
+ "GET /repos/owner/repo/pulls/7": pull,
+ "GET /repos/owner/repo/pulls/7/changes": (request: SentRequest) => ({
+ ...snapshot,
+ items: request.query.has("after")
+ ? [{ path: "gone.ts", status: "deleted" }]
+ : [{ path: "new name.ts", oldPath: "old name.ts", status: "renamed" }],
+ next: request.query.has("after") ? null : "next-page",
+ }),
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ const first = yield* provider.getDiffFilePaths!(target);
+ const second = yield* provider.getDiffFilePaths!({ ...target, cursor: first.nextCursor! });
+ assert.deepStrictEqual(first.files, [{ oldPath: "old name.ts", newPath: "new name.ts" }]);
+ assert.deepStrictEqual(second, {
+ files: [{ oldPath: "gone.ts", newPath: "gone.ts" }],
+ nextCursor: null,
+ });
+ assert.isFalse(server.sent.some((request) => request.path.includes("/diff-file")));
+ }).pipe(Effect.provide(server.layer));
+ });
+
+ it.effect.each(["getDiff", "getDiffFilePaths"] as const)(
+ "%s rejects a repeated continuation cursor",
+ (method) => {
+ const server = fakeGitCafe({
+ "GET /repos/owner/repo/pulls/7": pull,
+ "GET /repos/owner/repo/pulls/7/changes": { ...snapshot, items: [], next: "same-page" },
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ const first = yield* provider[method]!(target);
+ const input = { ...target, cursor: first.nextCursor! };
+ const result =
+ method === "getDiff"
+ ? yield* provider.getDiff(input).pipe(Effect.result)
+ : yield* provider.getDiffFilePaths!(input).pipe(Effect.result);
+ assert.strictEqual(result._tag, "Failure");
+ }).pipe(Effect.provide(server.layer));
+ },
+ );
+
+ // getDiff cases guard parity with the existing patch path; getDiffFilePaths must refuse the same pages.
+ it.effect.each(
+ (["getDiff", "getDiffFilePaths"] as const).flatMap((method) =>
+ [{ version: 5 }, { headOid: baseOid }, { comparisonBaseOid: headOid }].map((changed) => ({
+ method,
+ changed,
+ })),
+ ),
+ )(
+ "$method refuses a continuation from a different revision ($changed)",
+ ({ method, changed }) => {
+ const server = fakeGitCafe({
+ "GET /repos/owner/repo/pulls/7": pull,
+ "GET /repos/owner/repo/pulls/7/changes": (request: SentRequest) => ({
+ ...snapshot,
+ ...(request.query.has("after") ? changed : {}),
+ items: [],
+ next: request.query.has("after") ? null : "next-page",
+ }),
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ const read = (cursor?: string) =>
+ method === "getDiff"
+ ? provider.getDiff({ ...target, ...(cursor === undefined ? {} : { cursor }) })
+ : provider.getDiffFilePaths!({
+ ...target,
+ ...(cursor === undefined ? {} : { cursor }),
+ });
+ const first = yield* read();
+ const input = { ...target, cursor: first.nextCursor! };
+ const result =
+ method === "getDiff"
+ ? yield* provider.getDiff(input).pipe(Effect.result)
+ : yield* provider.getDiffFilePaths!(input).pipe(Effect.result);
+ assert.strictEqual(result._tag, "Failure");
+ }).pipe(Effect.provide(server.layer));
+ },
+ );
+
+ it.effect.each(["getDiff", "getDiffFilePaths"] as const)(
+ "%s reads a pull that reports no head yet",
+ (method) => {
+ const server = fakeGitCafe({
+ "GET /repos/owner/repo/pulls/7": { ...pull, headOid: null },
+ "GET /repos/owner/repo/pulls/7/changes": { ...snapshot, items: [], next: null },
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ const result = yield* provider[method]!(target);
+ assert.isNull(result.nextCursor);
+ }).pipe(Effect.provide(server.layer));
+ },
+ );
+
+ it.effect.each([{ version: 5 }, { headOid: baseOid }])(
+ "refuses initial changed paths from a different pull revision (%j)",
+ (changed) => {
+ const server = fakeGitCafe({
+ "GET /repos/owner/repo/pulls/7": pull,
+ "GET /repos/owner/repo/pulls/7/changes": { ...snapshot, ...changed, items: [], next: null },
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitCafePullRequestProvider.make;
+ const result = yield* provider.getDiffFilePaths!(target).pipe(Effect.result);
+ assert.strictEqual(result._tag, "Failure");
+ }).pipe(Effect.provide(server.layer));
+ },
+ );
+});
+
describe("GitCafePullRequestProvider source contents", () => {
const comparisonBase = "a".repeat(40);
const snapshot = { version: pull.version, headOid, comparisonBaseOid: comparisonBase };
diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
index 30e9296d36e..f2aa82fdcb6 100644
--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
@@ -56,6 +56,8 @@ const AUTHOR_DISCOVERY_PAGES = 5;
const KNOWN_AUTHORS_LIMIT = 10_000;
/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
const DIFF_FILES_BATCH = 64;
+/** Changed-path pages carry no hunks, so they can be read in larger pages. */
+const CHANGES_PAGE_LIMIT = 500;
/** Line totals require hunk reads; omit them for large PRs. */
const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
const MAX_CHANGE_PAGES = 20;
@@ -522,6 +524,45 @@ export const make = Effect.gen(function* () {
return { ...stack, members };
});
+ const readDiffPage = Effect.fn("GitCafePullRequestProvider.readDiffPage")(function* (
+ operation: string,
+ input: Parameters<PullRequestProviderApi["getDiff"]>[0],
+ limit: number,
+ ) {
+ if (input.commit !== undefined)
+ return yield* failure(operation, "GitCafe commit diffs are not supported yet.");
+ const cursor =
+ input.cursor === undefined
+ ? null
+ : yield* decodeDiffCursor(input.cursor).pipe(
+ Effect.mapError((cause) => failure(operation, "Invalid GitCafe diff cursor.", cause)),
+ );
+ // A pull without a head yet has nothing to pin; its version still is.
+ const expected = cursor ?? (yield* readPull(operation, input));
+ const version = expected.version;
+ const path = yield* pullPath(operation, input);
+ const query = new URLSearchParams({ expectedVersion: String(version), limit: String(limit) });
+ if (cursor !== null) query.set("after", cursor.after);
+ const page = yield* read(operation, input, { path: `${path}/changes?${query}` }, Changes);
+ if (
+ page.version !== version ||
+ (expected.headOid !== null && page.headOid !== expected.headOid) ||
+ (cursor !== null && cursor.baseOid !== page.comparisonBaseOid)
+ )
+ return yield* failure(
+ operation,
+ "GitCafe answered from a different revision of the pull request. Refresh the diff.",
+ );
+ if (cursor !== null && page.next !== null && page.next === cursor.after)
+ return yield* failure(operation, "GitCafe returned a repeated diff page cursor.");
+ const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
+ return {
+ items: page.items,
+ revision,
+ nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
+ };
+ });
+
const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
input: PullRef,
revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
@@ -605,7 +646,10 @@ export const make = Effect.gen(function* () {
let revision: { version: number; headOid: string; baseOid: string } | undefined;
let after: string | null = null;
for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
- const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
+ const query = new URLSearchParams({
+ expectedVersion: String(version),
+ limit: String(CHANGES_PAGE_LIMIT),
+ });
if (after !== null) query.set("after", after);
const batch: typeof Changes.Type = yield* read(
"getChangeRequest",
@@ -966,36 +1010,21 @@ export const make = Effect.gen(function* () {
getViewerPermissions: (input) =>
readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
- if (input.commit !== undefined)
- return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
- const cursor =
- input.cursor === undefined
- ? null
- : yield* decodeDiffCursor(input.cursor).pipe(
- Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
- );
- const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
- const path = yield* pullPath("getDiff", input);
- const query = new URLSearchParams({
- expectedVersion: String(version),
- limit: String(DIFF_FILES_BATCH),
- });
- if (cursor !== null) query.set("after", cursor.after);
- const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
- if (
- page.version !== version ||
- (cursor !== null &&
- (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
- )
- return yield* failure(
- "getDiff",
- "GitCafe answered from a different revision of the pull request. Refresh the diff.",
- );
- const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
- const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
+ const page = yield* readDiffPage("getDiff", input, DIFF_FILES_BATCH);
+ const details = yield* readDiffFiles(input, page.revision, detailablePaths(page.items));
return {
...Json.toDiff({ items: withDetails(page.items, details) }),
- nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
+ nextCursor: page.nextCursor,
+ };
+ }),
+ getDiffFilePaths: Effect.fn("GitCafePullRequestProvider.getDiffFilePaths")(function* (input) {
+ const page = yield* readDiffPage("getDiffFilePaths", input, CHANGES_PAGE_LIMIT);
+ return {
+ files: page.items.map((file) => ({
+ oldPath: file.oldPath ?? file.path,
+ newPath: file.path,
+ })),
+ nextCursor: page.nextCursor,
};
}),
getDiffFileContents: Effect.fn("GitCafePullRequestProvider.getDiffFileContents")(