@devries-cameron20 / t3code-1 / commits / 26bea7e62e
Fork 0

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

perf(web): diff panel reads its loader and collapse defaults without refs (#20468)

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

Julius Marminge committed Oct 16, 2026 at 18:46 UTC 26bea7e62e4fae5d59eeecb74374a87a2287239c
2 files changed +177 -191
apps/web/reactCompiledFiles.ts
+1
@@ -43,4 +43,5 @@ export const REACT_COMPILED_FILES = [
43 "apps/web/src/browser/useBrowserViewportResize.ts",
44 "apps/web/src/components/desktop/SnapShotCoordinator.tsx",
45 "apps/web/src/components/BranchToolbar.tsx",
46 + "apps/web/src/components/DiffPanel.tsx",
47 ] as const;
apps/web/src/components/DiffPanel.tsx
+176 -191
@@ -21,7 +21,7 @@ import {
21 import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
22 import * as Schema from "effect/Schema";
23 import * as DateTime from "effect/DateTime";
24 -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
24 +import { useEffect, useRef, useState } from "react";
25 import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
26 import { useFilesystemReadAccess } from "~/state/filesystem";
27 import { useOpenInPreferredEditor } from "../editorPreferences";
@@ -33,6 +33,7 @@ import { cn } from "~/lib/utils";
33 import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";
34 import { useLocalStorage } from "../hooks/useLocalStorage";
35 import { useTheme } from "../hooks/useTheme";
36 +import { useStableCallback } from "../hooks/useStableCallback";
37 import {
38 buildFileDiffContentVersion,
39 buildFileDiffIdentityKey,
@@ -112,6 +113,62 @@ function getCachedFileEntry(fileDiff: FileDiffMetadata) {
113 return entry;
114 }
115
116 +// These hooks call no hooks, so the compiler needs the directive to memoize them. Their results
117 +// feed the code view and the file patch loader, which key on identity.
118 +function useRenderablePatch(
119 + patch: string | undefined,
120 + theme: string,
121 + compactPartialHunkOffsets: boolean,
122 +) {
123 + "use memo";
124 + return getRenderablePatch(patch, `diff-panel:${theme}`, { compactPartialHunkOffsets });
125 +}
126 +
127 +function useGitDiffFileContentsLoader<E>(
128 + getDiffFileContents: Parameters<typeof createGitDiffFileContentsLoader<E>>[0],
129 + source: Parameters<typeof createGitDiffFileContentsLoader<E>>[1] | null,
130 +): FileDiffContentsLoader | undefined {
131 + "use memo";
132 + return source ? createGitDiffFileContentsLoader(getDiffFileContents, source) : undefined;
133 +}
134 +
135 +function useFileStats<File extends { readonly path: string }>(
136 + files: ReadonlyArray<File> | undefined,
137 +) {
138 + "use memo";
139 + return new Map(files?.map((file) => [file.path, file]));
140 +}
141 +
142 +function useDiffFileEntries(renderableFiles: ReadonlyArray<FileDiffMetadata>, collapsed: boolean) {
143 + "use memo";
144 + const renderableFileEntries = renderableFiles.map(getCachedFileEntry);
145 + const diffFileKeys = renderableFileEntries.map((file) => file.fileKey);
146 + return {
147 + renderableFileEntries,
148 + diffFileKeys,
149 + defaultCollapsedDiffFileKeys: collapsed
150 + ? new Set(diffFileKeys)
151 + : EMPTY_COLLAPSED_DIFF_FILE_KEYS,
152 + };
153 +}
154 +
155 +function useCodeViewFiles(
156 + entries: ReadonlyArray<ReturnType<typeof getCachedFileEntry>>,
157 + readyFilePaths: ReadonlySet<string> | null,
158 + collapsedFileKeys: ReadonlySet<string>,
159 +) {
160 + "use memo";
161 + return entries
162 + .filter(({ fileDiff }) => !readyFilePaths || readyFilePaths.has(resolveFileDiffPath(fileDiff)))
163 + .map(({ fileDiff, fileKey, fileVersion }) => ({
164 + fileDiff,
165 + filePath: resolveFileDiffPath(fileDiff),
166 + fileKey,
167 + fileVersion,
168 + collapsed: collapsedFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
169 + }));
170 +}
171 +
172 interface CollapsedDiffFilesState {
173 readonly scopeKey: string | null;
174 readonly fileKeys: ReadonlySet<string>;
@@ -260,20 +317,16 @@ export default function DiffPanel({
317 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
318 const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
319 useTurnDiffSummaries(activeThreadProjection);
263 - const orderedTurnDiffSummaries = useMemo(
264 - () =>
265 - [...turnDiffSummaries].toSorted((left, right) => {
266 - const leftTurnCount =
267 - left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
268 - const rightTurnCount =
269 - right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
270 - if (leftTurnCount !== rightTurnCount) {
271 - return rightTurnCount - leftTurnCount;
272 - }
273 - return right.completedAt.localeCompare(left.completedAt);
274 - }),
275 - [inferredCheckpointTurnCountByRunId, turnDiffSummaries],
276 - );
320 + const orderedTurnDiffSummaries = [...turnDiffSummaries].toSorted((left, right) => {
321 + const leftTurnCount =
322 + left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
323 + const rightTurnCount =
324 + right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
325 + if (leftTurnCount !== rightTurnCount) {
326 + return rightTurnCount - leftTurnCount;
327 + }
328 + return right.completedAt.localeCompare(left.completedAt);
329 + });
330
331 useEffect(() => {
332 if (!routeThreadRef || diffSelection.kind !== "turn") return;
@@ -316,16 +369,13 @@ export default function DiffPanel({
369 : selectedGitScope === "unstaged"
370 ? "Uncommitted"
371 : "Changes";
319 - const selectedCheckpointRange = useMemo(
320 - () =>
321 - typeof selectedCheckpointTurnCount === "number"
322 - ? {
323 - fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
324 - toTurnCount: selectedCheckpointTurnCount,
325 - }
326 - : null,
327 - [selectedCheckpointTurnCount],
328 - );
372 + const selectedCheckpointRange =
373 + typeof selectedCheckpointTurnCount === "number"
374 + ? {
375 + fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
376 + toTurnCount: selectedCheckpointTurnCount,
377 + }
378 + : null;
379 const activeCheckpointDiff = useCheckpointDiff(
380 {
381 environmentId: activeThread?.environmentId ?? null,
@@ -361,36 +411,27 @@ export default function DiffPanel({
411 const refreshPreviewQuery = branchDiffPreview.refresh;
412 const refreshDiffFromUserAction = refreshPreviewQuery;
413
364 - const currentLoadDiffFiles = useMemo<FileDiffContentsLoader | undefined>(() => {
365 - const preview = branchDiffPreview.data;
366 - if (selectedRunId !== null || !activeThread || !preview || !selectedGitSource) {
367 - return undefined;
368 - }
369 -
370 - if (!canReadFiles) return undefined;
371 - return createGitDiffFileContentsLoader(getDiffFileContents, {
372 - environmentId: activeThread.environmentId,
373 - cwd: preview.cwd,
374 - sourceKind: selectedGitSource.kind,
375 - baseRef: selectedGitSource.baseRef,
376 - headRef: selectedGitSource.headRef,
377 - cacheKey: selectedGitSource.diffHash,
378 - });
379 - }, [
380 - activeThread,
381 - branchDiffPreview.data,
414 + const preview = branchDiffPreview.data;
415 + const currentLoadDiffFiles = useGitDiffFileContentsLoader(
416 getDiffFileContents,
383 - canReadFiles,
384 - selectedGitSource,
385 - selectedRunId,
386 - ]);
387 - const loadDiffFilesRef = useRef(currentLoadDiffFiles);
388 - loadDiffFilesRef.current = currentLoadDiffFiles;
389 - const loadDiffFiles = useCallback<FileDiffContentsLoader>(async (fileDiff) => {
390 - const loader = loadDiffFilesRef.current;
391 - if (!loader) throw new Error("Diff file contents are unavailable for this selection.");
392 - return loader(fileDiff);
393 - }, []);
417 + selectedRunId === null && activeThread && preview && selectedGitSource && canReadFiles
418 + ? {
419 + environmentId: activeThread.environmentId,
420 + cwd: preview.cwd,
421 + sourceKind: selectedGitSource.kind,
422 + baseRef: selectedGitSource.baseRef,
423 + headRef: selectedGitSource.headRef,
424 + cacheKey: selectedGitSource.diffHash,
425 + }
426 + : null,
427 + );
428 + // The code view keeps one loader for its lifetime; a new identity would remount it.
429 + const loadDiffFiles: FileDiffContentsLoader = useStableCallback(async (fileDiff) => {
430 + if (!currentLoadDiffFiles) {
431 + throw new Error("Diff file contents are unavailable for this selection.");
432 + }
433 + return currentLoadDiffFiles(fileDiff);
434 + });
435 const localBranchRefs = useEnvironmentQuery(
436 selectedRunId === null &&
437 selectedGitScope === "branch" &&
@@ -453,19 +494,12 @@ export default function DiffPanel({
494 !selectedTurn && selectedGitSource?.truncated && selectedGitSource.files
495 ? selectedGitSource
496 : null;
456 - const renderablePatch = useMemo(
457 - () =>
458 - lazySource
459 - ? null
460 - : getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
461 - compactPartialHunkOffsets: selectedRunId === null,
462 - }),
463 - [lazySource, resolvedTheme, selectedPatch, selectedRunId],
464 - );
465 - const fileStats = useMemo(
466 - () => new Map(lazySource?.files?.map((file) => [file.path, file])),
467 - [lazySource?.files],
497 + const renderablePatch = useRenderablePatch(
498 + lazySource ? undefined : selectedPatch,
499 + resolvedTheme,
500 + selectedRunId === null,
501 );
502 + const fileStats = useFileStats(lazySource?.files);
503 const {
504 scope: filePatchScope,
505 isPending: areFilePatchesPending,
@@ -505,66 +539,38 @@ export default function DiffPanel({
539 });
540
541 const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
508 - const renderableFileEntries = useMemo(
509 - () => renderableFiles.map(getCachedFileEntry),
510 - [renderableFiles],
511 - );
512 - const defaultCollapsedDiffFileKeys = useMemo(
513 - () =>
514 - settings.diffFilesCollapsed
515 - ? new Set(renderableFileEntries.map((file) => file.fileKey))
516 - : EMPTY_COLLAPSED_DIFF_FILE_KEYS,
517 - [renderableFileEntries, settings.diffFilesCollapsed],
542 + const { renderableFileEntries, diffFileKeys, defaultCollapsedDiffFileKeys } = useDiffFileEntries(
543 + renderableFiles,
544 + settings.diffFilesCollapsed,
545 );
546 const collapsedDiffFileKeys =
547 collapsedDiffFiles.scopeKey === collapseScopeKey
548 ? collapsedDiffFiles.fileKeys
549 : defaultCollapsedDiffFileKeys;
523 - const renderLoadingBoundary = useCallback(
524 - () =>
525 - settledFileCount < renderableFiles.length ? (
526 - <DiffFileLoadingBoundary
527 - load={loadNextFiles}
528 - count={renderableFiles.length - settledFileCount}
529 - />
530 - ) : null,
531 - [settledFileCount, renderableFiles.length, loadNextFiles],
532 - );
533 - const codeViewFiles = useMemo(
534 - () =>
535 - renderableFileEntries
536 - .filter(({ fileDiff }) => !lazySource || readyFilePaths.has(resolveFileDiffPath(fileDiff)))
537 - .map(({ fileDiff, fileKey, fileVersion }) => {
538 - return {
539 - fileDiff,
540 - filePath: resolveFileDiffPath(fileDiff),
541 - fileKey,
542 - fileVersion,
543 - collapsed:
544 - collapsedDiffFileKeys.has(fileKey) ||
545 - fileDiff.cacheKey?.endsWith(":pending") === true,
546 - };
547 - }),
548 - [collapsedDiffFileKeys, renderableFileEntries, lazySource, readyFilePaths],
549 - );
550 - const diffFileKeys = useMemo(
551 - () => renderableFileEntries.map((file) => file.fileKey),
552 - [renderableFileEntries],
550 + const renderLoadingBoundary = () =>
551 + settledFileCount < renderableFiles.length ? (
552 + <DiffFileLoadingBoundary
553 + load={loadNextFiles}
554 + count={renderableFiles.length - settledFileCount}
555 + />
556 + ) : null;
557 + const codeViewFiles = useCodeViewFiles(
558 + renderableFileEntries,
559 + lazySource ? readyFilePaths : null,
560 + collapsedDiffFileKeys,
561 );
562 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
555 - const diffLineStat = useMemo(() => {
556 - if (!selectedTurn && selectedGitSource?.files) {
557 - return selectedGitSource.files.reduce(
558 - (total, file) => ({
559 - additions: total.additions + file.additions,
560 - deletions: total.deletions + file.deletions,
561 - }),
562 - { additions: 0, deletions: 0 },
563 - );
564 - }
565 - return getDiffLineStat(renderableFiles);
566 - }, [renderableFiles, selectedGitSource, selectedTurn]);
567 - const fileTreeEntries = useMemo(() => diffFileTreeEntries(renderableFiles), [renderableFiles]);
563 + const diffLineStat =
564 + !selectedTurn && selectedGitSource?.files
565 + ? selectedGitSource.files.reduce(
566 + (total, file) => ({
567 + additions: total.additions + file.additions,
568 + deletions: total.deletions + file.deletions,
569 + }),
570 + { additions: 0, deletions: 0 },
571 + )
572 + : getDiffLineStat(renderableFiles);
573 + const fileTreeEntries = diffFileTreeEntries(renderableFiles);
574 const selectedDiffFileKey = selectedFilePath
575 ? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
576 : null;
@@ -572,46 +578,33 @@ export default function DiffPanel({
578 useEffect(() => {
579 if (!selectedDiffFileKey || !codeView?.getInstance()) return;
580 codeView.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
581 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A remounted viewer or a repeated reveal request scrolls to the same file again.
582 }, [codeView, codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
583
577 - const treeRevealScope = useMemo(
578 - () => ({ collapseScopeKey, diffSelection }),
579 - [collapseScopeKey, diffSelection],
580 - );
584 + const treeRevealScope = { collapseScopeKey, diffSelection };
585 const requestTreeReveal = useCodeViewFileReveal(
586 codeView,
587 treeRevealScope,
588 codeViewFiles.map((file) => file.fileKey),
589 );
586 - const revealDiffFile = useCallback(
587 - (filePath: string) => {
588 - const index = renderableFileEntries.findIndex(
589 - (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
590 + const revealDiffFile = (filePath: string) => {
591 + const index = renderableFileEntries.findIndex(
592 + (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
593 + );
594 + const file = renderableFileEntries[index];
595 + if (!file) return;
596 + setCollapsedDiffFiles((current) => {
597 + const next = new Set(
598 + current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys,
599 );
591 - const file = renderableFileEntries[index];
592 - if (!file) return;
593 - setCollapsedDiffFiles((current) => {
594 - const next = new Set(
595 - current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys,
596 - );
597 - next.delete(file.fileKey);
598 - return { scopeKey: collapseScopeKey, fileKeys: next };
599 - });
600 - if (lazySource && index >= settledFileCount) {
601 - requestFile(index);
602 - }
603 - requestTreeReveal(file.fileKey);
604 - },
605 - [
606 - renderableFileEntries,
607 - collapseScopeKey,
608 - defaultCollapsedDiffFileKeys,
609 - requestTreeReveal,
610 - lazySource,
611 - settledFileCount,
612 - requestFile,
613 - ],
614 - );
600 + next.delete(file.fileKey);
601 + return { scopeKey: collapseScopeKey, fileKeys: next };
602 + });
603 + if (lazySource && index >= settledFileCount) {
604 + requestFile(index);
605 + }
606 + requestTreeReveal(file.fileKey);
607 + };
608
609 const externalRevealRef = useRef<{ cache: string; key: string } | null>(null);
610 useEffect(() => {
@@ -626,40 +619,33 @@ export default function DiffPanel({
619 revealDiffFile(selectedFilePath);
620 }, [lazySource, selectedFilePath, selectedFileRevealRequestId, filePatchScope, revealDiffFile]);
621
629 - const openDiffFile = useCallback(
630 - (filePath: string) => {
631 - openDiffFilePrimaryAction({
632 - threadRef: routeThreadRef,
633 - filePath,
634 - activeCwd,
635 - repositoryRoot: activeRepositoryRoot,
636 - openInEditor: (targetPath) => {
637 - void (async () => {
638 - const result = await openInPreferredEditor(targetPath);
639 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
640 - console.warn("Failed to open diff file in editor.", {
641 - operation: "open-diff-file",
642 - ...(routeThreadRef
643 - ? {
644 - environmentId: routeThreadRef.environmentId,
645 - threadId: routeThreadRef.threadId,
646 - }
647 - : {}),
648 - ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
649 - });
650 - }
651 - })();
652 - },
653 - });
654 - },
655 - [activeCwd, activeRepositoryRoot, openInPreferredEditor, routeThreadRef],
656 - );
657 - const collapseDefaultsRef = useRef({ collapseScopeKey, defaultCollapsedDiffFileKeys });
658 - useLayoutEffect(() => {
659 - collapseDefaultsRef.current = { collapseScopeKey, defaultCollapsedDiffFileKeys };
660 - }, [collapseScopeKey, defaultCollapsedDiffFileKeys]);
661 - const toggleDiffFileCollapsed = useCallback((fileKey: string) => {
662 - const { collapseScopeKey, defaultCollapsedDiffFileKeys } = collapseDefaultsRef.current;
622 + const openDiffFile = (filePath: string) => {
623 + openDiffFilePrimaryAction({
624 + threadRef: routeThreadRef,
625 + filePath,
626 + activeCwd,
627 + repositoryRoot: activeRepositoryRoot,
628 + openInEditor: (targetPath) => {
629 + void (async () => {
630 + const result = await openInPreferredEditor(targetPath);
631 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
632 + console.warn("Failed to open diff file in editor.", {
633 + operation: "open-diff-file",
634 + ...(routeThreadRef
635 + ? {
636 + environmentId: routeThreadRef.environmentId,
637 + threadId: routeThreadRef.threadId,
638 + }
639 + : {}),
640 + ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
641 + });
642 + }
643 + })();
644 + },
645 + });
646 + };
647 + // Every file header holds these; a new identity per collapse change would redraw them all.
648 + const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => {
649 setCollapsedDiffFiles((current) => {
650 const next = new Set(
651 current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys,
@@ -671,10 +657,9 @@ export default function DiffPanel({
657 }
658 return { scopeKey: collapseScopeKey, fileKeys: next };
659 });
674 - }, []);
660 + });
661 // Find can ask again before the unfolded file reaches the viewer, so this must never fold.
676 - const unfoldDiffFile = useCallback((fileKey: string) => {
677 - const { collapseScopeKey, defaultCollapsedDiffFileKeys } = collapseDefaultsRef.current;
662 + const unfoldDiffFile = useStableCallback((fileKey: string) => {
663 setCollapsedDiffFiles((current) => {
664 const fileKeys =
665 current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys;
@@ -683,9 +668,9 @@ export default function DiffPanel({
668 next.delete(fileKey);
669 return { scopeKey: collapseScopeKey, fileKeys: next };
670 });
686 - }, []);
671 + });
672
688 - const toggleDiffFileCollapse = useCallback(() => {
673 + const toggleDiffFileCollapse = () => {
674 setCodeViewRevision((current) => current + 1);
675 setCollapsedDiffFiles((current) => {
676 const currentKeys =
@@ -696,7 +681,7 @@ export default function DiffPanel({
681 fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
682 };
683 });
699 - }, [collapseScopeKey, defaultCollapsedDiffFileKeys, diffFileKeys]);
684 + };
685
686 const selectTurn = (runId: RunId) => {
687 if (!routeThreadRef) return;