@devries-cameron20 / t3code Mirror · read-only / commits / ba9e9f5736
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): the pull request code tab keeps its caching with one "use memo" hook (#20773)

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

Julius Marminge committed Oct 16, 2026 at 23:25 UTC ba9e9f5736364d029866110f0199769a4e721c56
1 file changed +182 -210
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+182 -210
@@ -243,173 +243,19 @@ export interface PullRequestAgentSelectionInput {
243 readonly request: string;
244 }
245
246 -// These hooks call no hooks, so the compiler needs the directive to memoize them. The viewer
247 -// and the viewed-file tracker key on the identity of what they return.
248 -function usePullRequestDiffFileContentsLoader<E>(
249 - getDiffFileContents: Parameters<typeof createPullRequestDiffFileContentsLoader<E>>[0],
250 - source: Parameters<typeof createPullRequestDiffFileContentsLoader<E>>[1],
251 -) {
252 - "use memo";
253 - return createPullRequestDiffFileContentsLoader(getDiffFileContents, source);
254 -}
255 -
256 -function useParsedDiffSlices(
257 - loadedSlices: ReadonlyArray<DiffSlice>,
258 - scopeKey: string,
259 - resolvedTheme: string,
260 - ignoreWhitespace: boolean,
261 -) {
262 - "use memo";
263 - // The cache key carries the theme, which is what the tokenizer caches against, so a theme
264 - // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page
265 - // reuses its cursor, and a key of position alone would hand back the parse it replaced.
266 - const parsedSlices = loadedSlices.map((slice) =>
267 - parseSlice(
268 - slice,
269 - `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`,
270 - ignoreWhitespace,
271 - ),
272 - );
273 - const files = parsedSlices.flatMap((parsed) =>
274 - parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
275 - );
276 - const filePaths = files.map((file) => resolveFileDiffPath(file));
277 - const omittedFileStats = new Map(
278 - loadedSlices.flatMap((slice) =>
279 - slice.omittedFileStats.map((file) => [file.path, file] as const),
280 - ),
281 - );
282 - const sourceFileStats = new Map(
283 - parsedSlices.flatMap((parsed) =>
284 - parsed?.kind === "files"
285 - ? parsed.files.map(
286 - (file, index) =>
287 - [
288 - buildFileDiffRenderKey(file),
289 - getDiffLineStat([parsed.sourceFiles[index] ?? file]),
290 - ] as const,
291 - )
292 - : [],
293 - ),
294 - );
295 - const fileTreeEntries = diffFileTreeEntries(files);
296 - return { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries };
297 -}
298 -
299 -function useAnnotatedDiffFiles(
300 - files: ReadonlyArray<FileDiffMetadata>,
301 - reviewThreads: ReadonlyArray<PullRequestReviewThread>,
302 - pendingComments: ReadonlyArray<PendingReviewComment>,
303 - draft: DraftAnchor | null,
304 - scopedToCommit: boolean,
305 -) {
306 - "use memo";
307 - // Placing a conversation takes more than its file being in the diff: its line has to fall
308 - // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
309 - // off-diff list rather than disappearing between the two.
310 - const placedThreadIds = (() => {
311 - const placed = new Set<string>();
312 - // A commit's diff counts lines within that commit; a review comment is anchored to the
313 - // pull request's head diff. Pinning one onto the other would put the remark against
314 - // whichever code happens to hold that line number in this commit, so while a commit is on
315 - // screen every conversation is listed rather than placed.
316 - if (scopedToCommit) return placed;
317 - for (const file of files) {
318 - const path = resolveFileDiffPath(file);
319 - for (const thread of reviewThreads) {
320 - if (
321 - thread.path === path &&
322 - thread.line !== null &&
323 - isLineInFileDiff(file, thread.side, thread.line)
324 - ) {
325 - placed.add(thread.id);
326 - }
327 - }
328 - }
329 - return placed;
330 - })();
331 -
332 - const annotatedFiles = files.map((fileDiff) => {
333 - const fileKey = buildFileDiffRenderKey(fileDiff);
334 - const path = resolveFileDiffPath(fileDiff);
335 - const groups = new Map<string, MutableAnnotationGroup>();
336 - const groupAt = (side: PullRequestDiffSide, line: number) => {
337 - const key = `${side}:${line}`;
338 - const existing = groups.get(key);
339 - if (existing) return existing;
340 - const created: MutableAnnotationGroup = {
341 - side,
342 - line,
343 - threads: [],
344 - pending: [],
345 - draft: false,
346 - };
347 - groups.set(key, created);
348 - return created;
349 - };
350 -
351 - for (const thread of reviewThreads) {
352 - if (thread.path !== path || thread.line === null) continue;
353 - if (!placedThreadIds.has(thread.id)) continue;
354 - groupAt(thread.side, thread.line).threads.push(thread);
355 - }
356 - if (!scopedToCommit) {
357 - for (const comment of pendingComments) {
358 - if (comment.path !== path) continue;
359 - const anchor = getReviewPositionAnchor(comment.position);
360 - groupAt(anchor.side, anchor.line).pending.push(comment);
361 - }
362 - }
363 - if (draft?.fileKey === fileKey) {
364 - const anchor = getReviewPositionAnchor(draft.position);
365 - groupAt(anchor.side, anchor.line).draft = true;
366 - }
367 -
368 - const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
369 - side: toViewerSide(group.side),
370 - lineNumber: group.line,
371 - metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
372 - }));
373 - return {
374 - fileKey,
375 - path,
376 - fileDiff,
377 - annotations,
378 - // The viewer re-renders an item only when its version changes, so everything the
379 - // annotations show has to be part of it.
380 - annotationsVersion: fnv1a32(
381 - annotations
382 - .map(
383 - ({ side, lineNumber, metadata }) =>
384 - `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
385 - .map((comment) => `${comment.id}:${comment.body}`)
386 - .join(",")}:${metadata.threads
387 - .map(
388 - (thread) =>
389 - `${thread.id}:${thread.isResolved ? "r" : ""}:${
390 - thread.isOutdated ? "o" : ""
391 - }:${thread.comments
392 - .map(
393 - (comment) =>
394 - `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
395 - comment.reactions ?? []
396 - )
397 - .map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`)
398 - .join(",")}`,
399 - )
400 - .join(";")}`,
401 - )
402 - .join(",")}`,
403 - )
404 - .join("|"),
405 - ),
406 - };
407 - });
408 - return { annotatedFiles, placedThreadIds };
409 -}
410 -
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(
412 - annotatedFiles: ReturnType<typeof useAnnotatedDiffFiles>["annotatedFiles"],
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: {
@@ -605,7 +451,7 @@ function PullRequestCodeTab({
451 reportFailure: false,
452 });
453 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
608 - const loadDiffFiles = usePullRequestDiffFileContentsLoader(getDiffFileContents, {
454 + const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
455 environmentId,
456 reference,
457 commit,
@@ -619,8 +465,173 @@ function PullRequestCodeTab({
465 resolve: hostReview.resolve && detail.viewerPermissions.resolve,
466 };
467 const canCommentOnLines = review.inlineComment && commit === null;
622 - const { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries } =
623 - useParsedDiffSlices(loadedSlices, scopeKey, resolvedTheme, ignoreWhitespace);
468 + // The cache key carries the theme, which is what the tokenizer caches against, so a theme
469 + // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page
470 + // reuses its cursor, and a key of position alone would hand back the parse it replaced.
471 + const parsedSlices = loadedSlices.map((slice) =>
472 + parseSlice(
473 + slice,
474 + `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`,
475 + ignoreWhitespace,
476 + ),
477 + );
478 + const files = parsedSlices.flatMap((parsed) =>
479 + parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
480 + );
481 + const filePaths = files.map((file) => resolveFileDiffPath(file));
482 + const omittedFileStats = new Map(
483 + loadedSlices.flatMap((slice) =>
484 + slice.omittedFileStats.map((file) => [file.path, file] as const),
485 + ),
486 + );
487 + const sourceFileStats = new Map(
488 + parsedSlices.flatMap((parsed) =>
489 + parsed?.kind === "files"
490 + ? parsed.files.map(
491 + (file, index) =>
492 + [
493 + buildFileDiffRenderKey(file),
494 + getDiffLineStat([parsed.sourceFiles[index] ?? file]),
495 + ] as const,
496 + )
497 + : [],
498 + ),
499 + );
500 + const fileTreeEntries = diffFileTreeEntries(files);
501 + // Placing a conversation takes more than its file being in the diff: its line has to fall
502 + // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
503 + // off-diff list rather than disappearing between the two.
504 + const placedThreadIds = (() => {
505 + const placed = new Set<string>();
506 + // A commit's diff counts lines within that commit; a review comment is anchored to the
507 + // pull request's head diff. Pinning one onto the other would put the remark against
508 + // whichever code happens to hold that line number in this commit, so while a commit is on
509 + // screen every conversation is listed rather than placed.
510 + if (commit !== null) return placed;
511 + for (const file of files) {
512 + const path = resolveFileDiffPath(file);
513 + for (const thread of detail.reviewThreads) {
514 + if (
515 + thread.path === path &&
516 + thread.line !== null &&
517 + isLineInFileDiff(file, thread.side, thread.line)
518 + ) {
519 + placed.add(thread.id);
520 + }
521 + }
522 + }
523 + return placed;
524 + })();
525 +
526 + const annotatedFiles = files.map((fileDiff) => {
527 + const fileKey = buildFileDiffRenderKey(fileDiff);
528 + const path = resolveFileDiffPath(fileDiff);
529 + const groups = new Map<string, MutableAnnotationGroup>();
530 + const groupAt = (side: PullRequestDiffSide, line: number) => {
531 + const key = `${side}:${line}`;
532 + const existing = groups.get(key);
533 + if (existing) return existing;
534 + const created: MutableAnnotationGroup = {
535 + side,
536 + line,
537 + threads: [],
538 + pending: [],
539 + draft: false,
540 + };
541 + groups.set(key, created);
542 + return created;
543 + };
544 +
545 + for (const thread of detail.reviewThreads) {
546 + if (thread.path !== path || thread.line === null) continue;
547 + if (!placedThreadIds.has(thread.id)) continue;
548 + groupAt(thread.side, thread.line).threads.push(thread);
549 + }
550 + if (commit === null) {
551 + for (const comment of pendingComments) {
552 + if (comment.path !== path) continue;
553 + const anchor = getReviewPositionAnchor(comment.position);
554 + groupAt(anchor.side, anchor.line).pending.push(comment);
555 + }
556 + }
557 + if (draft?.fileKey === fileKey) {
558 + const anchor = getReviewPositionAnchor(draft.position);
559 + groupAt(anchor.side, anchor.line).draft = true;
560 + }
561 +
562 + const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
563 + side: toViewerSide(group.side),
564 + lineNumber: group.line,
565 + metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
566 + }));
567 + return {
568 + fileKey,
569 + path,
570 + fileDiff,
571 + annotations,
572 + // The viewer re-renders an item only when its version changes, so everything the
573 + // annotations show has to be part of it.
574 + annotationsVersion: fnv1a32(
575 + annotations
576 + .map(
577 + ({ side, lineNumber, metadata }) =>
578 + `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
579 + .map((comment) => `${comment.id}:${comment.body}`)
580 + .join(",")}:${metadata.threads
581 + .map(
582 + (thread) =>
583 + `${thread.id}:${thread.isResolved ? "r" : ""}:${
584 + thread.isOutdated ? "o" : ""
585 + }:${thread.comments
586 + .map(
587 + (comment) =>
588 + `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
589 + comment.reactions ?? []
590 + )
591 + .map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`)
592 + .join(",")}`,
593 + )
594 + .join(";")}`,
595 + )
596 + .join(",")}`,
597 + )
598 + .join("|"),
599 + ),
600 + };
601 + });
602 +
603 + const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
604 + const withheldContent =
605 + loadedSlices.some((slice) => slice.truncated) ||
606 + parsedSlices.some((parsed) => parsed?.kind === "raw");
607 + // Only once the diff is whole: returning here while a cursor is outstanding would take the
608 + // sentinel off screen and end the walk, leaving the rest of the change unasked for.
609 + const rawSlices =
610 + nextCursor === null
611 + ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))
612 + : [];
613 + const rawSlicesView =
614 + files.length === 0 && rawSlices.length > 0 ? (
615 + <div className="space-y-4 px-4 py-5">
616 + {rawSlices.map((slice) => (
617 + <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
618 + <p className="text-xs text-muted-foreground">{slice.reason}</p>
619 + <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
620 + </div>
621 + ))}
622 + </div>
623 + ) : null;
624 + const unstructured =
625 + rawSlices.length === 0 ? null : (
626 + <div className="space-y-4 border-t border-border/60 px-4 py-5">
627 + {rawSlices.map((slice) => (
628 + <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
629 + <p className="text-xs text-muted-foreground">{slice.reason}</p>
630 + <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
631 + </div>
632 + ))}
633 + </div>
634 + );
635 const viewedFilesStore = detail.capabilities.viewedFiles;
636 const filesViewed = usePullRequestFilesViewed({
637 environmentId,
@@ -643,18 +654,6 @@ function PullRequestCodeTab({
654 refreshFirstDiffPage();
655 refreshFilesViewed();
656 }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]);
646 - const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
647 - const withheldContent =
648 - loadedSlices.some((slice) => slice.truncated) ||
649 - parsedSlices.some((parsed) => parsed?.kind === "raw");
650 -
651 - const { annotatedFiles, placedThreadIds } = useAnnotatedDiffFiles(
652 - files,
653 - detail.reviewThreads,
654 - pendingComments,
655 - draft,
656 - commit !== null,
657 - );
657
658 const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed);
659 const fileKeys = items.map((item) => item.id);
@@ -1336,23 +1335,8 @@ function PullRequestCodeTab({
1335 );
1336 }
1337
1339 - // Only once the diff is whole: returning here while a cursor is outstanding would take the
1340 - // sentinel off screen and end the walk, leaving the rest of the change unasked for.
1341 - const rawSlices =
1342 - nextCursor === null
1343 - ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))
1344 - : [];
1345 - if (files.length === 0 && rawSlices.length > 0) {
1346 - return withToolbar(
1347 - <div className="space-y-4 px-4 py-5">
1348 - {rawSlices.map((slice) => (
1349 - <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
1350 - <p className="text-xs text-muted-foreground">{slice.reason}</p>
1351 - <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
1352 - </div>
1353 - ))}
1354 - </div>,
1355 - );
1338 + if (rawSlicesView !== null) {
1339 + return withToolbar(rawSlicesView);
1340 }
1341
1342 if (items.length === 0 && nextCursor === null) {
@@ -1373,18 +1357,6 @@ function PullRequestCodeTab({
1357 else orphanFiles.set(thread.path, [thread]);
1358 }
1359
1376 - const unstructured =
1377 - rawSlices.length === 0 ? null : (
1378 - <div className="space-y-4 border-t border-border/60 px-4 py-5">
1379 - {rawSlices.map((slice) => (
1380 - <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
1381 - <p className="text-xs text-muted-foreground">{slice.reason}</p>
1382 - <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
1383 - </div>
1384 - ))}
1385 - </div>
1386 - );
1387 -
1360 return (
1361 <div className="flex h-full min-h-0 flex-col">
1362 {toolbar}