diff --git a/bun.lock b/bun.lock
index 7d96870..48c391e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -25,6 +25,7 @@
"@tanstack/react-router": "^1.131.59",
"@tanstack/react-router-devtools": "^1.131.59",
"@tanstack/react-start": "^1.131.59",
+ "@tanstack/react-virtual": "^3.13.18",
"@tanstack/rxdb-db-collection": "^0.1.58",
"@tanstack/store": "^0.8.0",
"class-variance-authority": "^0.7.1",
@@ -758,6 +759,8 @@
"@tanstack/react-store": ["@tanstack/react-store@0.8.0", "", { "dependencies": { "@tanstack/store": "0.8.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-1vG9beLIuB7q69skxK9r5xiLN3ztzIPfSQSs0GfeqWGO2tGIyInZx0x1COhpx97RKaONSoAb8C3dxacWksm1ow=="],
+ "@tanstack/react-virtual": ["@tanstack/react-virtual@3.13.18", "", { "dependencies": { "@tanstack/virtual-core": "3.13.18" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A=="],
+
"@tanstack/router-core": ["@tanstack/router-core@1.136.3", "", { "dependencies": { "@tanstack/history": "1.133.28", "@tanstack/store": "^0.8.0", "cookie-es": "^2.0.0", "seroval": "^1.3.2", "seroval-plugins": "^1.3.2", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" } }, "sha512-trSbUMs41rfd6GPgwR8tSZGvKTKtjEorgKZU1ttlTtCSEa2uyvTslGqPnpUq739w5wxTSqM8BPyf2irhxuJXaQ=="],
"@tanstack/router-devtools-core": ["@tanstack/router-devtools-core@1.159.4", "", { "dependencies": { "clsx": "^2.1.1", "goober": "^2.1.16", "tiny-invariant": "^1.3.3" }, "peerDependencies": { "@tanstack/router-core": "^1.159.4", "csstype": "^3.0.10" }, "optionalPeers": ["csstype"] }, "sha512-qMUeIv+6n1mZOcO2raCIbdOeDeMpJEmgm6oMs/nWEG61lYrzJYaCcpBTviAX0nRhSiQSUCX9cHiosUEA0e2HAw=="],
@@ -782,6 +785,8 @@
"@tanstack/store": ["@tanstack/store@0.8.0", "", {}, "sha512-Om+BO0YfMZe//X2z0uLF2j+75nQga6TpTJgLJQBiq85aOyZNIhkCgleNcud2KQg4k4v9Y9l+Uhru3qWMPGTOzQ=="],
+ "@tanstack/virtual-core": ["@tanstack/virtual-core@3.13.18", "", {}, "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg=="],
+
"@tanstack/virtual-file-routes": ["@tanstack/virtual-file-routes@1.133.19", "", {}, "sha512-IKwZENsK7owmW1Lm5FhuHegY/SyQ8KqtL/7mTSnzoKJgfzhrrf9qwKB1rmkKkt+svUuy/Zw3uVEpZtUzQruWtA=="],
"@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
diff --git a/package.json b/package.json
index eb8b34e..169e71d 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"@tanstack/react-router": "^1.131.59",
"@tanstack/react-router-devtools": "^1.131.59",
"@tanstack/react-start": "^1.131.59",
+ "@tanstack/react-virtual": "^3.13.18",
"@tanstack/rxdb-db-collection": "^0.1.58",
"@tanstack/store": "^0.8.0",
"class-variance-authority": "^0.7.1",
diff --git a/src/components/file-tree.tsx b/src/components/file-tree.tsx
index 8e43d12..d8f43ed 100644
--- a/src/components/file-tree.tsx
+++ b/src/components/file-tree.tsx
@@ -12,6 +12,7 @@ import {
SlidersHorizontal,
SwatchBook,
} from "lucide-react";
+import { memo, useMemo } from "react";
import { GitHostIcon } from "@/components/git-host-icon";
import { RepositoryFileIcon } from "@/components/repository-file-icon";
import { type ChangeKind, type FileNode, useFileTree } from "@/lib/file-tree-context";
@@ -110,29 +111,29 @@ export function FileTree({
const active = activeFile ?? tree.activeFile;
const treeIndentSize = tree.treeIndentSize;
const normalizedQuery = filterQuery?.trim().toLowerCase() ?? "";
-
- const matchesNode = (node: FileNode): boolean => {
- if (node.type === "summary") {
- if (!normalizedQuery) return true;
- const summarySearch = `${node.name} ${node.path}`.toLowerCase();
- return summarySearch.includes(normalizedQuery);
- }
- if (node.type === "file") {
- const queryMatch = !normalizedQuery || node.path.toLowerCase().includes(normalizedQuery);
- const allowedMatch = !allowedFiles || allowedFiles.has(node.path);
- return queryMatch && allowedMatch;
- }
- const children = tree.getChildrenForPath(node.path);
- const host = hostFromTreePath(node.path);
- if (host && children.length === 0) {
- if (!normalizedQuery) return true;
- const hostSearch = `${node.name} ${node.path}`.toLowerCase();
- return hostSearch.includes(normalizedQuery);
- }
- return children.some(matchesNode);
- };
-
- const nodes = rawNodes.filter(matchesNode);
+ const nodes = useMemo(() => {
+ const matchesNode = (node: FileNode): boolean => {
+ if (node.type === "summary") {
+ if (!normalizedQuery) return true;
+ const summarySearch = `${node.name} ${node.path}`.toLowerCase();
+ return summarySearch.includes(normalizedQuery);
+ }
+ if (node.type === "file") {
+ const queryMatch = !normalizedQuery || node.path.toLowerCase().includes(normalizedQuery);
+ const allowedMatch = !allowedFiles || allowedFiles.has(node.path);
+ return queryMatch && allowedMatch;
+ }
+ const children = tree.getChildrenForPath(node.path);
+ const host = hostFromTreePath(node.path);
+ if (host && children.length === 0) {
+ if (!normalizedQuery) return true;
+ const hostSearch = `${node.name} ${node.path}`.toLowerCase();
+ return hostSearch.includes(normalizedQuery);
+ }
+ return children.some(matchesNode);
+ };
+ return rawNodes.filter(matchesNode);
+ }, [allowedFiles, normalizedQuery, rawNodes, tree]);
return (
@@ -288,7 +289,7 @@ function DirectoryNode({
);
}
-function FileNodeRow({
+const FileNodeRow = memo(function FileNodeRow({
node,
level,
treeIndentSize,
@@ -352,4 +353,40 @@ function FileNodeRow({
{node.name}
);
+}, areFileNodeRowPropsEqual);
+
+function areFileNodeRowPropsEqual(
+ previous: Readonly<{
+ node: FileNode;
+ level: number;
+ treeIndentSize: number;
+ kinds: ReadonlyMap
;
+ active?: string;
+ viewed?: boolean;
+ onFileClick?: (node: FileNode) => void;
+ showUnviewedIndicator: boolean;
+ }>,
+ next: Readonly<{
+ node: FileNode;
+ level: number;
+ treeIndentSize: number;
+ kinds: ReadonlyMap;
+ active?: string;
+ viewed?: boolean;
+ onFileClick?: (node: FileNode) => void;
+ showUnviewedIndicator: boolean;
+ }>,
+) {
+ if (previous.node !== next.node) return false;
+ if (previous.level !== next.level) return false;
+ if (previous.treeIndentSize !== next.treeIndentSize) return false;
+ if (previous.viewed !== next.viewed) return false;
+ if (previous.onFileClick !== next.onFileClick) return false;
+ if (previous.showUnviewedIndicator !== next.showUnviewedIndicator) return false;
+ const previousWasActive = previous.active === previous.node.path;
+ const nextIsActive = next.active === next.node.path;
+ if (previousWasActive !== nextIsActive) return false;
+ const previousKind = previous.node.type === "summary" ? undefined : previous.kinds.get(previous.node.path);
+ const nextKind = next.node.type === "summary" ? undefined : next.kinds.get(next.node.path);
+ return previousKind === nextKind;
}
diff --git a/src/components/pull-request-review-page.tsx b/src/components/pull-request-review-page.tsx
index aab0d76..7627f12 100644
--- a/src/components/pull-request-review-page.tsx
+++ b/src/components/pull-request-review-page.tsx
@@ -1,2 +1,10 @@
-// Keep the historical import path stable while the implementation is extracted.
-export { PullRequestReviewPage } from "@/components/pull-request-review/review-page";
+import { PullRequestReviewPage as PullRequestReviewPageInner } from "@/components/pull-request-review/review-page";
+import { ReviewPerformanceProviders } from "@/components/pull-request-review/review-performance-providers";
+
+export function PullRequestReviewPage(props: Parameters[0]) {
+ return (
+
+
+
+ );
+}
diff --git a/src/components/pull-request-review/review-all-mode-view.tsx b/src/components/pull-request-review/review-all-mode-view.tsx
index 8620704..488c165 100644
--- a/src/components/pull-request-review/review-all-mode-view.tsx
+++ b/src/components/pull-request-review/review-all-mode-view.tsx
@@ -1,7 +1,9 @@
import type { FileDiffOptions, OnDiffLineClickProps, OnDiffLineEnterLeaveProps } from "@pierre/diffs";
import { FileDiff, type FileDiffMetadata } from "@pierre/diffs/react";
+import { useVirtualizer } from "@tanstack/react-virtual";
import { Check, CheckCheck, ChevronDown, ChevronRight, Copy, ScrollText } from "lucide-react";
-import type { CSSProperties } from "react";
+import type { CSSProperties, RefObject } from "react";
+import { useEffect, useMemo } from "react";
import { PullRequestSummaryPanel } from "@/components/pr-summary-panel";
import { DiffContextButton, type DiffContextState } from "@/components/pull-request-review/diff-context-button";
import { FileVersionSelect, type FileVersionSelectOption } from "@/components/pull-request-review/file-version-select";
@@ -74,6 +76,8 @@ type ReviewAllModeViewProps = {
onOpenDiffSettings: () => void;
onLoadFullFileContext: (path: string, fileDiff: FileDiffMetadata) => void;
fileContextState: Record;
+ scrollElementRef: RefObject;
+ pendingScrollPath: string | null;
};
export function ReviewAllModeView({
@@ -130,8 +134,28 @@ export function ReviewAllModeView({
onOpenDiffSettings,
onLoadFullFileContext,
fileContextState,
+ scrollElementRef,
+ pendingScrollPath,
}: ReviewAllModeViewProps) {
const diffListBottomPadding = "max(420px, 90vh)";
+ const filePathsInOrder = useMemo(() => allModeDiffEntries.map((entry) => entry.filePath), [allModeDiffEntries]);
+ const rowVirtualizer = useVirtualizer({
+ count: allModeDiffEntries.length,
+ getScrollElement: () => scrollElementRef.current,
+ estimateSize: () => 420,
+ overscan: 4,
+ });
+ const virtualRows = rowVirtualizer.getVirtualItems();
+ const paddingTop = virtualRows.length > 0 ? (virtualRows[0]?.start ?? 0) : 0;
+ const paddingBottom =
+ virtualRows.length > 0 ? Math.max(0, rowVirtualizer.getTotalSize() - (virtualRows[virtualRows.length - 1]?.end ?? 0)) : rowVirtualizer.getTotalSize();
+
+ useEffect(() => {
+ if (!pendingScrollPath) return;
+ const index = filePathsInOrder.indexOf(pendingScrollPath);
+ if (index < 0) return;
+ rowVirtualizer.scrollToIndex(index, { align: "start" });
+ }, [filePathsInOrder, pendingScrollPath, rowVirtualizer]);
return (
{prData ? (
@@ -190,7 +214,11 @@ export function ReviewAllModeView({
) : null}
- {allModeDiffEntries.map(({ fileDiff, filePath }, index) => {
+ {paddingTop > 0 ? : null}
+ {virtualRows.map((virtualRow) => {
+ const entry = allModeDiffEntries[virtualRow.index];
+ if (!entry) return null;
+ const { fileDiff, filePath } = entry;
const fileUnresolvedCount = (threadsByPath.get(filePath) ?? []).filter((thread) => !thread.root.resolution && !thread.root.deleted).length;
const fileStats = fileLineStats.get(filePath) ?? { added: 0, removed: 0 };
const fileName = filePath.split("/").pop() || filePath;
@@ -211,132 +239,138 @@ export function ReviewAllModeView({
: compactDiffOptions;
return (
-
+
-
-
-
- onSelectVersionForPath(filePath, versionId)}
- onOpenChange={(open) => {
- if (!open) return;
- onOpenVersionMenuForPath(filePath);
- }}
- />
- onLoadFullFileContext(filePath, fileDiff)}
- disabled={readOnlyHistorical}
- />
-
-
- +{fileStats.added}
- -{fileStats.removed}
- {fileUnresolvedCount > 0 ? {fileUnresolvedCount} unresolved : null}
-
-
-
-
- {isCollapsed ? : }
-
-
- {!isCollapsed ? (
-
- {diffHighlighterReady && displayedFileDiff ? (
-
{
- if (readOnlyHistorical) return;
- onOpenInlineDraftForPath(filePath, props);
- },
- onLineNumberClick: (props) => {
- if (readOnlyHistorical) return;
- onOpenInlineDraftForPath(filePath, props);
- },
- onLineEnter: onDiffLineEnter,
- onLineLeave: onDiffLineLeave,
+
+
+
+
onSelectVersionForPath(filePath, versionId)}
+ onOpenChange={(open) => {
+ if (!open) return;
+ onOpenVersionMenuForPath(filePath);
}}
- className="compact-diff commentable-diff pr-diff-font"
- style={diffTypographyStyle}
- lineAnnotations={readOnlyHistorical ? [] : buildFileAnnotations(filePath)}
- renderAnnotation={(annotation) => (
-
- )}
/>
- ) : (
-
- Loading syntax highlighting...
-
- )}
+ onLoadFullFileContext(filePath, fileDiff)}
+ disabled={readOnlyHistorical}
+ />
+
+
+ +{fileStats.added}
+ -{fileStats.removed}
+ {fileUnresolvedCount > 0 ? {fileUnresolvedCount} unresolved : null}
+
+
+
+
+ {isCollapsed ? : }
+
- ) : null}
+ {!isCollapsed ? (
+
+ {diffHighlighterReady && displayedFileDiff ? (
+
{
+ if (readOnlyHistorical) return;
+ onOpenInlineDraftForPath(filePath, props);
+ },
+ onLineNumberClick: (props) => {
+ if (readOnlyHistorical) return;
+ onOpenInlineDraftForPath(filePath, props);
+ },
+ onLineEnter: onDiffLineEnter,
+ onLineLeave: onDiffLineLeave,
+ }}
+ className="compact-diff commentable-diff pr-diff-font"
+ style={diffTypographyStyle}
+ lineAnnotations={readOnlyHistorical ? [] : buildFileAnnotations(filePath)}
+ renderAnnotation={(annotation) => (
+
+ )}
+ />
+ ) : (
+
+ Loading syntax highlighting...
+
+ )}
+
+ ) : null}
+
);
})}
+ {paddingBottom > 0 ? : null}
{allModeDiffEntries.length === 0 ? (
No files match the current search.
diff --git a/src/components/pull-request-review/review-page-diff-content.tsx b/src/components/pull-request-review/review-page-diff-content.tsx
index 1a86f3d..f78d390 100644
--- a/src/components/pull-request-review/review-page-diff-content.tsx
+++ b/src/components/pull-request-review/review-page-diff-content.tsx
@@ -1,6 +1,6 @@
import type { FileDiffOptions } from "@pierre/diffs";
import type { FileDiffMetadata } from "@pierre/diffs/react";
-import type { CSSProperties } from "react";
+import type { CSSProperties, RefObject } from "react";
import type { DiffContextState } from "@/components/pull-request-review/diff-context-button";
import type { FileVersionSelectOption } from "@/components/pull-request-review/file-version-select";
import { ReviewAllModeView } from "@/components/pull-request-review/review-all-mode-view";
@@ -80,6 +80,8 @@ type ReviewPageDiffContentProps = {
onDiffLineEnter: NonNullable["onLineEnter"]>;
onDiffLineLeave: NonNullable["onLineLeave"]>;
onHistoryCommentNavigate: (payload: { path: string; line?: number; side?: "additions" | "deletions"; commentId?: number }) => void;
+ scrollElementRef: RefObject;
+ pendingScrollPath: string | null;
};
export function ReviewPageDiffContent({
@@ -146,6 +148,8 @@ export function ReviewPageDiffContent({
onDiffLineEnter,
onDiffLineLeave,
onHistoryCommentNavigate,
+ scrollElementRef,
+ pendingScrollPath,
}: ReviewPageDiffContentProps) {
const openDiffSettings = () => {
onActiveFileChange(settingsPathForTab("diff"));
@@ -284,6 +288,8 @@ export function ReviewPageDiffContent({
onOpenDiffSettings={openDiffSettings}
onLoadFullFileContext={onLoadFullFileContext}
fileContextState={fileContextState}
+ scrollElementRef={scrollElementRef}
+ pendingScrollPath={pendingScrollPath}
/>
);
}
diff --git a/src/components/pull-request-review/review-page-model.ts b/src/components/pull-request-review/review-page-model.ts
index 9e52348..8d2fabe 100644
--- a/src/components/pull-request-review/review-page-model.ts
+++ b/src/components/pull-request-review/review-page-model.ts
@@ -1,7 +1,7 @@
import type { FileDiffMetadata } from "@pierre/diffs/react";
import type { InlineCommentDraft } from "@/components/pull-request-review/use-inline-comment-drafts";
import type { FileNode } from "@/lib/file-tree-context";
-import type { Comment as PullRequestComment } from "@/lib/git-host/types";
+import type { Comment as PullRequestComment, PullRequestRef } from "@/lib/git-host/types";
import type { CommentThread } from "./review-threads";
export type CommentLineSide = "additions" | "deletions";
@@ -53,3 +53,35 @@ export function collectDirectoryPaths(nodes: FileNode[]) {
walk(nodes);
return paths;
}
+
+export function hashString(value: string) {
+ let hash1 = 0x811c9dc5;
+ let hash2 = 0x01000193;
+ for (let i = 0; i < value.length; i += 1) {
+ const char = value.charCodeAt(i);
+ hash1 = Math.imul(hash1 ^ char, 0x01000193);
+ hash2 = Math.imul(hash2 ^ (char + i), 0x01000193);
+ }
+ return `${(hash1 >>> 0).toString(16)}${(hash2 >>> 0).toString(16)}`;
+}
+
+export function buildReviewScopeCacheKey(prRef: PullRequestRef, scopeKey: string) {
+ return `${prRef.host}:${prRef.workspace}/${prRef.repo}/${prRef.pullRequestId}:${scopeKey}`;
+}
+
+function commentSignature(comments: PullRequestComment[]) {
+ return comments
+ .map((comment) => {
+ const path = comment.inline?.path ?? "";
+ const line = comment.inline?.to ?? comment.inline?.from ?? 0;
+ const updatedAt = comment.updatedAt ?? comment.createdAt ?? "";
+ return `${comment.id}:${path}:${line}:${updatedAt}:${comment.parent?.id ?? 0}:${comment.deleted ? 1 : 0}`;
+ })
+ .join("|");
+}
+
+export function buildReviewDerivedCacheKey({ scopeCacheKey, diffText, comments }: { scopeCacheKey: string; diffText: string; comments: PullRequestComment[] }) {
+ const diffHash = hashString(diffText);
+ const commentsHash = hashString(commentSignature(comments));
+ return `${scopeCacheKey}:${diffHash}:${commentsHash}`;
+}
diff --git a/src/components/pull-request-review/review-page.tsx b/src/components/pull-request-review/review-page.tsx
index 8bdfa5b..f6312de 100644
--- a/src/components/pull-request-review/review-page.tsx
+++ b/src/components/pull-request-review/review-page.tsx
@@ -2,7 +2,18 @@ import { type FileDiffOptions, type OnDiffLineClickProps, parsePatchFiles } from
import type { FileDiffMetadata } from "@pierre/diffs/react";
import { useLiveQuery } from "@tanstack/react-db";
import { useNavigate } from "@tanstack/react-router";
-import { type CSSProperties, type ReactNode, type SetStateAction, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import {
+ type CSSProperties,
+ type ReactNode,
+ type SetStateAction,
+ startTransition,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
import type { DiffContextState } from "@/components/pull-request-review/diff-context-button";
import type { FileVersionSelectOption } from "@/components/pull-request-review/file-version-select";
import { ReviewCommitScopeControl } from "@/components/pull-request-review/review-commit-scope-control";
@@ -11,7 +22,7 @@ import { ReviewPageDiffContent } from "@/components/pull-request-review/review-p
import { ReviewPageAuthRequiredState, ReviewPageErrorState } from "@/components/pull-request-review/review-page-guards";
import { ReviewPageLoadingView } from "@/components/pull-request-review/review-page-loading-view";
import { ReviewPageMainView } from "@/components/pull-request-review/review-page-main-view";
-import type { SingleFileAnnotation } from "@/components/pull-request-review/review-page-model";
+import { hashString, type SingleFileAnnotation } from "@/components/pull-request-review/review-page-model";
import { useInlineCommentDrafts } from "@/components/pull-request-review/use-inline-comment-drafts";
import { useReviewLayoutPreferences } from "@/components/pull-request-review/use-review-layout-preferences";
import { useReviewPageActions } from "@/components/pull-request-review/use-review-page-actions";
@@ -57,6 +68,7 @@ import { fetchPullRequestFileContents } from "@/lib/git-host/service";
import type { GitHost } from "@/lib/git-host/types";
import { PR_SUMMARY_PATH } from "@/lib/pr-summary";
import { diffScopeStorageSegment, type ReviewDiffScopeSearch, resolveReviewDiffScope } from "@/lib/review-diff-scope";
+import { markReviewPerf } from "@/lib/review-performance/metrics";
import { makeDirectoryStateStorageKey } from "@/lib/review-storage";
interface PullRequestReviewPageProps {
@@ -96,11 +108,24 @@ function commitVersionId(path: string, commitHash: string) {
return `${path}:${commitHash}`;
}
+const singlePatchParseCache = new Map();
+
function parseSingleFilePatch(patch: string) {
if (!patch) return undefined;
+ const cacheKey = hashString(patch);
+ if (singlePatchParseCache.has(cacheKey)) {
+ return singlePatchParseCache.get(cacheKey);
+ }
const parsed = parsePatchFiles(patch);
const firstPatch = parsed[0];
const firstFile = firstPatch?.files?.[0];
+ if (singlePatchParseCache.size > 300) {
+ const firstKey = singlePatchParseCache.keys().next().value;
+ if (firstKey) {
+ singlePatchParseCache.delete(firstKey);
+ }
+ }
+ singlePatchParseCache.set(cacheKey, firstFile);
return firstFile;
}
@@ -207,19 +232,23 @@ function usePullRequestReviewPageView({
const copiedSourceBranch = useReviewPageUiValue(uiStore, (state) => state.copiedSourceBranch);
const setSearchQuery = useCallback(
(next: SetStateAction) => {
- uiStore.setState((prev) => ({
- ...prev,
- searchQuery: typeof next === "function" ? (next as (current: string) => string)(prev.searchQuery) : next,
- }));
+ startTransition(() => {
+ uiStore.setState((prev) => ({
+ ...prev,
+ searchQuery: typeof next === "function" ? (next as (current: string) => string)(prev.searchQuery) : next,
+ }));
+ });
},
[uiStore],
);
const setShowUnviewedOnly = useCallback(
(next: SetStateAction) => {
- uiStore.setState((prev) => ({
- ...prev,
- showUnviewedOnly: typeof next === "function" ? (next as (current: boolean) => boolean)(prev.showUnviewedOnly) : next,
- }));
+ startTransition(() => {
+ uiStore.setState((prev) => ({
+ ...prev,
+ showUnviewedOnly: typeof next === "function" ? (next as (current: boolean) => boolean)(prev.showUnviewedOnly) : next,
+ }));
+ });
},
[uiStore],
);
@@ -307,8 +336,10 @@ function usePullRequestReviewPageView({
const allModeLastStickyPathRef = useRef(null);
const suppressHashSyncRef = useRef(false);
const pendingCommentScrollRef = useRef(null);
- const loadedViewedStorageKeyRef = useRef("");
+ const loadedViewedStateRevisionRef = useRef("");
+ const skipViewedStatePersistRevisionRef = useRef("");
const loadedHistoryRevisionRef = useRef("");
+ const firstDiffRenderedKeyRef = useRef("");
const { inlineComment, setInlineComment, getInlineDraftContent, setInlineDraftContent, clearInlineDraftContent, openInlineCommentDraft } =
useInlineCommentDrafts({
workspace,
@@ -317,7 +348,13 @@ function usePullRequestReviewPageView({
setActiveFile,
setViewMode,
});
- const { hostCapabilities, query: prQuery } = useReviewQuery({
+ const {
+ hostCapabilities,
+ isCriticalLoading,
+ isDeferredLoading,
+ isRefreshing,
+ query: prQuery,
+ } = useReviewQuery({
host,
workspace,
repo,
@@ -334,10 +371,10 @@ function usePullRequestReviewPageView({
const pullRequest = basePrData?.pr;
const pullRequestUrl = pullRequest?.links?.html?.href;
const pullRequestTitle = pullRequest?.title?.trim();
- const isPrQueryFetching = prQuery.isFetching;
+ const isPrQueryFetching = isRefreshing || isDeferredLoading;
const refetchPrQuery = prQuery.refetch;
const isRateLimitedError = isRateLimitedQueryError(prQuery.error);
- useReviewDocumentTitle({ isLoading: prQuery.isLoading, pullRequestTitle });
+ useReviewDocumentTitle({ isLoading: isCriticalLoading, pullRequestTitle });
const directoryStateStorageKey = useMemo(() => makeDirectoryStateStorageKey(workspace, repo, pullRequestId), [pullRequestId, repo, workspace]);
const prRef = useMemo(() => ({ host, workspace, repo, pullRequestId }), [host, workspace, repo, pullRequestId]);
@@ -610,6 +647,7 @@ function usePullRequestReviewPageView({
const openInlineCommentDraftForPath = useCallback(
(path: string, props: OnDiffLineClickProps) => {
if (resolvedScope.mode !== "full") return;
+ markReviewPerf("inline_comment_open");
openInlineCommentDraft({
path,
line: props.lineNumber,
@@ -724,6 +762,11 @@ function usePullRequestReviewPageView({
}
return map;
}, [fileDiffFingerprints]);
+ const viewedStateLoadRevision = useMemo(() => {
+ if (!viewedStorageKey) return "";
+ const sortedVersionIds = Array.from(latestVersionIdByPath.values()).sort();
+ return `${viewedStorageKey}:${sortedVersionIds.length}:${hashString(sortedVersionIds.join("|"))}`;
+ }, [latestVersionIdByPath, viewedStorageKey]);
const historyRevision = `${effectiveBaseCommitHash ?? ""}:${effectiveHeadCommitHash ?? ""}`;
const resetHistoryTracking = useCallback(() => {
@@ -734,8 +777,11 @@ function usePullRequestReviewPageView({
useEffect(() => {
if (!viewedStorageKey || typeof window === "undefined") return;
- if (loadedViewedStorageKeyRef.current === viewedStorageKey) return;
- loadedViewedStorageKeyRef.current = viewedStorageKey;
+ if (prData?.diffstat.length && latestVersionIdByPath.size === 0) return;
+ if (loadedViewedStateRevisionRef.current === viewedStateLoadRevision) return;
+ loadedViewedStateRevisionRef.current = viewedStateLoadRevision;
+ // Prevent persisting stale viewedFiles from the previous scope/key during the same commit.
+ skipViewedStatePersistRevisionRef.current = viewedStateLoadRevision;
autoMarkedViewedVersionIdsRef.current = new Set();
const knownVersionIds = new Set(latestVersionIdByPath.values());
const viewedIds = readViewedVersionIds(viewedStorageKey, {
@@ -750,7 +796,7 @@ function usePullRequestReviewPageView({
}
setViewedFiles(nextViewedFiles);
resetHistoryTracking();
- }, [fileDiffFingerprints, latestVersionIdByPath, resetHistoryTracking, viewedStorageKey]);
+ }, [fileDiffFingerprints, latestVersionIdByPath, prData?.diffstat.length, resetHistoryTracking, viewedStateLoadRevision, viewedStorageKey]);
useEffect(() => {
if (loadedHistoryRevisionRef.current === historyRevision) return;
@@ -761,6 +807,12 @@ function usePullRequestReviewPageView({
useEffect(() => {
if (!viewedStorageKey || typeof window === "undefined") return;
+ if (prData?.diffstat.length && latestVersionIdByPath.size === 0) return;
+ if (loadedViewedStateRevisionRef.current !== viewedStateLoadRevision) return;
+ if (skipViewedStatePersistRevisionRef.current === viewedStateLoadRevision) {
+ skipViewedStatePersistRevisionRef.current = "";
+ return;
+ }
const viewedVersionIds = new Set();
for (const viewedPath of viewedFiles) {
const latestVersionId = latestVersionIdByPath.get(viewedPath);
@@ -768,7 +820,7 @@ function usePullRequestReviewPageView({
viewedVersionIds.add(latestVersionId);
}
writeViewedVersionIds(viewedStorageKey, viewedVersionIds);
- }, [latestVersionIdByPath, viewedFiles, viewedStorageKey]);
+ }, [latestVersionIdByPath, prData?.diffstat.length, viewedFiles, viewedStateLoadRevision, viewedStorageKey]);
useEffect(() => {
setSelectedVersionIdByPath((prev) => {
@@ -1002,6 +1054,29 @@ function usePullRequestReviewPageView({
: { fileDiff: selectedFileDiff, readOnlyHistorical: false, selectedVersionId: undefined },
[resolveDisplayedDiffForPath, selectedFileDiff, selectedFilePath],
);
+ const hasRenderableSingleDiff = Boolean(selectedFileDisplayState.fileDiff) && !isSummarySelected;
+ const hasRenderableAllDiffs = allModeDiffEntries.length > 0;
+ useEffect(() => {
+ const renderKey = `${prContextKey}:${resolvedScope.mode}:${viewMode}`;
+ if (firstDiffRenderedKeyRef.current === renderKey) return;
+ if (!diffHighlighterReady) return;
+ if (showSettingsPanel) return;
+ const canMark =
+ viewMode === "single" ? hasRenderableSingleDiff : (prData ? !isSummaryCollapsedInAllMode || hasRenderableAllDiffs : false) || hasRenderableAllDiffs;
+ if (!canMark) return;
+ firstDiffRenderedKeyRef.current = renderKey;
+ markReviewPerf("first_diff_rendered");
+ }, [
+ diffHighlighterReady,
+ hasRenderableAllDiffs,
+ hasRenderableSingleDiff,
+ isSummaryCollapsedInAllMode,
+ prContextKey,
+ prData,
+ resolvedScope.mode,
+ showSettingsPanel,
+ viewMode,
+ ]);
const allDiffFilePaths = useMemo(() => Array.from(selectableDiffPathSet), [selectableDiffPathSet]);
const unviewedFileCount = useMemo(
@@ -1232,6 +1307,7 @@ function usePullRequestReviewPageView({
allModeLastStickyPathRef.current = null;
}
if (isSameActiveFile) return;
+ markReviewPerf("all_mode_scroll_update");
revealTreePath(path);
suppressHashSyncRef.current = true;
setActiveFile(path);
@@ -1528,11 +1604,11 @@ function usePullRequestReviewPageView({
inlineDraftFocusRef,
});
- if (prQuery.isLoading) {
+ if (isCriticalLoading) {
return ;
}
- if (prQuery.error) {
+ if (prQuery.error && !prData) {
const errorMessage = prQuery.error instanceof Error ? prQuery.error.message : "Failed to load pull request";
const showAuthPrompt = isRateLimitedError && !auth.canWrite;
@@ -1634,16 +1710,24 @@ function usePullRequestReviewPageView({
submitThreadReply(commentId, content);
}}
onHistoryCommentNavigate={handleHistoryCommentNavigate}
- onToggleSummaryCollapsed={() => setIsSummaryCollapsedInAllMode((prev) => !prev)}
+ onToggleSummaryCollapsed={() =>
+ startTransition(() => {
+ setIsSummaryCollapsedInAllMode((prev) => !prev);
+ })
+ }
onToggleCollapsedFile={(path, next) =>
- setCollapsedAllModeFiles((prev) => ({
- ...prev,
- [path]: next,
- }))
+ startTransition(() => {
+ setCollapsedAllModeFiles((prev) => ({
+ ...prev,
+ [path]: next,
+ }));
+ })
}
onOpenInlineDraftForPath={openInlineCommentDraftForPath}
onDiffLineEnter={handleDiffLineEnter}
onDiffLineLeave={handleDiffLineLeave}
+ scrollElementRef={diffScrollRef}
+ pendingScrollPath={allModePendingScrollPath}
/>
}
mergeDialogProps={mergeDialogProps}
diff --git a/src/components/pull-request-review/review-performance-providers.tsx b/src/components/pull-request-review/review-performance-providers.tsx
new file mode 100644
index 0000000..ab4b2d3
--- /dev/null
+++ b/src/components/pull-request-review/review-performance-providers.tsx
@@ -0,0 +1,76 @@
+import { useWorkerPool, WorkerPoolContextProvider } from "@pierre/diffs/react";
+import DiffsPortableWorker from "@pierre/diffs/worker/worker-portable.js?worker";
+import { type ReactNode, useEffect, useMemo } from "react";
+import { useDiffOptions } from "@/lib/diff-options-context";
+import { ensureLongTaskObserver, setWorkerQueueDepth } from "@/lib/review-performance/metrics";
+import { ReviewComputeWorkerProvider } from "@/lib/review-performance/review-compute-worker-context";
+import { ShikiAppThemeSync } from "@/lib/shiki-app-theme-sync";
+
+const TOKENIZE_MAX_LINE_LENGTH = 4_000;
+
+function ReviewWorkerRenderOptionsSync() {
+ const { options } = useDiffOptions();
+ const workerPool = useWorkerPool();
+
+ useEffect(() => {
+ if (!workerPool) return;
+ void workerPool.setRenderOptions({
+ theme: options.theme,
+ lineDiffType: options.lineDiffType,
+ tokenizeMaxLineLength: TOKENIZE_MAX_LINE_LENGTH,
+ });
+ }, [options.lineDiffType, options.theme, workerPool]);
+
+ useEffect(() => {
+ if (!workerPool) return;
+
+ const updateStats = () => {
+ const stats = workerPool.getStats();
+ setWorkerQueueDepth(stats.queuedTasks + stats.pendingTasks);
+ };
+
+ updateStats();
+ const intervalId = window.setInterval(updateStats, 250);
+ return () => {
+ window.clearInterval(intervalId);
+ };
+ }, [workerPool]);
+
+ return null;
+}
+
+export function ReviewPerformanceProviders({ children }: { children: ReactNode }) {
+ const { options } = useDiffOptions();
+
+ const workerPoolOptions = useMemo(() => {
+ const hardwareConcurrency = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
+ return {
+ workerFactory: () => new DiffsPortableWorker(),
+ poolSize: Math.max(2, Math.min(8, hardwareConcurrency - 1)),
+ };
+ }, []);
+
+ const highlighterOptions = useMemo(
+ () => ({
+ theme: options.theme,
+ lineDiffType: options.lineDiffType,
+ tokenizeMaxLineLength: TOKENIZE_MAX_LINE_LENGTH,
+ langs: ["text", "javascript"] as Array<"text" | "javascript">,
+ }),
+ [options.lineDiffType, options.theme],
+ );
+
+ useEffect(() => {
+ ensureLongTaskObserver();
+ }, []);
+
+ return (
+
+
+
+
+ {children}
+
+
+ );
+}
diff --git a/src/components/pull-request-review/use-review-page-derived.ts b/src/components/pull-request-review/use-review-page-derived.ts
index 6e68ecb..ee30d33 100644
--- a/src/components/pull-request-review/use-review-page-derived.ts
+++ b/src/components/pull-request-review/use-review-page-derived.ts
@@ -1,26 +1,41 @@
import { type FileDiffOptions, getFiletypeFromFileName, type OnDiffLineClickProps, type OnDiffLineEnterLeaveProps, parsePatchFiles } from "@pierre/diffs";
import type { FileDiffMetadata } from "@pierre/diffs/react";
-import { useCallback, useMemo } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { formatNavbarDate, linesUpdated, normalizeNavbarState } from "@/components/pull-request-review/review-formatters";
import { useDiffHighlighterState } from "@/components/pull-request-review/use-review-page-effects";
+import { readReviewDerivedCacheValue, writeReviewDerivedCacheValue } from "@/lib/data/query-collections";
import type { FileNode } from "@/lib/file-tree-context";
import type { PullRequestBundle, PullRequestDetails } from "@/lib/git-host/types";
import { PR_SUMMARY_PATH } from "@/lib/pr-summary";
-import { collectDirectoryPaths, getCommentInlinePosition, getCommentPath, getFilePath, type SingleFileAnnotation } from "./review-page-model";
+import { useReviewComputeWorker } from "@/lib/review-performance/review-compute-worker-context";
+import {
+ buildReviewDerivedCacheKey,
+ buildReviewScopeCacheKey,
+ collectDirectoryPaths,
+ getCommentInlinePosition,
+ getCommentPath,
+ getFilePath,
+ hashString,
+ type SingleFileAnnotation,
+} from "./review-page-model";
import type { CommentThread } from "./review-threads";
-import { buildCommentThreads, sortThreadsByCreatedAt } from "./review-threads";
+import { sortThreadsByCreatedAt } from "./review-threads";
import type { InlineCommentDraft } from "./use-inline-comment-drafts";
-function hashString(value: string) {
- let hash1 = 0x811c9dc5;
- let hash2 = 0x01000193;
- for (let i = 0; i < value.length; i += 1) {
- const char = value.charCodeAt(i);
- hash1 = Math.imul(hash1 ^ char, 0x01000193);
- hash2 = Math.imul(hash2 ^ (char + i), 0x01000193);
- }
- return `${(hash1 >>> 0).toString(16)}${(hash2 >>> 0).toString(16)}`;
-}
+type CachedReviewDerivedArtifacts = {
+ fileDiffs: FileDiffMetadata[];
+ fileDiffFingerprints: Array<[string, string]>;
+ threads: CommentThread[];
+};
+
+type WorkerDerivedState = {
+ cacheKey: string;
+ fileDiffs: FileDiffMetadata[];
+ fileDiffFingerprints: Map;
+ threads: CommentThread[];
+};
+
+const EMPTY_COMMENTS: PullRequestBundle["comments"] = [];
function buildFileDiffFingerprint(fileDiff: FileDiffMetadata) {
const normalized = {
@@ -80,12 +95,141 @@ export function useReviewPageDerived({
fullFileContexts: Record;
}) {
const diffText = prData?.diff ?? "";
+ const comments = prData?.comments ?? EMPTY_COMMENTS;
+ const { computeReviewDerived } = useReviewComputeWorker();
+ const [workerDerived, setWorkerDerived] = useState({
+ cacheKey: "",
+ fileDiffs: [],
+ fileDiffFingerprints: new Map(),
+ threads: [],
+ });
+ const pendingDerivedCacheKeyRef = useRef(null);
+
+ const applyWorkerDerived = useCallback((cacheKey: string, next: Omit) => {
+ pendingDerivedCacheKeyRef.current = null;
+ setWorkerDerived((prev) => {
+ if (prev.cacheKey === cacheKey) return prev;
+ return {
+ cacheKey,
+ ...next,
+ };
+ });
+ }, []);
+
+ const scopeCacheKey = useMemo(() => {
+ if (!prData?.prRef) return "review:empty";
+ return buildReviewScopeCacheKey(prData.prRef, "review-derived");
+ }, [prData?.prRef]);
+
+ const derivedCacheKey = useMemo(
+ () =>
+ buildReviewDerivedCacheKey({
+ scopeCacheKey,
+ diffText,
+ comments,
+ }),
+ [comments, diffText, scopeCacheKey],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+
+ if (workerDerived.cacheKey === derivedCacheKey) {
+ return;
+ }
- const rawFileDiffs = useMemo(() => {
- if (!diffText) return [] as FileDiffMetadata[];
- const patches = parsePatchFiles(diffText);
- return patches.flatMap((patch) => patch.files);
- }, [diffText]);
+ if (!diffText && comments.length === 0) {
+ applyWorkerDerived(derivedCacheKey, {
+ fileDiffs: [],
+ fileDiffFingerprints: new Map(),
+ threads: [],
+ });
+ return;
+ }
+
+ const cachedArtifacts = readReviewDerivedCacheValue(derivedCacheKey);
+ if (cachedArtifacts) {
+ applyWorkerDerived(derivedCacheKey, {
+ fileDiffs: cachedArtifacts.fileDiffs,
+ fileDiffFingerprints: new Map(cachedArtifacts.fileDiffFingerprints),
+ threads: cachedArtifacts.threads,
+ });
+ return;
+ }
+
+ if (pendingDerivedCacheKeyRef.current === derivedCacheKey) {
+ return;
+ }
+ pendingDerivedCacheKeyRef.current = derivedCacheKey;
+
+ void computeReviewDerived({
+ cacheKey: derivedCacheKey,
+ diffText,
+ comments,
+ })
+ .then((result) => {
+ if (cancelled) return;
+ if (pendingDerivedCacheKeyRef.current !== derivedCacheKey) return;
+ writeReviewDerivedCacheValue(derivedCacheKey, {
+ fileDiffs: result.fileDiffs,
+ fileDiffFingerprints: Array.from(result.fileDiffFingerprints.entries()),
+ threads: result.threads,
+ } satisfies CachedReviewDerivedArtifacts);
+ applyWorkerDerived(derivedCacheKey, {
+ fileDiffs: result.fileDiffs,
+ fileDiffFingerprints: result.fileDiffFingerprints,
+ threads: result.threads,
+ });
+ })
+ .catch(() => {
+ if (cancelled) return;
+ if (pendingDerivedCacheKeyRef.current !== derivedCacheKey) return;
+ // Keep UI responsive if the compute worker fails unexpectedly.
+ const parsedPatches = diffText ? parsePatchFiles(diffText) : [];
+ const fallbackDiffs = parsedPatches.flatMap((patch) => patch.files);
+ const fallbackFingerprints = new Map();
+ fallbackDiffs.forEach((fileDiff, index) => {
+ const path = getFilePath(fileDiff, index);
+ if (!fallbackFingerprints.has(path)) {
+ fallbackFingerprints.set(path, buildFileDiffFingerprint(fileDiff));
+ }
+ });
+ const roots = comments.filter((comment) => !comment.parent?.id);
+ const repliesByParent = new Map();
+ for (const comment of comments) {
+ const parentId = comment.parent?.id;
+ if (!parentId) continue;
+ const replies = repliesByParent.get(parentId) ?? [];
+ replies.push(comment);
+ repliesByParent.set(parentId, replies);
+ }
+ const fallbackThreads: CommentThread[] = roots
+ .map((root) => ({
+ id: root.id,
+ root,
+ replies: [...(repliesByParent.get(root.id) ?? [])].sort(
+ (a, b) => new Date(a.createdAt ?? 0).getTime() - new Date(b.createdAt ?? 0).getTime(),
+ ),
+ }))
+ .sort((a, b) => new Date(a.root.createdAt ?? 0).getTime() - new Date(b.root.createdAt ?? 0).getTime());
+ writeReviewDerivedCacheValue(derivedCacheKey, {
+ fileDiffs: fallbackDiffs,
+ fileDiffFingerprints: Array.from(fallbackFingerprints.entries()),
+ threads: fallbackThreads,
+ } satisfies CachedReviewDerivedArtifacts);
+ applyWorkerDerived(derivedCacheKey, {
+ fileDiffs: fallbackDiffs,
+ fileDiffFingerprints: fallbackFingerprints,
+ threads: fallbackThreads,
+ });
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [applyWorkerDerived, comments, computeReviewDerived, derivedCacheKey, diffText, workerDerived.cacheKey]);
+
+ const rawFileDiffs = workerDerived.fileDiffs;
const fileDiffs = useMemo(() => {
if (!rawFileDiffs.length) return rawFileDiffs;
@@ -139,16 +283,7 @@ export function useReviewPageDerived({
});
return map;
}, [fileDiffs]);
- const fileDiffFingerprints = useMemo(() => {
- const map = new Map();
- fileDiffs.forEach((fileDiff, index) => {
- const path = getFilePath(fileDiff, index);
- if (!map.has(path)) {
- map.set(path, buildFileDiffFingerprint(fileDiff));
- }
- });
- return map;
- }, [fileDiffs]);
+ const fileDiffFingerprints = workerDerived.fileDiffFingerprints;
const selectableDiffPathSet = useMemo(() => new Set(diffByPath.keys()), [diffByPath]);
const visibleFilePaths = useMemo(() => {
@@ -212,8 +347,7 @@ export function useReviewPageDerived({
}, [diffByPath, selectedFilePath]);
const isSummarySelected = activeFile === PR_SUMMARY_PATH;
- const comments = prData?.comments ?? [];
- const threads = useMemo(() => buildCommentThreads(comments), [comments]);
+ const threads = workerDerived.threads;
const unresolvedThreads = threads.filter((thread) => !thread.root.resolution && !thread.root.deleted);
const threadsByPath = useMemo(() => {
diff --git a/src/components/pull-request-review/use-review-page-effects.ts b/src/components/pull-request-review/use-review-page-effects.ts
index 2b62a79..07c2f00 100644
--- a/src/components/pull-request-review/use-review-page-effects.ts
+++ b/src/components/pull-request-review/use-review-page-effects.ts
@@ -1,4 +1,5 @@
-import { type FileDiffMetadata, preloadHighlighter } from "@pierre/diffs";
+import type { FileDiffMetadata } from "@pierre/diffs";
+import { useWorkerPool } from "@pierre/diffs/react";
import { type Dispatch, type MutableRefObject, type SetStateAction, useEffect, useMemo, useRef, useState } from "react";
import { readReviewDirectoryState, writeReviewDirectoryState } from "@/lib/data/query-collections";
import { fileAnchorId } from "@/lib/file-anchors";
@@ -84,16 +85,8 @@ export function useDirectoryStateStorage({
}, [dirState, dirStateHydrated, directoryStateStorageKey]);
}
-export function useDiffHighlighterState({
- fileDiffs,
- theme,
- preloadLanguages,
-}: {
- fileDiffs: FileDiffMetadata[];
- theme: Parameters[0]["themes"][number];
- preloadLanguages: string[];
-}) {
- const [diffHighlighterReady, setDiffHighlighterReady] = useState(false);
+export function useDiffHighlighterState({ fileDiffs, theme, preloadLanguages }: { fileDiffs: FileDiffMetadata[]; theme: string; preloadLanguages: string[] }) {
+ const workerPool = useWorkerPool();
const [diffPlainTextFallback, setDiffPlainTextFallback] = useState(false);
const preloadLanguagesKey = useMemo(() => [...new Set(preloadLanguages)].sort().join(","), [preloadLanguages]);
const languagesForPreload = useMemo(() => {
@@ -103,32 +96,33 @@ export function useDiffHighlighterState({
useEffect(() => {
if (fileDiffs.length === 0) {
- setDiffHighlighterReady(true);
setDiffPlainTextFallback(false);
return;
}
- let cancelled = false;
- setDiffHighlighterReady(false);
+
setDiffPlainTextFallback(false);
- void preloadHighlighter({
- themes: [theme],
- langs: languagesForPreload as Parameters[0]["langs"],
- })
- .then(() => {
- if (cancelled) return;
- setDiffHighlighterReady(true);
+ if (!workerPool || !workerPool.isWorkingPool()) {
+ setDiffPlainTextFallback(true);
+ return;
+ }
+
+ let cancelled = false;
+ void workerPool
+ .setRenderOptions({
+ theme,
})
+ .then(() => workerPool.initialize(languagesForPreload as Parameters[0]))
.catch(() => {
if (cancelled) return;
setDiffPlainTextFallback(true);
- setDiffHighlighterReady(true);
});
+
return () => {
cancelled = true;
};
- }, [fileDiffs.length, languagesForPreload, theme]);
+ }, [fileDiffs.length, languagesForPreload, theme, workerPool]);
- return { diffHighlighterReady, diffPlainTextFallback };
+ return { diffHighlighterReady: true, diffPlainTextFallback };
}
export function useReviewTreeModelSync({
diff --git a/src/components/pull-request-review/use-review-query.ts b/src/components/pull-request-review/use-review-query.ts
index 8ed699a..0c93163 100644
--- a/src/components/pull-request-review/use-review-query.ts
+++ b/src/components/pull-request-review/use-review-query.ts
@@ -1,5 +1,5 @@
import { useLiveQuery } from "@tanstack/react-db";
-import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
+import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import {
getGitHostFetchActivitySnapshot,
getHostDataCollectionsVersionSnapshot,
@@ -11,7 +11,8 @@ import {
} from "@/lib/git-host/query-collections";
import { parseSchema, pullRequestBundleSchema } from "@/lib/git-host/schemas";
import { getCapabilitiesForHost } from "@/lib/git-host/service";
-import { type GitHost, HostApiError } from "@/lib/git-host/types";
+import { type GitHost, HostApiError, type PullRequestCriticalBundle, type PullRequestDeferredBundle } from "@/lib/git-host/types";
+import { markReviewPerf, measureReviewPerf, setCriticalLoadDuration, setDeferredLoadDuration } from "@/lib/review-performance/metrics";
interface UseReviewQueryProps {
host: GitHost;
@@ -23,6 +24,9 @@ interface UseReviewQueryProps {
onRequireAuth?: (reason: "rate_limit") => void;
}
+const CRITICAL_STALE_MS = 30_000;
+const DEFERRED_STALE_MS = 2 * 60_000;
+
export function isRateLimitedError(error: unknown) {
if (!error) return false;
if (error instanceof HostApiError) {
@@ -37,14 +41,16 @@ export function isRateLimitedError(error: unknown) {
function normalizeBundleRecord(value: unknown): PullRequestBundleRecord | undefined {
const parsed = parseSchema(pullRequestBundleSchema, value);
if (!parsed) return undefined;
+ const raw = value as PullRequestBundleRecord;
return {
- ...(value as PullRequestBundleRecord),
+ ...raw,
diffstat: Array.isArray(parsed.diffstat) ? (parsed.diffstat as PullRequestBundleRecord["diffstat"]) : [],
commits: Array.isArray(parsed.commits) ? (parsed.commits as PullRequestBundleRecord["commits"]) : [],
comments: Array.isArray(parsed.comments) ? (parsed.comments as PullRequestBundleRecord["comments"]) : [],
history: Array.isArray(parsed.history) ? (parsed.history as PullRequestBundleRecord["history"]) : [],
reviewers: Array.isArray(parsed.reviewers) ? (parsed.reviewers as PullRequestBundleRecord["reviewers"]) : [],
buildStatuses: Array.isArray(parsed.buildStatuses) ? (parsed.buildStatuses as PullRequestBundleRecord["buildStatuses"]) : [],
+ deferredStatus: raw.deferredStatus === "ready" || raw.deferredStatus === "loading" || raw.deferredStatus === "error" ? raw.deferredStatus : "idle",
};
}
@@ -64,12 +70,17 @@ export function useReviewQuery({ host, workspace, repo, pullRequestId, canRead,
// Depend on host-data collection version so we rescope when persistence falls back.
void hostDataCollectionsVersion;
if (!canLoadPullRequest) return null;
- return getPullRequestBundleCollection({
- host,
- workspace,
- repo,
- pullRequestId,
- });
+ return getPullRequestBundleCollection(
+ {
+ host,
+ workspace,
+ repo,
+ pullRequestId,
+ },
+ {
+ staged: true,
+ },
+ );
}, [canLoadPullRequest, host, hostDataCollectionsVersion, pullRequestId, repo, workspace]);
const bundleQuery = useLiveQuery(
@@ -84,37 +95,113 @@ export function useReviewQuery({ host, workspace, repo, pullRequestId, canRead,
() => (bundleQuery.data ?? []).map(normalizeBundleRecord).find((record) => record?.id === bundleId),
[bundleId, bundleQuery.data],
);
+
+ const critical = useMemo(() => {
+ if (!queryData) return undefined;
+ return {
+ prRef: queryData.prRef,
+ pr: queryData.pr,
+ diff: queryData.diff,
+ diffstat: queryData.diffstat,
+ commits: queryData.commits,
+ };
+ }, [queryData]);
+
+ const deferred = useMemo(() => {
+ if (!queryData) return undefined;
+ return {
+ prRef: queryData.prRef,
+ comments: queryData.comments,
+ history: queryData.history,
+ reviewers: queryData.reviewers,
+ buildStatuses: queryData.buildStatuses,
+ };
+ }, [queryData]);
+
+ const stagedBundle = useMemo(() => {
+ if (!critical) return undefined;
+ return {
+ ...critical,
+ comments: deferred?.comments ?? [],
+ history: deferred?.history,
+ reviewers: deferred?.reviewers,
+ buildStatuses: deferred?.buildStatuses,
+ };
+ }, [critical, deferred]);
+
const collectionError = bundleStore?.utils.lastError;
const queryError = collectionError;
- const queryIsLoading = canLoadPullRequest ? bundleQuery.isLoading && !queryData : false;
- const queryIsFetching = canLoadPullRequest ? fetchActivity.activeFetches.some((fetch) => fetch.scopeId === fetchScopeId) : false;
+ const queryIsFetching = canLoadPullRequest ? fetchActivity.activeFetches.some((fetch) => fetch.scopeId.startsWith(fetchScopeId)) : false;
+ const isCriticalLoading = canLoadPullRequest ? !critical && (bundleQuery.isLoading || queryIsFetching) : false;
+ const isDeferredLoading = canLoadPullRequest ? Boolean(critical) && (!queryData?.deferredFetchedAt || queryData?.deferredStatus === "loading") : false;
const refetchQuery = useCallback(() => bundleStore?.utils.refetch({ throwOnError: false }) ?? Promise.resolve(), [bundleStore]);
const query = useMemo(
() => ({
- data: queryData,
+ data: stagedBundle,
error: queryError,
- isLoading: queryIsLoading,
+ isLoading: isCriticalLoading,
isFetching: queryIsFetching,
refetch: refetchQuery,
}),
- [queryData, queryError, queryIsLoading, queryIsFetching, refetchQuery],
+ [isCriticalLoading, queryError, queryIsFetching, refetchQuery, stagedBundle],
);
- const hasPendingBuildStatuses = queryData?.buildStatuses?.some((status) => status.state === "pending") ?? false;
+ const criticalMarkRef = useRef("");
+ const deferredMarkRef = useRef("");
+ useEffect(() => {
+ if (critical || criticalMarkRef.current) return;
+ criticalMarkRef.current = markReviewPerf("critical_data_start");
+ }, [critical]);
+ useEffect(() => {
+ if (!critical || !criticalMarkRef.current) return;
+ const endMark = markReviewPerf("critical_data_ready");
+ const duration = measureReviewPerf("critical_data", criticalMarkRef.current, endMark);
+ if (typeof duration === "number") {
+ setCriticalLoadDuration(duration);
+ }
+ criticalMarkRef.current = "";
+ }, [critical]);
+
+ useEffect(() => {
+ if (queryData?.deferredFetchedAt || deferredMarkRef.current) return;
+ deferredMarkRef.current = markReviewPerf("deferred_data_start");
+ }, [queryData?.deferredFetchedAt]);
+ useEffect(() => {
+ if (!queryData?.deferredFetchedAt || !deferredMarkRef.current) return;
+ const endMark = markReviewPerf("deferred_data_ready");
+ const duration = measureReviewPerf("deferred_data", deferredMarkRef.current, endMark);
+ if (typeof duration === "number") {
+ setDeferredLoadDuration(duration);
+ }
+ deferredMarkRef.current = "";
+ }, [queryData?.deferredFetchedAt]);
+
+ const hasPendingBuildStatuses = stagedBundle?.buildStatuses?.some((status) => status.state === "pending") ?? false;
useEffect(() => {
if (!bundleStore) return;
- // Force a network refresh on mount to replace stale in-memory rows from previous runtime shape changes.
- void bundleStore.utils.refetch({ throwOnError: false });
- }, [bundleStore]);
+ if (queryIsFetching) return;
+
+ const now = Date.now();
+ const criticalFetchedAt = queryData?.criticalFetchedAt ?? queryData?.fetchedAt ?? 0;
+ const deferredFetchedAt = queryData?.deferredFetchedAt ?? 0;
+ const criticalStale = !criticalFetchedAt || now - criticalFetchedAt > CRITICAL_STALE_MS;
+ const deferredStale = !deferredFetchedAt || now - deferredFetchedAt > DEFERRED_STALE_MS;
+
+ if (!queryData || criticalStale || deferredStale) {
+ void bundleStore.utils.refetch({ throwOnError: false });
+ }
+ }, [bundleStore, queryData, queryIsFetching]);
useEffect(() => {
if (!hasPendingBuildStatuses) return;
- const intervalId = window.setInterval(() => {
+ const poll = () => {
if (queryIsFetching) return;
+ if (typeof document !== "undefined" && document.hidden) return;
void refetchQuery();
- }, 10_000);
+ };
+ const intervalId = window.setInterval(poll, 10_000);
return () => {
window.clearInterval(intervalId);
};
@@ -127,6 +214,11 @@ export function useReviewQuery({ host, workspace, repo, pullRequestId, canRead,
return {
hostCapabilities,
+ critical,
+ deferred,
+ isCriticalLoading,
+ isDeferredLoading,
+ isRefreshing: queryIsFetching,
query,
};
}
diff --git a/src/components/settings-menu.tsx b/src/components/settings-menu.tsx
index a279fdb..c74f097 100644
--- a/src/components/settings-menu.tsx
+++ b/src/components/settings-menu.tsx
@@ -29,6 +29,7 @@ import {
MONO_FONT_FAMILY_OPTIONS,
SANS_FONT_FAMILY_OPTIONS,
} from "@/lib/font-options";
+import { getReviewPerfSnapshot, type ReviewPerfSnapshot } from "@/lib/review-performance/metrics";
import { type ShortcutConfig, useShortcuts } from "@/lib/shortcuts-context";
import { cn } from "@/lib/utils";
@@ -506,11 +507,13 @@ function formatTimestamp(timestamp: number | null) {
function StorageTab() {
const [state, setState] = useState<{
snapshot: DataCollectionsDebugSnapshot | null;
+ perfSnapshot: ReviewPerfSnapshot | null;
loading: boolean;
busyAction: "refresh" | "clear-cache" | "clear-expired" | "export" | null;
statusMessage: string | null;
}>({
snapshot: null,
+ perfSnapshot: null,
loading: true,
busyAction: null,
statusMessage: null,
@@ -520,9 +523,11 @@ function StorageTab() {
setState((prev) => ({ ...prev, busyAction: "refresh" }));
try {
const snapshot = await getDataCollectionsDebugSnapshot();
+ const perfSnapshot = getReviewPerfSnapshot();
setState((prev) => ({
...prev,
snapshot,
+ perfSnapshot,
}));
} finally {
setState((prev) => ({ ...prev, busyAction: null, loading: false }));
@@ -569,10 +574,12 @@ function StorageTab() {
setState((prev) => ({ ...prev, busyAction: "export", statusMessage: null }));
try {
const snapshot = await getDataCollectionsDebugSnapshot();
+ const perfSnapshot = getReviewPerfSnapshot();
const payload = JSON.stringify(
{
generatedAt: new Date().toISOString(),
storage: snapshot,
+ reviewPerformance: perfSnapshot,
},
null,
2,
@@ -609,6 +616,7 @@ function StorageTab() {
const tierOrder: StorageTier[] = ["cache", "state", "permanent"];
const snapshot = state.snapshot;
+ const perfSnapshot = state.perfSnapshot;
if (state.loading && !snapshot) {
return Loading storage diagnostics...
;
@@ -628,7 +636,7 @@ function StorageTab() {
{snapshot ? (
Storage Health
-
+
Collections backend: {snapshot.backendMode}
Host cache backend: {snapshot.hostBackendMode}
@@ -642,6 +650,12 @@ function StorageTab() {
Quota estimate: {formatBytes(snapshot.estimatedUsageBytes)} / {formatBytes(snapshot.estimatedQuotaBytes)}
+
+
Critical load ms: {perfSnapshot?.lastCriticalLoadMs ?? "n/a"}
+
Deferred load ms: {perfSnapshot?.lastDeferredLoadMs ?? "n/a"}
+
Long tasks: {perfSnapshot?.longTaskCount ?? 0}
+
Worker queue depth: {perfSnapshot?.workerQueueDepth ?? 0}
+
) : null}
diff --git a/src/lib/data/query-collections.ts b/src/lib/data/query-collections.ts
index e526171..bd0925f 100644
--- a/src/lib/data/query-collections.ts
+++ b/src/lib/data/query-collections.ts
@@ -13,6 +13,9 @@ export type StorageTier = "cache" | "state" | "permanent";
const DATA_DATABASE_NAME = "pullrequestdotreview_data_v1";
const STATE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
+const REVIEW_DERIVED_CACHE_TTL_MS = 12 * 60 * 60 * 1000;
+const REVIEW_DERIVED_CACHE_MAX_BYTES = 512 * 1024;
+const REVIEW_DERIVED_CACHE_MAX_RECORDS = 120;
const LEGACY_RESET_METADATA_ID = "legacy_reset_v1";
const APP_PREFERENCES_COLLECTION_NAME = "app_preferences";
@@ -887,6 +890,59 @@ export function writeHostPreferencesRecord(data: { activeHost: GitHost; reposByH
);
}
+function reviewDerivedCacheRecordId(cacheKey: string) {
+ return `review-derived:${cacheKey}`;
+}
+
+export function readReviewDerivedCacheValue(cacheKey: string): T | null {
+ const id = reviewDerivedCacheRecordId(cacheKey);
+ const record = getAppMetadataCollection().get(id);
+ if (!record) return null;
+ if (isExpiredRecord(record, Date.now())) {
+ void deleteRecord(getAppMetadataCollection(), id, id);
+ return null;
+ }
+ try {
+ return JSON.parse(record.value) as T;
+ } catch {
+ return null;
+ }
+}
+
+export function writeReviewDerivedCacheValue(cacheKey: string, payload: unknown) {
+ const id = reviewDerivedCacheRecordId(cacheKey);
+ const serializedPayload = JSON.stringify(payload);
+ if (new TextEncoder().encode(serializedPayload).length > REVIEW_DERIVED_CACHE_MAX_BYTES) {
+ return;
+ }
+ const now = Date.now();
+ const metadataCollection = getAppMetadataCollection();
+ const derivedRecords = Array.from(metadataCollection.values())
+ .filter((record) => record.id.startsWith("review-derived:"))
+ .sort((left, right) => left.updatedAt - right.updatedAt);
+
+ void (async () => {
+ const overflow = derivedRecords.length - REVIEW_DERIVED_CACHE_MAX_RECORDS;
+ if (overflow >= 0) {
+ for (let index = 0; index <= overflow; index += 1) {
+ const evicted = derivedRecords[index];
+ if (!evicted || evicted.id === id) continue;
+ await deleteRecord(metadataCollection, evicted.id, evicted.id);
+ }
+ }
+ await upsertRecord(
+ metadataCollection,
+ {
+ id,
+ value: serializedPayload,
+ updatedAt: now,
+ expiresAt: now + REVIEW_DERIVED_CACHE_TTL_MS,
+ },
+ id,
+ );
+ })();
+}
+
export function readBitbucketAuthCredential() {
const record = readPermanentRecord>("bitbucket");
if (!record || record.host !== "bitbucket") return null;
diff --git a/src/lib/git-host/providers/bitbucket.ts b/src/lib/git-host/providers/bitbucket.ts
index e5d4434..4d9123d 100644
--- a/src/lib/git-host/providers/bitbucket.ts
+++ b/src/lib/git-host/providers/bitbucket.ts
@@ -12,6 +12,8 @@ import {
type PullRequestBuildStatus,
type PullRequestBundle,
type PullRequestCommitRangeDiff,
+ type PullRequestCriticalBundle,
+ type PullRequestDeferredBundle,
type PullRequestDetails,
type PullRequestFileHistory,
type PullRequestFileHistoryEntry,
@@ -221,6 +223,24 @@ async function request(url: string, init: RequestInit = {}) {
return response;
}
+async function mapWithConcurrency(values: TInput[], concurrency: number, mapper: (value: TInput, index: number) => Promise) {
+ if (values.length === 0) return [] as TOutput[];
+ const safeConcurrency = Math.max(1, Math.min(concurrency, values.length));
+ const results = new Array(values.length);
+ let index = 0;
+
+ const workers = Array.from({ length: safeConcurrency }, async () => {
+ while (index < values.length) {
+ const current = index;
+ index += 1;
+ results[current] = await mapper(values[current], current);
+ }
+ });
+
+ await Promise.all(workers);
+ return results;
+}
+
async function fetchAllDiffStat(startUrl: string): Promise {
const values: DiffStatEntry[] = [];
let nextUrl: string | undefined = startUrl;
@@ -560,6 +580,69 @@ export const bitbucketNormalization = {
mapActivityToHistory,
};
+async function fetchBitbucketPullRequestCritical(prRef: { workspace: string; repo: string; pullRequestId: string }): Promise {
+ const baseApi = `https://api.bitbucket.org/2.0/repositories/${prRef.workspace}/${prRef.repo}/pullrequests/${prRef.pullRequestId}`;
+ const [prRes, diffRes, diffstat, commits] = await Promise.all([
+ request(baseApi, { headers: { Accept: "application/json" } }),
+ request(`${baseApi}/diff`, { headers: { Accept: "text/plain" } }),
+ fetchAllDiffStat(`${baseApi}/diffstat?pagelen=100`),
+ fetchAllCommits(`${baseApi}/commits?pagelen=50`),
+ ]);
+
+ const pr = mapPullRequest((await prRes.json()) as BitbucketPullRequestRaw, null);
+ return {
+ prRef: {
+ host: "bitbucket",
+ workspace: prRef.workspace,
+ repo: prRef.repo,
+ pullRequestId: prRef.pullRequestId,
+ },
+ pr,
+ diff: await diffRes.text(),
+ diffstat,
+ commits,
+ };
+}
+
+async function fetchBitbucketPullRequestDeferred(prRef: { workspace: string; repo: string; pullRequestId: string }): Promise {
+ const baseApi = `https://api.bitbucket.org/2.0/repositories/${prRef.workspace}/${prRef.repo}/pullrequests/${prRef.pullRequestId}`;
+
+ const [prRes, comments, activity, currentUserRes, firstCommitRes] = await Promise.all([
+ request(baseApi, { headers: { Accept: "application/json" } }),
+ fetchAllComments(`${baseApi}/comments?pagelen=100&sort=created_on`),
+ fetchAllActivity(`${baseApi}/activity?pagelen=50`).catch(() => []),
+ request("https://api.bitbucket.org/2.0/user", { headers: { Accept: "application/json" } }).catch(() => null),
+ request(`${baseApi}/commits?pagelen=1`, { headers: { Accept: "application/json" } }).catch(() => null),
+ ]);
+
+ const currentUser = currentUserRes ? ((await currentUserRes.json()) as BitbucketUser) : null;
+ const pr = mapPullRequest((await prRes.json()) as BitbucketPullRequestRaw, currentUser);
+ const firstCommitPage = firstCommitRes ? ((await firstCommitRes.json()) as BitbucketCommitPage) : null;
+ const latestCommitHash = firstCommitPage?.values?.[0]?.hash?.trim();
+ const latestBuildStatuses = latestCommitHash
+ ? await fetchAllBuildStatuses(
+ `https://api.bitbucket.org/2.0/repositories/${prRef.workspace}/${prRef.repo}/commit/${latestCommitHash}/statuses?pagelen=100`,
+ ).catch(() => [])
+ : [];
+
+ return {
+ prRef: {
+ host: "bitbucket",
+ workspace: prRef.workspace,
+ repo: prRef.repo,
+ pullRequestId: prRef.pullRequestId,
+ },
+ comments,
+ history: mapHistory(pr, comments, activity),
+ reviewers: mapReviewers(pr),
+ buildStatuses: mapBuildStatuses(latestBuildStatuses),
+ prPatch: {
+ currentUserReviewStatus: pr.currentUserReviewStatus,
+ currentUser: pr.currentUser,
+ },
+ };
+}
+
export const bitbucketClient: GitHostClient = {
host: "bitbucket",
capabilities: {
@@ -622,58 +705,56 @@ export const bitbucketClient: GitHostClient = {
},
async listPullRequestsForRepos(data) {
if (!data.repos.length) return [];
- const results: Array<{
- repo: RepoRef;
- pullRequests: PullRequestSummary[];
- }> = [];
-
- for (const repo of data.repos) {
+ return mapWithConcurrency(data.repos, 4, async (repo) => {
const url = `https://api.bitbucket.org/2.0/repositories/${repo.workspace}/${repo.repo}/pullrequests?pagelen=20`;
const res = await request(url, {
headers: { Accept: "application/json" },
});
const page = (await res.json()) as BitbucketPullRequestPage;
- results.push({
+ return {
repo,
pullRequests: (page.values ?? []).map(mapPullRequestSummary),
- });
- }
-
- return results;
+ };
+ });
+ },
+ async fetchPullRequestCriticalByRef(data): Promise {
+ return fetchBitbucketPullRequestCritical({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ });
+ },
+ async fetchPullRequestDeferredByRef(data): Promise {
+ return fetchBitbucketPullRequestDeferred({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ });
},
async fetchPullRequestBundleByRef(data): Promise {
- const prRef = data.prRef;
- const baseApi = `https://api.bitbucket.org/2.0/repositories/${prRef.workspace}/${prRef.repo}/pullrequests/${prRef.pullRequestId}`;
-
- const [prRes, diffRes, diffstat, commits, comments, activity, currentUserRes] = await Promise.all([
- request(baseApi, { headers: { Accept: "application/json" } }),
- request(`${baseApi}/diff`, { headers: { Accept: "text/plain" } }),
- fetchAllDiffStat(`${baseApi}/diffstat?pagelen=100`),
- fetchAllCommits(`${baseApi}/commits?pagelen=50`),
- fetchAllComments(`${baseApi}/comments?pagelen=100&sort=created_on`),
- fetchAllActivity(`${baseApi}/activity?pagelen=50`).catch(() => []),
- request("https://api.bitbucket.org/2.0/user", { headers: { Accept: "application/json" } }).catch(() => null),
+ const [critical, deferred] = await Promise.all([
+ fetchBitbucketPullRequestCritical({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ }),
+ fetchBitbucketPullRequestDeferred({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ }),
]);
-
- const currentUser = currentUserRes ? ((await currentUserRes.json()) as BitbucketUser) : null;
- const pr = mapPullRequest((await prRes.json()) as BitbucketPullRequestRaw, currentUser);
- const latestCommitHash = commits[0]?.hash;
- const latestBuildStatuses = latestCommitHash
- ? await fetchAllBuildStatuses(
- `https://api.bitbucket.org/2.0/repositories/${prRef.workspace}/${prRef.repo}/commit/${latestCommitHash}/statuses?pagelen=100`,
- ).catch(() => [])
- : [];
-
+ const mergedPullRequest: PullRequestDetails = {
+ ...critical.pr,
+ ...(deferred.prPatch ?? {}),
+ };
return {
- prRef,
- pr,
- diff: await diffRes.text(),
- diffstat,
- commits,
- comments,
- history: mapHistory(pr, comments, activity),
- reviewers: mapReviewers(pr),
- buildStatuses: mapBuildStatuses(latestBuildStatuses),
+ ...critical,
+ pr: mergedPullRequest,
+ comments: deferred.comments,
+ history: deferred.history,
+ reviewers: deferred.reviewers,
+ buildStatuses: deferred.buildStatuses,
};
},
async approvePullRequest(data) {
@@ -809,20 +890,18 @@ export const bitbucketClient: GitHostClient = {
return { path: normalizedPath, entries: [], fetchedAt: Date.now() };
}
- const entries: PullRequestFileHistoryEntry[] = [];
- for (const commit of commits) {
- if (entries.length >= limit) break;
+ const commitCandidates = commits.filter((commit) => Boolean(commit.hash?.trim()));
+ const resolved = await mapWithConcurrency(commitCandidates, 4, async (commit) => {
const commitHash = commit.hash?.trim();
- if (!commitHash) continue;
+ if (!commitHash) return null;
const diffRes = await request(`https://api.bitbucket.org/2.0/repositories/${prRef.workspace}/${prRef.repo}/diff/${commitHash}`, {
headers: { Accept: "text/plain" },
});
const diffText = await diffRes.text();
const match = extractSingleFilePatchFromUnifiedDiff(diffText, normalizedPath);
- if (!match) continue;
-
- entries.push({
+ if (!match) return null;
+ return {
versionId: `${normalizedPath}:${commitHash}`,
commitHash,
commitDate: commit.date,
@@ -831,8 +910,9 @@ export const bitbucketClient: GitHostClient = {
filePathAtCommit: match.filePathAtCommit,
status: match.status,
patch: match.patch,
- });
- }
+ };
+ });
+ const entries = resolved.filter((entry): entry is PullRequestFileHistoryEntry => entry !== null).slice(0, limit);
return {
path: normalizedPath,
diff --git a/src/lib/git-host/providers/github.ts b/src/lib/git-host/providers/github.ts
index cd58dbb..4bfea89 100644
--- a/src/lib/git-host/providers/github.ts
+++ b/src/lib/git-host/providers/github.ts
@@ -13,13 +13,14 @@ import {
type PullRequestBuildStatus,
type PullRequestBundle,
type PullRequestCommitRangeDiff,
+ type PullRequestCriticalBundle,
+ type PullRequestDeferredBundle,
type PullRequestDetails,
type PullRequestFileHistory,
type PullRequestFileHistoryEntry,
type PullRequestHistoryEvent,
type PullRequestReviewer,
type PullRequestSummary,
- type RepoRef,
} from "@/lib/git-host/types";
const API_BASE = "https://api.github.com";
@@ -263,6 +264,24 @@ async function listPaginated(path: string) {
});
}
+async function mapWithConcurrency(values: TInput[], concurrency: number, mapper: (value: TInput, index: number) => Promise) {
+ if (values.length === 0) return [] as TOutput[];
+ const safeConcurrency = Math.max(1, Math.min(concurrency, values.length));
+ const results = new Array(values.length);
+ let index = 0;
+
+ const workers = Array.from({ length: safeConcurrency }, async () => {
+ while (index < values.length) {
+ const current = index;
+ index += 1;
+ results[current] = await mapper(values[current], current);
+ }
+ });
+
+ await Promise.all(workers);
+ return results;
+}
+
function mapFileStatus(status: string): DiffStatEntry["status"] {
if (status === "added") return "added";
if (status === "removed") return "removed";
@@ -270,6 +289,27 @@ function mapFileStatus(status: string): DiffStatEntry["status"] {
return "modified";
}
+function resolveCurrentUserReviewStatus(reviews: GithubReview[], currentLogin?: string): PullRequestDetails["currentUserReviewStatus"] {
+ if (!currentLogin) return "none";
+ let currentUserReviewStatus: PullRequestDetails["currentUserReviewStatus"] = "none";
+ for (let i = reviews.length - 1; i >= 0; i -= 1) {
+ const review = reviews[i];
+ if (review.user?.login !== currentLogin) continue;
+ const state = (review.state ?? "").toUpperCase();
+ if (state === "APPROVED") {
+ currentUserReviewStatus = "approved";
+ }
+ if (state === "CHANGES_REQUESTED") {
+ currentUserReviewStatus = "changesRequested";
+ }
+ if (state === "APPROVED" || state === "CHANGES_REQUESTED" || state === "DISMISSED") {
+ if (state === "DISMISSED") currentUserReviewStatus = "none";
+ break;
+ }
+ }
+ return currentUserReviewStatus;
+}
+
function matchGithubCommitFileForPath(file: GithubCommitFile, targetPath: string) {
const normalizedTarget = targetPath.trim();
if (!normalizedTarget) return false;
@@ -698,6 +738,98 @@ export const githubNormalization = {
mapReviewStateToStatus,
};
+async function fetchGithubPullRequestCritical(prRef: { workspace: string; repo: string; pullRequestId: string }): Promise {
+ const basePath = `/repos/${prRef.workspace}/${prRef.repo}/pulls/${prRef.pullRequestId}`;
+ const [prRes, diffRes, files, commits] = await Promise.all([
+ request(basePath),
+ request(basePath, {
+ headers: { Accept: "application/vnd.github.v3.diff" },
+ }),
+ listPaginated(`${basePath}/files`),
+ listPaginated(`${basePath}/commits`),
+ ]);
+ const pr = (await prRes.json()) as GithubPull;
+ const diffstat: DiffStatEntry[] = files.map((file) => ({
+ status: mapFileStatus(file.status),
+ new: { path: file.filename },
+ old: { path: file.previous_filename ?? file.filename },
+ linesAdded: file.additions,
+ linesRemoved: file.deletions,
+ }));
+ return {
+ prRef: {
+ host: "github",
+ workspace: prRef.workspace,
+ repo: prRef.repo,
+ pullRequestId: prRef.pullRequestId,
+ },
+ pr: mapPullRequestDetails(pr, "none"),
+ diff: await diffRes.text(),
+ diffstat,
+ commits: commits.map(mapCommit),
+ };
+}
+
+async function fetchGithubPullRequestDeferred(prRef: { workspace: string; repo: string; pullRequestId: string }): Promise {
+ const basePath = `/repos/${prRef.workspace}/${prRef.repo}/pulls/${prRef.pullRequestId}`;
+ const isAuthenticated = Boolean(authHeader());
+ const [prRes, issueComments, reviewComments, reviews, issueEvents] = await Promise.all([
+ request(basePath),
+ listPaginated(`/repos/${prRef.workspace}/${prRef.repo}/issues/${prRef.pullRequestId}/comments`),
+ listPaginated(`${basePath}/comments`),
+ listPaginated(`${basePath}/reviews`),
+ listPaginated(`/repos/${prRef.workspace}/${prRef.repo}/issues/${prRef.pullRequestId}/events`).catch(() => []),
+ ]);
+
+ let currentLogin: string | undefined;
+ let currentAvatarUrl: string | undefined;
+ if (isAuthenticated) {
+ const currentUserRes = await request("/user");
+ const currentUser = (await currentUserRes.json()) as GithubUser;
+ currentLogin = currentUser.login;
+ currentAvatarUrl = currentUser.avatar_url;
+ }
+
+ const pr = (await prRes.json()) as GithubPull;
+ const headSha = pr.head?.sha;
+ const [checks, combinedStatus] = await Promise.all([
+ headSha
+ ? request(`/repos/${prRef.workspace}/${prRef.repo}/commits/${headSha}/check-runs`)
+ .then((res) => res.json() as Promise)
+ .catch(() => null)
+ : Promise.resolve(null),
+ headSha
+ ? request(`/repos/${prRef.workspace}/${prRef.repo}/commits/${headSha}/status`)
+ .then((res) => res.json() as Promise)
+ .catch(() => null)
+ : Promise.resolve(null),
+ ]);
+
+ const currentUserReviewStatus = resolveCurrentUserReviewStatus(reviews, currentLogin);
+
+ return {
+ prRef: {
+ host: "github",
+ workspace: prRef.workspace,
+ repo: prRef.repo,
+ pullRequestId: prRef.pullRequestId,
+ },
+ comments: mergeIssueAndReviewComments(issueComments, reviewComments),
+ history: mapHistory(pr, issueComments, reviews, issueEvents),
+ reviewers: mapReviewers(pr, reviews),
+ buildStatuses: mapBuildStatuses(checks, combinedStatus),
+ prPatch: {
+ currentUserReviewStatus,
+ currentUser: currentLogin
+ ? {
+ displayName: currentLogin,
+ avatarUrl: currentAvatarUrl,
+ }
+ : undefined,
+ },
+ };
+}
+
export const githubClient: GitHostClient = {
host: "github",
capabilities: {
@@ -761,101 +893,52 @@ export const githubClient: GitHostClient = {
},
async listPullRequestsForRepos(data) {
if (!data.repos.length) return [];
- const results: Array<{
- repo: RepoRef;
- pullRequests: PullRequestSummary[];
- }> = [];
-
- for (const repo of data.repos) {
+ return mapWithConcurrency(data.repos, 4, async (repo) => {
const pulls = await listPaginated(`/repos/${repo.workspace}/${repo.repo}/pulls?state=open`);
- results.push({
+ return {
repo,
pullRequests: pulls.map(mapPullRequestSummary),
- });
- }
-
- return results;
+ };
+ });
+ },
+ async fetchPullRequestCriticalByRef(data): Promise {
+ return fetchGithubPullRequestCritical({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ });
+ },
+ async fetchPullRequestDeferredByRef(data): Promise {
+ return fetchGithubPullRequestDeferred({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ });
},
async fetchPullRequestBundleByRef(data): Promise {
- const prRef = data.prRef;
- const basePath = `/repos/${prRef.workspace}/${prRef.repo}/pulls/${prRef.pullRequestId}`;
- const isAuthenticated = Boolean(authHeader());
- const [prRes, diffRes, files, commits, issueComments, reviewComments, reviews] = await Promise.all([
- request(basePath),
- request(`${basePath}`, {
- headers: { Accept: "application/vnd.github.v3.diff" },
+ const [critical, deferred] = await Promise.all([
+ fetchGithubPullRequestCritical({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
+ }),
+ fetchGithubPullRequestDeferred({
+ workspace: data.prRef.workspace,
+ repo: data.prRef.repo,
+ pullRequestId: data.prRef.pullRequestId,
}),
- listPaginated(`${basePath}/files`),
- listPaginated(`${basePath}/commits`),
- listPaginated(`/repos/${prRef.workspace}/${prRef.repo}/issues/${prRef.pullRequestId}/comments`),
- listPaginated(`${basePath}/comments`),
- listPaginated(`${basePath}/reviews`),
- ]);
-
- let currentLogin: string | undefined;
- let currentAvatarUrl: string | undefined;
- if (isAuthenticated) {
- const currentUserRes = await request("/user");
- const currentUser = (await currentUserRes.json()) as GithubUser;
- currentLogin = currentUser.login;
- currentAvatarUrl = currentUser.avatar_url;
- }
- const pr = (await prRes.json()) as GithubPull;
- const issueEvents = await listPaginated(`/repos/${prRef.workspace}/${prRef.repo}/issues/${prRef.pullRequestId}/events`).catch(
- () => [],
- );
-
- const headSha = pr.head?.sha;
- const [checks, combinedStatus] = await Promise.all([
- headSha
- ? request(`/repos/${prRef.workspace}/${prRef.repo}/commits/${headSha}/check-runs`)
- .then((res) => res.json() as Promise)
- .catch(() => null)
- : Promise.resolve(null),
- headSha
- ? request(`/repos/${prRef.workspace}/${prRef.repo}/commits/${headSha}/status`)
- .then((res) => res.json() as Promise)
- .catch(() => null)
- : Promise.resolve(null),
]);
-
- let currentUserReviewStatus: PullRequestDetails["currentUserReviewStatus"] = "none";
- if (currentLogin) {
- for (let i = reviews.length - 1; i >= 0; i -= 1) {
- const review = reviews[i];
- if (review.user?.login !== currentLogin) continue;
- const state = (review.state ?? "").toUpperCase();
- if (state === "APPROVED") {
- currentUserReviewStatus = "approved";
- }
- if (state === "CHANGES_REQUESTED") {
- currentUserReviewStatus = "changesRequested";
- }
- if (state === "APPROVED" || state === "CHANGES_REQUESTED" || state === "DISMISSED") {
- if (state === "DISMISSED") currentUserReviewStatus = "none";
- break;
- }
- }
- }
-
- const diffstat: DiffStatEntry[] = files.map((file) => ({
- status: mapFileStatus(file.status),
- new: { path: file.filename },
- old: { path: file.previous_filename ?? file.filename },
- linesAdded: file.additions,
- linesRemoved: file.deletions,
- }));
-
+ const mergedPullRequest: PullRequestDetails = {
+ ...critical.pr,
+ ...(deferred.prPatch ?? {}),
+ };
return {
- prRef,
- pr: mapPullRequestDetails(pr, currentUserReviewStatus, currentLogin, currentAvatarUrl),
- diff: await diffRes.text(),
- diffstat,
- commits: commits.map(mapCommit),
- comments: mergeIssueAndReviewComments(issueComments, reviewComments),
- history: mapHistory(pr, issueComments, reviews, issueEvents),
- reviewers: mapReviewers(pr, reviews),
- buildStatuses: mapBuildStatuses(checks, combinedStatus),
+ ...critical,
+ pr: mergedPullRequest,
+ comments: deferred.comments,
+ history: deferred.history,
+ reviewers: deferred.reviewers,
+ buildStatuses: deferred.buildStatuses,
};
},
async approvePullRequest(data) {
@@ -1096,16 +1179,15 @@ export const githubClient: GitHostClient = {
return { path: normalizedPath, entries: [], fetchedAt: Date.now() };
}
- const entries: PullRequestFileHistoryEntry[] = [];
- for (const commit of commits) {
- if (entries.length >= limit) break;
+ const commitCandidates = commits.filter((commit) => Boolean(commit.hash?.trim()));
+ const resolved = await mapWithConcurrency(commitCandidates, 4, async (commit) => {
const commitHash = commit.hash?.trim();
- if (!commitHash) continue;
+ if (!commitHash) return null;
const commitRes = await request(`/repos/${prRef.workspace}/${prRef.repo}/commits/${commitHash}`);
const commitDetails = (await commitRes.json()) as GithubCommitDetails;
const matchingFile = (commitDetails.files ?? []).find((file) => matchGithubCommitFileForPath(file, normalizedPath));
- if (!matchingFile) continue;
+ if (!matchingFile) return null;
let patch = buildGithubSingleFilePatch(matchingFile);
if (!patch) {
@@ -1115,11 +1197,11 @@ export const githubClient: GitHostClient = {
const diffText = await diffRes.text();
patch = extractSingleFilePatchFromUnifiedDiff(diffText, normalizedPath);
}
- if (!patch) continue;
+ if (!patch) return null;
const filePathAtCommit = matchingFile.filename?.trim() || matchingFile.previous_filename?.trim() || normalizedPath;
const status = mapFileStatus((matchingFile.status ?? "modified").toLowerCase());
- entries.push({
+ return {
versionId: `${normalizedPath}:${commitHash}`,
commitHash,
commitDate: commit.date,
@@ -1128,8 +1210,9 @@ export const githubClient: GitHostClient = {
filePathAtCommit,
status,
patch,
- });
- }
+ };
+ });
+ const entries = resolved.filter((entry): entry is PullRequestFileHistoryEntry => entry !== null).slice(0, limit);
return {
path: normalizedPath,
diff --git a/src/lib/git-host/query-collections.ts b/src/lib/git-host/query-collections.ts
index 8092875..cf4b1bc 100644
--- a/src/lib/git-host/query-collections.ts
+++ b/src/lib/git-host/query-collections.ts
@@ -3,6 +3,8 @@ import { rxdbCollectionOptions } from "@tanstack/rxdb-db-collection";
import {
fetchPullRequestBundleByRef,
fetchPullRequestCommitRangeDiff,
+ fetchPullRequestCriticalByRef,
+ fetchPullRequestDeferredByRef,
fetchPullRequestFileHistory,
fetchRepoPullRequestsForHost,
listRepositoriesForHost,
@@ -12,7 +14,10 @@ import type {
GitHost,
PullRequestBundle,
PullRequestCommitRangeDiff,
+ PullRequestCriticalBundle,
+ PullRequestDeferredBundle,
PullRequestFileHistoryEntry,
+ PullRequestHydrationState,
PullRequestRef,
PullRequestSummary,
RepoRef,
@@ -23,6 +28,9 @@ export type PullRequestBundleRecord = PullRequestBundle & {
id: string;
fetchedAt: number;
expiresAt: number;
+ criticalFetchedAt?: number;
+ deferredFetchedAt?: number;
+ deferredStatus?: PullRequestHydrationState["deferredStatus"];
};
type PersistedPullRequestBundleRecord = PullRequestBundleRecord;
@@ -138,7 +146,7 @@ export type GitHostDataDebugSnapshot = {
>;
};
-const HOST_DATA_DATABASE_NAME = "pullrequestdotreview_host_data_v5";
+const HOST_DATA_DATABASE_NAME = "pullrequestdotreview_host_data_v6";
const REPOSITORY_RX_COLLECTION_NAME = "repositories";
const REPO_PULL_REQUEST_RX_COLLECTION_NAME = "repo_pull_requests";
const PULL_REQUEST_BUNDLE_RX_COLLECTION_NAME = "pull_request_bundles";
@@ -318,6 +326,16 @@ const PULL_REQUEST_BUNDLE_RX_SCHEMA = {
type: "number",
minimum: 0,
},
+ criticalFetchedAt: {
+ type: ["number", "null"],
+ },
+ deferredFetchedAt: {
+ type: ["number", "null"],
+ },
+ deferredStatus: {
+ type: "string",
+ maxLength: 20,
+ },
},
required: ["id", "prRef", "pr", "diff", "diffstat", "commits", "comments", "fetchedAt", "expiresAt"],
additionalProperties: false,
@@ -694,13 +712,58 @@ function approxRecordBytes(record: object) {
return new TextEncoder().encode(JSON.stringify(record)).length;
}
-function serializePullRequestBundle(bundle: PullRequestBundle): PersistedPullRequestBundleRecord {
+function serializePullRequestCriticalBundle(
+ critical: PullRequestCriticalBundle,
+ existing: PersistedPullRequestBundleRecord | undefined,
+): PersistedPullRequestBundleRecord {
+ const fetchedAt = Date.now();
+ return {
+ id: pullRequestBundleId(critical.prRef),
+ prRef: critical.prRef,
+ pr: {
+ ...(existing?.pr ?? {}),
+ ...critical.pr,
+ },
+ diff: critical.diff,
+ diffstat: critical.diffstat,
+ commits: critical.commits,
+ comments: existing?.comments ?? [],
+ history: existing?.history ?? [],
+ reviewers: existing?.reviewers ?? [],
+ buildStatuses: existing?.buildStatuses ?? [],
+ fetchedAt,
+ expiresAt: cacheExpiresAt(fetchedAt),
+ criticalFetchedAt: fetchedAt,
+ deferredFetchedAt: existing?.deferredFetchedAt,
+ deferredStatus: "loading",
+ };
+}
+
+function mergePullRequestDeferredBundle(record: PersistedPullRequestBundleRecord, deferred: PullRequestDeferredBundle): PersistedPullRequestBundleRecord {
const fetchedAt = Date.now();
return {
- ...bundle,
- id: pullRequestBundleId(bundle.prRef),
+ ...record,
+ pr: deferred.prPatch ? { ...record.pr, ...deferred.prPatch } : record.pr,
+ comments: deferred.comments,
+ history: deferred.history ?? [],
+ reviewers: deferred.reviewers ?? [],
+ buildStatuses: deferred.buildStatuses ?? [],
fetchedAt,
expiresAt: cacheExpiresAt(fetchedAt),
+ criticalFetchedAt: record.criticalFetchedAt ?? fetchedAt,
+ deferredFetchedAt: fetchedAt,
+ deferredStatus: "ready",
+ };
+}
+
+function markPullRequestDeferredError(record: PersistedPullRequestBundleRecord): PersistedPullRequestBundleRecord {
+ const now = Date.now();
+ return {
+ ...record,
+ fetchedAt: now,
+ expiresAt: cacheExpiresAt(now),
+ deferredFetchedAt: now,
+ deferredStatus: "error",
};
}
@@ -1341,22 +1404,67 @@ export async function getGitHostDataDebugSnapshot(now = Date.now()): Promise {
+ const requestId = ++requestSerial;
utils.isFetching = true;
setFetchActivity(scopeId, scopeLabel, true);
try {
- const bundle = await fetchPullRequestBundleByRef({ prRef });
- await upsertRecord("pullRequestBundles", serializePullRequestBundle(bundle));
- utils.lastError = undefined;
- utils.dataUpdatedAt = Date.now();
+ if (!staged) {
+ const bundle = await fetchPullRequestBundleByRef({ prRef });
+ if (requestId !== requestSerial) return;
+ const legacyRecord = {
+ ...bundle,
+ id: pullRequestBundleId(bundle.prRef),
+ fetchedAt: Date.now(),
+ expiresAt: cacheExpiresAt(Date.now()),
+ criticalFetchedAt: Date.now(),
+ deferredFetchedAt: Date.now(),
+ deferredStatus: "ready" as const,
+ };
+ await upsertRecord("pullRequestBundles", legacyRecord);
+ utils.lastError = undefined;
+ utils.dataUpdatedAt = Date.now();
+ } else {
+ const collection = getHostDataCollection("pullRequestBundles");
+ const existingRecord = collection.get(bundleId);
+ const critical = await fetchPullRequestCriticalByRef({ prRef });
+ if (requestId !== requestSerial) return;
+ const stagedCriticalRecord = serializePullRequestCriticalBundle(critical, existingRecord);
+ await upsertRecord("pullRequestBundles", stagedCriticalRecord);
+ utils.lastError = undefined;
+ utils.dataUpdatedAt = Date.now();
+
+ const deferredScopeId = `${scopeId}:deferred`;
+ const deferredScopeLabel = `${scopeLabel} [deferred]`;
+ setFetchActivity(deferredScopeId, deferredScopeLabel, true);
+ try {
+ const deferred = await fetchPullRequestDeferredByRef({ prRef });
+ if (requestId !== requestSerial) return;
+ const currentRecord = collection.get(bundleId) ?? stagedCriticalRecord;
+ const mergedRecord = mergePullRequestDeferredBundle(currentRecord, deferred);
+ await upsertRecord("pullRequestBundles", mergedRecord);
+ utils.dataUpdatedAt = Date.now();
+ } catch (deferredError) {
+ if (requestId !== requestSerial) return;
+ const currentRecord = collection.get(bundleId) ?? stagedCriticalRecord;
+ await upsertRecord("pullRequestBundles", markPullRequestDeferredError(currentRecord));
+ if (opts?.throwOnError && !existingRecord) {
+ throw deferredError;
+ }
+ } finally {
+ setFetchActivity(deferredScopeId, deferredScopeLabel, false);
+ }
+ }
} catch (error) {
utils.lastError = error;
if (opts?.throwOnError) {
@@ -1372,9 +1480,9 @@ export function getPullRequestBundleCollection(prRef: PullRequestRef) {
collection: getHostDataCollection("pullRequestBundles"),
utils,
};
- const { evicted } = pullRequestBundleScopedCollections.set(bundleId, scoped);
+ const { evicted } = pullRequestBundleScopedCollections.set(scopeId, scoped);
if (evicted) {
- unregisterScope(`pr-bundle:${evicted.key}`);
+ unregisterScope(evicted.key);
}
registerRefetchScope(scopeId, scopeLabel, utils.refetch);
return scoped;
diff --git a/src/lib/git-host/service.ts b/src/lib/git-host/service.ts
index 1921a11..dac4e6d 100644
--- a/src/lib/git-host/service.ts
+++ b/src/lib/git-host/service.ts
@@ -26,6 +26,14 @@ export async function fetchPullRequestBundleByRef(data: { prRef: PullRequestRef
return getHostClient(data.prRef.host).fetchPullRequestBundleByRef(data);
}
+export async function fetchPullRequestCriticalByRef(data: { prRef: PullRequestRef }) {
+ return getHostClient(data.prRef.host).fetchPullRequestCriticalByRef(data);
+}
+
+export async function fetchPullRequestDeferredByRef(data: { prRef: PullRequestRef }) {
+ return getHostClient(data.prRef.host).fetchPullRequestDeferredByRef(data);
+}
+
export async function approvePullRequest(data: { prRef: PullRequestRef }) {
return getHostClient(data.prRef.host).approvePullRequest(data);
}
diff --git a/src/lib/git-host/types.ts b/src/lib/git-host/types.ts
index c591d08..0397819 100644
--- a/src/lib/git-host/types.ts
+++ b/src/lib/git-host/types.ts
@@ -155,6 +155,29 @@ export interface PullRequestBundle {
buildStatuses?: PullRequestBuildStatus[];
}
+export interface PullRequestCriticalBundle {
+ prRef: PullRequestRef;
+ pr: PullRequestDetails;
+ diff: string;
+ diffstat: DiffStatEntry[];
+ commits: Commit[];
+}
+
+export interface PullRequestDeferredBundle {
+ prRef: PullRequestRef;
+ comments: Comment[];
+ history?: PullRequestHistoryEvent[];
+ reviewers?: PullRequestReviewer[];
+ buildStatuses?: PullRequestBuildStatus[];
+ prPatch?: Partial;
+}
+
+export interface PullRequestHydrationState {
+ criticalFetchedAt: number;
+ deferredFetchedAt?: number;
+ deferredStatus: "idle" | "loading" | "ready" | "error";
+}
+
export interface PullRequestCommitRangeDiff {
prRef: PullRequestRef;
baseCommitHash: string;
@@ -237,6 +260,8 @@ export interface GitHostClient {
logout(): Promise;
listRepositories(): Promise;
listPullRequestsForRepos(data: { repos: RepoRef[] }): Promise>;
+ fetchPullRequestCriticalByRef(data: { prRef: PullRequestRef }): Promise;
+ fetchPullRequestDeferredByRef(data: { prRef: PullRequestRef }): Promise;
fetchPullRequestBundleByRef(data: { prRef: PullRequestRef }): Promise;
approvePullRequest(data: { prRef: PullRequestRef }): Promise<{ ok: true }>;
removePullRequestApproval(data: { prRef: PullRequestRef }): Promise<{ ok: true }>;
diff --git a/src/lib/review-diff-scope.ts b/src/lib/review-diff-scope.ts
index 6427e23..3acc9c7 100644
--- a/src/lib/review-diff-scope.ts
+++ b/src/lib/review-diff-scope.ts
@@ -14,7 +14,7 @@ type ResolveReviewDiffScopeArgs = {
destinationCommitHash?: string;
};
-export type ResolvedReviewDiffScope =
+type ResolvedReviewDiffScope =
| {
mode: "full";
visibleCommits: Commit[];
diff --git a/src/lib/review-performance/metrics.ts b/src/lib/review-performance/metrics.ts
new file mode 100644
index 0000000..50157fc
--- /dev/null
+++ b/src/lib/review-performance/metrics.ts
@@ -0,0 +1,90 @@
+export type ReviewPerfSnapshot = {
+ lastCriticalLoadMs: number | null;
+ lastDeferredLoadMs: number | null;
+ longTaskCount: number;
+ workerQueueDepth: number;
+};
+
+const snapshot: ReviewPerfSnapshot = {
+ lastCriticalLoadMs: null,
+ lastDeferredLoadMs: null,
+ longTaskCount: 0,
+ workerQueueDepth: 0,
+};
+
+const markCounts = new Map();
+let longTaskObserverStarted = false;
+
+function nextMarkName(name: string) {
+ const count = (markCounts.get(name) ?? 0) + 1;
+ markCounts.set(name, count);
+ return `${name}#${count}`;
+}
+
+export function markReviewPerf(name: string) {
+ if (typeof performance === "undefined") return "";
+ const markName = nextMarkName(name);
+ performance.mark(markName);
+ return markName;
+}
+
+export function measureReviewPerf(name: string, startMark: string, endMark?: string) {
+ if (typeof performance === "undefined" || !startMark) return null;
+ const end = endMark && endMark.length > 0 ? endMark : undefined;
+ try {
+ performance.measure(name, startMark, end);
+ const entries = performance.getEntriesByName(name, "measure");
+ const latest = entries[entries.length - 1];
+ return latest ? latest.duration : null;
+ } catch {
+ return null;
+ }
+}
+
+export function setCriticalLoadDuration(durationMs: number) {
+ snapshot.lastCriticalLoadMs = Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : null;
+}
+
+export function setDeferredLoadDuration(durationMs: number) {
+ snapshot.lastDeferredLoadMs = Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : null;
+}
+
+export function setWorkerQueueDepth(depth: number) {
+ if (!Number.isFinite(depth)) return;
+ snapshot.workerQueueDepth = Math.max(0, Math.round(depth));
+}
+
+function incrementLongTaskCount() {
+ snapshot.longTaskCount += 1;
+}
+
+export function getReviewPerfSnapshot(): ReviewPerfSnapshot {
+ return { ...snapshot };
+}
+
+export function ensureLongTaskObserver() {
+ if (longTaskObserverStarted || typeof window === "undefined" || typeof PerformanceObserver === "undefined") {
+ return;
+ }
+
+ const supportedEntryTypes = PerformanceObserver.supportedEntryTypes;
+ if (!Array.isArray(supportedEntryTypes) || !supportedEntryTypes.includes("longtask")) {
+ return;
+ }
+
+ const observer = new PerformanceObserver((list) => {
+ const entries = list.getEntries();
+ if (!entries.length) return;
+ for (const entry of entries) {
+ if (entry.entryType !== "longtask") continue;
+ incrementLongTaskCount();
+ }
+ });
+
+ try {
+ observer.observe({ type: "longtask", buffered: true });
+ longTaskObserverStarted = true;
+ } catch {
+ // Ignore unsupported browsers.
+ }
+}
diff --git a/src/lib/review-performance/review-compute-worker-context.tsx b/src/lib/review-performance/review-compute-worker-context.tsx
new file mode 100644
index 0000000..1c04e1d
--- /dev/null
+++ b/src/lib/review-performance/review-compute-worker-context.tsx
@@ -0,0 +1,156 @@
+import type { FileDiffMetadata } from "@pierre/diffs/react";
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
+import type { CommentThread } from "@/components/pull-request-review/review-threads";
+import type { Comment as PullRequestComment } from "@/lib/git-host/types";
+import ReviewComputeWorker from "@/lib/review-performance/review-compute.worker?worker";
+import { LruCache } from "@/lib/utils/lru";
+
+type ComputeReviewDerivedPayload = {
+ cacheKey: string;
+ diffText: string;
+ comments: PullRequestComment[];
+};
+
+type ComputeReviewDerivedResult = {
+ fileDiffs: FileDiffMetadata[];
+ fileDiffFingerprints: Map;
+ threads: CommentThread[];
+};
+
+type WorkerRequest = {
+ type: "compute-review-derived";
+ requestId: number;
+ diffText: string;
+ comments: PullRequestComment[];
+};
+
+type WorkerSuccessResponse = {
+ type: "compute-review-derived:success";
+ requestId: number;
+ fileDiffs: FileDiffMetadata[];
+ fileDiffFingerprints: Array<[string, string]>;
+ threads: CommentThread[];
+};
+
+type WorkerErrorResponse = {
+ type: "compute-review-derived:error";
+ requestId: number;
+ error: string;
+};
+
+type WorkerResponse = WorkerSuccessResponse | WorkerErrorResponse;
+
+type PendingRequest = {
+ cacheKey: string;
+ resolve: (value: ComputeReviewDerivedResult) => void;
+ reject: (error: Error) => void;
+};
+
+type ReviewComputeWorkerContextValue = {
+ computeReviewDerived: (payload: ComputeReviewDerivedPayload) => Promise;
+ workerReady: boolean;
+};
+
+const ReviewComputeWorkerContext = createContext(null);
+
+export function ReviewComputeWorkerProvider({ children }: { children: ReactNode }) {
+ const [workerReady, setWorkerReady] = useState(false);
+ const workerRef = useRef(null);
+ const nextRequestIdRef = useRef(1);
+ const pendingRequestsRef = useRef(new Map());
+ const cacheRef = useRef(new LruCache(40));
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+
+ const worker = new ReviewComputeWorker();
+ workerRef.current = worker;
+ setWorkerReady(true);
+
+ worker.onmessage = (event: MessageEvent) => {
+ const message = event.data;
+ const pending = pendingRequestsRef.current.get(message.requestId);
+ if (!pending) return;
+ pendingRequestsRef.current.delete(message.requestId);
+
+ if (message.type === "compute-review-derived:error") {
+ pending.reject(new Error(message.error));
+ return;
+ }
+
+ const result: ComputeReviewDerivedResult = {
+ fileDiffs: message.fileDiffs,
+ fileDiffFingerprints: new Map(message.fileDiffFingerprints),
+ threads: message.threads,
+ };
+ cacheRef.current.set(pending.cacheKey, result);
+ pending.resolve(result);
+ };
+
+ worker.onerror = (event) => {
+ const reason = event?.message || "Review compute worker failed.";
+ for (const pending of pendingRequestsRef.current.values()) {
+ pending.reject(new Error(reason));
+ }
+ pendingRequestsRef.current.clear();
+ };
+
+ return () => {
+ for (const pending of pendingRequestsRef.current.values()) {
+ pending.reject(new Error("Review compute worker terminated."));
+ }
+ pendingRequestsRef.current.clear();
+ worker.terminate();
+ workerRef.current = null;
+ };
+ }, []);
+
+ const computeReviewDerived = useCallback((payload: ComputeReviewDerivedPayload) => {
+ const cached = cacheRef.current.get(payload.cacheKey);
+ if (cached) {
+ return Promise.resolve(cached);
+ }
+
+ const worker = workerRef.current;
+ if (!worker) {
+ return Promise.reject(new Error("Review compute worker is unavailable."));
+ }
+
+ const requestId = nextRequestIdRef.current;
+ nextRequestIdRef.current += 1;
+
+ return new Promise((resolve, reject) => {
+ pendingRequestsRef.current.set(requestId, {
+ cacheKey: payload.cacheKey,
+ resolve,
+ reject,
+ });
+
+ const request: WorkerRequest = {
+ type: "compute-review-derived",
+ requestId,
+ diffText: payload.diffText,
+ comments: payload.comments,
+ };
+ worker.postMessage(request);
+ });
+ }, []);
+
+ const value = useMemo(
+ () => ({
+ computeReviewDerived,
+ workerReady,
+ }),
+ [computeReviewDerived, workerReady],
+ );
+
+ return {children};
+}
+
+export function useReviewComputeWorker() {
+ const context = useContext(ReviewComputeWorkerContext);
+ if (!context) {
+ throw new Error("useReviewComputeWorker must be used within ReviewComputeWorkerProvider");
+ }
+ return context;
+}
diff --git a/src/lib/review-performance/review-compute.worker.ts b/src/lib/review-performance/review-compute.worker.ts
new file mode 100644
index 0000000..0ba31b2
--- /dev/null
+++ b/src/lib/review-performance/review-compute.worker.ts
@@ -0,0 +1,142 @@
+import { parsePatchFiles } from "@pierre/diffs";
+import type { FileDiffMetadata } from "@pierre/diffs/react";
+import type { Comment as PullRequestComment } from "@/lib/git-host/types";
+
+type CommentThread = {
+ id: number;
+ root: PullRequestComment;
+ replies: PullRequestComment[];
+};
+
+type ComputeReviewDerivedRequest = {
+ type: "compute-review-derived";
+ requestId: number;
+ diffText: string;
+ comments: PullRequestComment[];
+};
+
+type ComputeReviewDerivedSuccess = {
+ type: "compute-review-derived:success";
+ requestId: number;
+ fileDiffs: FileDiffMetadata[];
+ fileDiffFingerprints: Array<[string, string]>;
+ threads: CommentThread[];
+};
+
+type ComputeReviewDerivedError = {
+ type: "compute-review-derived:error";
+ requestId: number;
+ error: string;
+};
+
+type WorkerRequest = ComputeReviewDerivedRequest;
+type WorkerResponse = ComputeReviewDerivedSuccess | ComputeReviewDerivedError;
+
+function hashString(value: string) {
+ let hash1 = 0x811c9dc5;
+ let hash2 = 0x01000193;
+ for (let i = 0; i < value.length; i += 1) {
+ const char = value.charCodeAt(i);
+ hash1 = Math.imul(hash1 ^ char, 0x01000193);
+ hash2 = Math.imul(hash2 ^ (char + i), 0x01000193);
+ }
+ return `${(hash1 >>> 0).toString(16)}${(hash2 >>> 0).toString(16)}`;
+}
+
+function getFilePath(fileDiff: FileDiffMetadata, index: number) {
+ return fileDiff.name ?? fileDiff.prevName ?? String(index);
+}
+
+function buildFileDiffFingerprint(fileDiff: FileDiffMetadata) {
+ const normalized = {
+ type: fileDiff.type,
+ name: fileDiff.name,
+ prevName: fileDiff.prevName ?? "",
+ hunks: (fileDiff.hunks ?? []).map((hunk) => ({
+ additionCount: hunk.additionCount,
+ additionLines: hunk.additionLines,
+ additionStart: hunk.additionStart,
+ deletionCount: hunk.deletionCount,
+ deletionLines: hunk.deletionLines,
+ deletionStart: hunk.deletionStart,
+ unifiedLineCount: hunk.unifiedLineCount,
+ unifiedLineStart: hunk.unifiedLineStart,
+ splitLineCount: hunk.splitLineCount,
+ splitLineStart: hunk.splitLineStart,
+ hunkContext: hunk.hunkContext,
+ hunkSpecs: hunk.hunkSpecs,
+ hunkContent: hunk.hunkContent,
+ })),
+ };
+ return hashString(JSON.stringify(normalized));
+}
+
+function sortByCreatedAt(left: { createdAt?: string }, right: { createdAt?: string }) {
+ return new Date(left.createdAt ?? 0).getTime() - new Date(right.createdAt ?? 0).getTime();
+}
+
+function buildCommentThreads(comments: PullRequestComment[]): CommentThread[] {
+ const roots = comments.filter((comment) => !comment.parent?.id);
+ const repliesByParent = new Map();
+
+ for (const comment of comments) {
+ const parentId = comment.parent?.id;
+ if (!parentId) continue;
+ const replies = repliesByParent.get(parentId) ?? [];
+ replies.push(comment);
+ repliesByParent.set(parentId, replies);
+ }
+
+ return roots
+ .map((root) => ({
+ id: root.id,
+ root,
+ replies: [...(repliesByParent.get(root.id) ?? [])].sort(sortByCreatedAt),
+ }))
+ .sort((left, right) => sortByCreatedAt(left.root, right.root));
+}
+
+function computeReviewDerived(diffText: string, comments: PullRequestComment[]) {
+ const patches = diffText ? parsePatchFiles(diffText) : [];
+ const fileDiffs = patches.flatMap((patch) => patch.files);
+ const fingerprintEntries = new Map();
+
+ fileDiffs.forEach((fileDiff, index) => {
+ const path = getFilePath(fileDiff, index);
+ if (!fingerprintEntries.has(path)) {
+ fingerprintEntries.set(path, buildFileDiffFingerprint(fileDiff));
+ }
+ });
+
+ return {
+ fileDiffs,
+ fileDiffFingerprints: Array.from(fingerprintEntries.entries()),
+ threads: buildCommentThreads(comments),
+ };
+}
+
+const workerScope = self as unknown as Worker;
+
+workerScope.onmessage = (event: MessageEvent) => {
+ const message = event.data;
+ if (!message || message.type !== "compute-review-derived") return;
+
+ try {
+ const result = computeReviewDerived(message.diffText, message.comments);
+ const response: ComputeReviewDerivedSuccess = {
+ type: "compute-review-derived:success",
+ requestId: message.requestId,
+ fileDiffs: result.fileDiffs,
+ fileDiffFingerprints: result.fileDiffFingerprints,
+ threads: result.threads,
+ };
+ workerScope.postMessage(response as WorkerResponse);
+ } catch (error) {
+ const response: ComputeReviewDerivedError = {
+ type: "compute-review-derived:error",
+ requestId: message.requestId,
+ error: error instanceof Error ? error.message : "Failed to compute review derived data.",
+ };
+ workerScope.postMessage(response as WorkerResponse);
+ }
+};
diff --git a/src/routes/$workspace/$repo/pull-requests/$pullRequestId.tsx b/src/routes/$workspace/$repo/pull-requests/$pullRequestId.tsx
index 848c061..7f7ac41 100644
--- a/src/routes/$workspace/$repo/pull-requests/$pullRequestId.tsx
+++ b/src/routes/$workspace/$repo/pull-requests/$pullRequestId.tsx
@@ -1,7 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
+import { useEffect } from "react";
import { PullRequestReviewPage } from "@/components/pull-request-review-page";
import { usePrContext } from "@/lib/pr-context";
import { type ReviewDiffScopeSearch, validateReviewDiffScopeSearch } from "@/lib/review-diff-scope";
+import { markReviewPerf } from "@/lib/review-performance/metrics";
export const Route = createFileRoute("/$workspace/$repo/pull-requests/$pullRequestId")({
validateSearch: validateReviewDiffScopeSearch,
@@ -14,6 +16,10 @@ function BitbucketPullRequestRoute() {
const navigate = Route.useNavigate();
const { authByHost } = usePrContext();
+ useEffect(() => {
+ markReviewPerf("route_enter");
+ }, []);
+
return (
{
+ markReviewPerf("route_enter");
+ }, []);
+
return (
{
- let cancelled = false;
- ensureDataCollectionsReady().finally(() => {
- if (cancelled) return;
- setStorageReady(true);
- });
- return () => {
- cancelled = true;
- };
+ void ensureDataCollectionsReady();
+ ensureLongTaskObserver();
}, []);
return (
- {storageReady ? (
-
-
-
-
-
-
-
-
-
-
-
-
- ) : (
-
- )}
+
+
+
+
+
+
+
+
+
+
+
);