@devries-cameron20 / t3code Mirror · read-only / commits / 78f8d38ebb
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 05:30 UTC

refactor(web): pull request code tab keeps its caching without "use memo" (#20816)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 17, 2026 at 00:33 UTC 78f8d38ebb8c7cabddc2a0c9f114d5aa27c95ab3
5 files changed +81 -136
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+79 -108
@@ -1,9 +1,4 @@
1 -import type {
2 - CodeViewItem,
3 - DiffLineAnnotation,
4 - FileDiffMetadata,
5 - SelectedLineRange,
6 -} from "@pierre/diffs";
1 +import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
2 import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
3 import type {
4 EnvironmentId,
@@ -243,47 +238,6 @@ export interface PullRequestAgentSelectionInput {
238 readonly request: string;
239 }
240
246 -// Kept as a "use memo" hook: each item's version needs the viewed state that
247 -// `usePullRequestFilesViewed` returns, so items are built after that hook from `annotatedFiles`. Those
248 -// alias `files`, which already went through plain functions before the hook, and the hook itself has
249 -// to receive `filePaths`. Built inline, that straddle leaves `files` and everything derived from it
250 -// uncached. The viewer re-renders each item on its version.
251 -function useDiffItems(
252 - annotatedFiles: ReadonlyArray<{
253 - readonly fileKey: string;
254 - readonly path: string;
255 - readonly fileDiff: FileDiffMetadata;
256 - readonly annotations: ReviewAnnotation[];
257 - readonly annotationsVersion: number;
258 - }>,
259 - foldOverride: Exclude<DiffFoldOverride, null>,
260 - toggledFiles: ReadonlySet<string>,
261 - viewedFiles: {
262 - readonly enabled: boolean;
263 - readonly isViewed: (path: string) => boolean;
264 - readonly isStale: (path: string) => boolean;
265 - },
266 -) {
267 - "use memo";
268 - const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
269 - ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
270 - const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles);
271 - const viewedMark = viewedFiles.enabled
272 - ? `e${viewedFiles.isViewed(path) ? "v" : ""}${viewedFiles.isStale(path) ? "s" : ""}`
273 - : "";
274 - return {
275 - id: fileKey,
276 - type: "diff" as const,
277 - fileDiff,
278 - annotations,
279 - collapsed,
280 - version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
281 - };
282 - },
283 - );
284 - return items;
285 -}
286 -
241 function PullRequestCodeTab({
242 scrollerRef,
243 environmentId,
@@ -451,13 +405,41 @@ function PullRequestCodeTab({
405 reportFailure: false,
406 });
407 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
408 +
409 + const viewedFilesStore = detail.capabilities.viewedFiles;
410 + const filesViewed = usePullRequestFilesViewed({
411 + environmentId,
412 + reference,
413 + enabled: viewedFilesStore !== undefined,
414 + });
415 + const {
416 + setViewed,
417 + refresh: refreshFilesViewed,
418 + enabled: filesViewedEnabled,
419 + isViewed: isFileViewed,
420 + isStale: isFileViewedStale,
421 + } = filesViewed;
422 + const appliedRefreshToken = useRef(refreshToken);
423 + useEffect(() => {
424 + if (appliedRefreshToken.current === refreshToken) return;
425 + appliedRefreshToken.current = refreshToken;
426 + setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
427 + refreshFirstDiffPage();
428 + refreshFilesViewed();
429 + }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
430 +
431 + // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
432 + // an effect reading a ref could run before that node exists and would never arm the observer.
433 + const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
434 + const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
435 + const answeredReveal = useRef<number | null>(null);
436 +
437 const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
438 environmentId,
439 reference,
440 commit,
441 cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
442 });
460 -
443 const hostReview = detail.capabilities.review;
444 const review = {
445 inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
@@ -632,30 +614,23 @@ function PullRequestCodeTab({
614 ))}
615 </div>
616 );
635 - const viewedFilesStore = detail.capabilities.viewedFiles;
636 - const filesViewed = usePullRequestFilesViewed({
637 - environmentId,
638 - reference,
639 - enabled: viewedFilesStore !== undefined,
640 - paths: filePaths,
641 - });
642 - const {
643 - setViewed,
644 - refresh: refreshFilesViewed,
645 - enabled: filesViewedEnabled,
646 - isViewed: isFileViewed,
647 - isStale: isFileViewedStale,
648 - } = filesViewed;
649 - const appliedRefreshToken = useRef(refreshToken);
650 - useEffect(() => {
651 - if (appliedRefreshToken.current === refreshToken) return;
652 - appliedRefreshToken.current = refreshToken;
653 - setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
654 - refreshFirstDiffPage();
655 - refreshFilesViewed();
656 - }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
617
658 - const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed);
618 + const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
619 + ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
620 + const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);
621 + const viewedMark = filesViewedEnabled
622 + ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`
623 + : "";
624 + return {
625 + id: fileKey,
626 + type: "diff" as const,
627 + fileDiff,
628 + annotations,
629 + collapsed,
630 + version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
631 + };
632 + },
633 + );
634 const fileKeys = items.map((item) => item.id);
635 const collapsedFileKeys = new Set(
636 items.filter((item) => item.collapsed === true).map((item) => item.id),
@@ -674,21 +649,6 @@ function PullRequestCodeTab({
649 setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
650 };
651
677 - // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
678 - // an effect reading a ref could run before that node exists and would never arm the observer.
679 - const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
680 - useEffect(() => {
681 - if (sentinel === null || !canLoadNextSlice) return;
682 - const observer = new IntersectionObserver(
683 - (observed) => {
684 - if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
685 - },
686 - { rootMargin: "240px" },
687 - );
688 - observer.observe(sentinel);
689 - return () => observer.disconnect();
690 - }, [canLoadNextSlice, loadNextSlice, sentinel]);
691 -
652 const toggleFile = (fileKey: string) =>
653 setToggledFiles((current) => {
654 const next = new Set(current);
@@ -710,28 +670,12 @@ function PullRequestCodeTab({
670 setFileViewed,
671 };
672
713 - const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
673 const revealFile = (path: string) => {
674 const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
675 if (item === undefined) return;
676 if (item.collapsed === true) toggleFile(item.id);
677 requestTreeReveal(item.id);
678 };
720 - const answeredReveal = useRef<number | null>(null);
721 - const answerReveal = useEffectEvent(() => {
722 - if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
723 - if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
724 - if (canLoadNextSlice) loadNextSlice();
725 - return;
726 - }
727 - answeredReveal.current = revealRequest.nonce;
728 - revealFile(revealRequest.path);
729 - });
730 - useEffect(() => {
731 - // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
732 - answerReveal();
733 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
734 - }, [canLoadNextSlice, items, revealRequest]);
679
680 const toggleAllFiles = () => {
681 setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
@@ -1014,11 +958,6 @@ function PullRequestCodeTab({
958 // to the whole diff and it is not drawn without commits to list, so a scope that outlived them
959 // would leave the tab reading one obsolete commit with nothing to press.
960 const selectedCommit = orderedCommits.find((entry) => entry.oid === commit);
1017 - useEffect(() => {
1018 - if (commit !== null && selectedCommit === undefined) {
1019 - onSelectedCommitChange(null);
1020 - }
1021 - }, [commit, onSelectedCommitChange, selectedCommit]);
961 const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits";
962 const changeIgnoreWhitespace = (next: boolean) => {
963 setIgnoreWhitespace(next);
@@ -1083,7 +1022,7 @@ function PullRequestCodeTab({
1022 {filesViewed.enabled && files.length > 0 ? (
1023 <span className="flex min-w-0 items-center gap-1 tabular-nums">
1024 <span className="shrink-0">
1086 - {filesViewed.viewedCount} / {files.length}
1025 + {filePaths.filter(isFileViewed).length} / {files.length}
1026 </span>
1027 <span className="truncate">
1028 {viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"}
@@ -1316,6 +1255,38 @@ function PullRequestCodeTab({
1255 </div>
1256 </div>
1257 );
1258 + // The effects sit after every derivation: a hook between the diff's derivations and their
1259 + // later readers (the viewer options, the reveal handler) would leave them uncached.
1260 + useEffect(() => {
1261 + if (sentinel === null || !canLoadNextSlice) return;
1262 + const observer = new IntersectionObserver(
1263 + (observed) => {
1264 + if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
1265 + },
1266 + { rootMargin: "240px" },
1267 + );
1268 + observer.observe(sentinel);
1269 + return () => observer.disconnect();
1270 + }, [canLoadNextSlice, loadNextSlice, sentinel]);
1271 + const answerReveal = useEffectEvent(() => {
1272 + if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
1273 + if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
1274 + if (canLoadNextSlice) loadNextSlice();
1275 + return;
1276 + }
1277 + answeredReveal.current = revealRequest.nonce;
1278 + revealFile(revealRequest.path);
1279 + });
1280 + useEffect(() => {
1281 + // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
1282 + answerReveal();
1283 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
1284 + }, [canLoadNextSlice, items, revealRequest]);
1285 + useEffect(() => {
1286 + if (commit !== null && selectedCommit === undefined) {
1287 + onSelectedCommitChange(null);
1288 + }
1289 + }, [commit, onSelectedCommitChange, selectedCommit]);
1290 const withToolbar = (body: ReactNode) => (
1291 <div className="flex h-full min-h-0 flex-col">
1292 {toolbar}
apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts
-9
@@ -1,7 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 import {
4 - countViewedFiles,
4 isFileViewed,
5 isStaleViewedState,
6 revertFileViewedOverlay,
@@ -47,14 +46,6 @@ describe("isFileViewed", () => {
46 });
47 });
48
50 -describe("countViewedFiles", () => {
51 - it("counts only the files on screen, presses included", () => {
52 - expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, NO_OVERLAY)).toBe(1);
53 - expect(countViewedFiles(["a.ts", "b.ts", "c.ts"], states, new Map([["b.ts", true]]))).toBe(2);
54 - expect(countViewedFiles(["b.ts"], states, NO_OVERLAY)).toBe(0);
55 - });
56 -});
57 -
49 describe("settleFileViewedOverlay", () => {
50 it("drops a press the host has caught up on", () => {
51 const settled = settleFileViewedOverlay(
apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts
-11
@@ -28,17 +28,6 @@ export function isFileViewed(
28 return pressed ?? isViewedState(states?.get(path));
29 }
30
31 -export function countViewedFiles(
32 - paths: ReadonlyArray<string>,
33 - states: FileViewedStates | null,
34 - overlay: FileViewedOverlay,
35 -): number {
36 - return paths.reduce(
37 - (total, path) => (isFileViewed(path, states, overlay) ? total + 1 : total),
38 - 0,
39 - );
40 -}
41 -
31 /**
32 * A press is held until a read that could have seen it comes back, rather than cleared when the
33 * write succeeds: that read is a separate round trip, and dropping the press in between flashes
apps/web/src/components/pullRequest/usePullRequestFilesViewed.test.tsx
+1 -3
@@ -41,7 +41,6 @@ const reference: PullRequestRef = {
41 repository: "acme/web",
42 number: 42,
43 };
44 -const paths = ["a.ts"];
44
45 function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesViewedResult {
46 return { files: [{ path: "a.ts", state }], truncated: false };
@@ -54,7 +53,7 @@ function Probe(_props: { readonly view: PullRequestFilesViewedView }) {
53 }
54
55 function Surface() {
57 - const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true, paths });
56 + const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
57 return <Probe view={view} />;
58 }
59
@@ -110,7 +109,6 @@ describe("a mark whose file was pushed to before the read that followed it", ()
109
110 expect(view().isViewed("a.ts")).toBe(false);
111 expect(view().isStale("a.ts")).toBe(true);
113 - expect(view().viewedCount).toBe(0);
112 });
113
114 it("stays given way to on every later read, having nothing left to recover", async () => {
apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts
+1 -5
@@ -9,7 +9,6 @@ import { useStableCallback } from "~/hooks/useStableCallback";
9
10 import { toastManager } from "../ui/toast";
11 import {
12 - countViewedFiles,
12 isFileViewed,
13 isStaleViewedState,
14 revertFileViewedOverlay,
@@ -29,7 +28,6 @@ export interface PullRequestFilesViewedView {
28 readonly isViewed: (path: string) => boolean;
29 readonly isStale: (path: string) => boolean;
30 readonly setViewed: (path: string, viewed: boolean) => void;
32 - readonly viewedCount: number;
31 readonly truncated: boolean;
32 readonly error: string | null;
33 readonly refresh: () => void;
@@ -39,9 +37,8 @@ export function usePullRequestFilesViewed(options: {
37 readonly environmentId: EnvironmentId;
38 readonly reference: PullRequestRef;
39 readonly enabled: boolean;
42 - readonly paths: ReadonlyArray<string>;
40 }): PullRequestFilesViewedView {
44 - const { environmentId, reference, enabled, paths } = options;
41 + const { environmentId, reference, enabled } = options;
42 const query = useEnvironmentQuery(
43 enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
44 );
@@ -154,7 +151,6 @@ export function usePullRequestFilesViewed(options: {
151 isViewed: (path: string) => isFileViewed(path, states, overlay),
152 isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
153 setViewed,
157 - viewedCount: countViewedFiles(paths, states, overlay),
154 truncated,
155 error,
156 refresh,