Skip to content

Commit 3418a0e

Browse files
refactor(web): diff and file reveals are requests, and workspace edits refetch by construction
Workspace edits refreshed the diff panel, file previews and media URLs through effects that compared a mutation id against a ref and then called refresh(). The diff panel also ran its own open-revalidation and window-focus effects, the review file patches compared preview revisions in an effect, and code-view reveals were state plus an effect that waited for the viewer. - DiffPanel reads the branch diff preview under the workspace mutation id (revisionedQuery) and revalidates on show/focus through useLiveRefresh (now with refreshOnShow and no interval for a costly read). - useReviewFilePatches hands the preview input to the patch query, whose refreshTrigger already refreshes patches when the preview revision moves. - FilePreviewPanel mounts the file read under the mutation id and passes the mutation id to useAssetUrlState for video, audio and file previews. - Code-view reveals are a small request object: applied at once when the viewer holds the file, otherwise flushed from the viewer's post-render. - The PR code tab's load-more sentinel observes through a ref callback. - Pull request files-viewed presses live in a store keyed by scope instead of two effects and five refs in the hook. Effects kept: DiffPanel's turn reconcile and external reveal, the PR code tab's reveal answer (now a layout effect so it can position after the viewer attaches), and FilePreviewPanel's breadcrumb scroll, editor dismissal and highlight priming. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 71ba6b3 commit 3418a0e

11 files changed

Lines changed: 810 additions & 288 deletions

‎apps/web/src/components/DiffPanel.tsx‎

Lines changed: 52 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,15 @@ import {
1919
} from "lucide-react";
2020
import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
2121
import * as Schema from "effect/Schema";
22-
import * as DateTime from "effect/DateTime";
2322
import { useEffect, useRef, useState } from "react";
24-
import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
23+
import { createCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
2524
import { useFilesystemReadAccess } from "~/state/filesystem";
2625
import { useOpenInPreferredEditor } from "../editorPreferences";
2726
import { useFileContextMenuHandler } from "../fileContextMenu";
2827
import { type DraftId } from "../composerDraftStore";
2928
import { openDiffFilePrimaryAction } from "../diffFileActions";
3029
import { useCheckpointDiff } from "~/lib/checkpointDiffState";
30+
import { revisionedQuery } from "~/state/revisionedQuery";
3131
import { cn } from "~/lib/utils";
3232
import {
3333
selectThreadDiffPanelSelection,
@@ -48,7 +48,7 @@ import {
4848
} from "../lib/diffRendering";
4949
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
5050
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
51-
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
51+
import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";
5252
import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";
5353
import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
5454
import { formatShortTimestamp } from "../timestampFormat";
@@ -322,20 +322,29 @@ export default function DiffPanel({
322322
},
323323
{ enabled: isGitRepo && selectedTurn !== undefined },
324324
);
325-
const branchDiffPreview = useEnvironmentQuery(
325+
const branchDiffPreviewInput =
326326
canReadFiles && selectedRunId === null && activeThread && activeCwd
327-
? reviewEnvironment.diffPreview({
328-
environmentId: activeThread.environmentId,
329-
input: {
330-
cwd: activeCwd,
331-
...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
332-
ignoreWhitespace: diffIgnoreWhitespace,
333-
},
334-
})
335-
: null,
336-
);
327+
? {
328+
cwd: activeCwd,
329+
...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
330+
ignoreWhitespace: diffIgnoreWhitespace,
331+
}
332+
: undefined;
337333
const canRefreshGitDiff =
338334
isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null;
335+
// Read under the workspace mutation id, so each mutation refetches the diff; the panel stays
336+
// mounted while hidden, so a mutation made then is already reflected when it shows.
337+
const branchDiffPreview = useEnvironmentQuery(
338+
branchDiffPreviewInput && activeThread
339+
? revisionedQuery(
340+
reviewEnvironment.diffPreview({
341+
environmentId: activeThread.environmentId,
342+
input: branchDiffPreviewInput,
343+
}),
344+
canRefreshGitDiff ? workspaceMutationId : undefined,
345+
)
346+
: null,
347+
);
339348
const activeThreadRefreshKey = routeThreadRef
340349
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
341350
: null;
@@ -458,51 +467,30 @@ export default function DiffPanel({
458467
baseRef: lazySource?.baseRef ?? selectedBaseRef,
459468
ignoreWhitespace: diffIgnoreWhitespace,
460469
theme: resolvedTheme,
461-
revision: branchDiffPreview.data
462-
? DateTime.formatIso(branchDiffPreview.data.generatedAt)
463-
: undefined,
470+
previewInput: branchDiffPreviewInput,
464471
preview: renderablePatch,
465472
});
466473
const refreshBranchDiffPreview = refreshPreviewQuery;
467-
const previewOpenHandledRef = useRef(false);
468-
const refreshDiffForWorkspaceMutation = useStableCallback(() => {
469-
previewOpenHandledRef.current = true;
470-
refreshBranchDiffPreview();
471-
});
472-
473-
// A mutation refresh also satisfies revalidation for the current opening.
474-
useWorkspaceMutationRefresh({
475-
enabled: canRefreshGitDiff,
476-
mutationId: workspaceMutationId,
477-
refresh: refreshDiffForWorkspaceMutation,
478-
resourceKey: `diff:${activeThreadRefreshKey ?? ""}`,
479-
});
480-
481-
useEffect(() => {
482-
if (!visible || !canReadFiles || !canRefreshGitDiff) {
483-
previewOpenHandledRef.current = false;
484-
return;
485-
}
486-
if (previewOpenHandledRef.current) return;
487-
previewOpenHandledRef.current = true;
488-
if (branchDiffPreview.data !== null && !branchDiffPreview.isPending) {
489-
refreshBranchDiffPreview();
490-
}
491-
}, [
492-
branchDiffPreview.data,
493-
branchDiffPreview.isPending,
494-
canReadFiles,
495-
canRefreshGitDiff,
496-
refreshBranchDiffPreview,
497-
visible,
498-
]);
474+
const diffRefreshKey = `diff:${activeThreadRefreshKey ?? ""}`;
499475

500-
useEffect(() => {
501-
if (!canRefreshGitDiff) return;
502-
const refreshOnFocus = () => refreshBranchDiffPreview();
503-
window.addEventListener("focus", refreshOnFocus);
504-
return () => window.removeEventListener("focus", refreshOnFocus);
505-
}, [canRefreshGitDiff, refreshBranchDiffPreview]);
476+
// The panel stays mounted while hidden, and edits made outside T3 Code bump no mutation id, so
477+
// showing it revalidates the diff; that also stands in for focus events missed while hidden.
478+
// A git diff is too costly to repeat on a timer nobody asked for. A diff read within the floor,
479+
// such as a mutation's refetch while hidden, already counts as that revalidation.
480+
useLiveRefresh(
481+
branchDiffPreview.data !== null && !branchDiffPreview.isPending
482+
? () => {
483+
if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return;
484+
refreshBranchDiffPreview();
485+
}
486+
: null,
487+
{
488+
enabled: visible && canReadFiles && canRefreshGitDiff,
489+
key: diffRefreshKey,
490+
intervalMs: null,
491+
refreshOnShow: true,
492+
},
493+
);
506494

507495
const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
508496
const renderableFileEntries = renderableFiles.map(getCachedFileEntry);
@@ -542,13 +530,12 @@ export default function DiffPanel({
542530
collapsed:
543531
collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
544532
}));
545-
const codeViewFileKeys = codeViewFiles.map((file) => file.fileKey);
546533
const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));
547534
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
548535
const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
549536
const fileTreeEntries = diffFileTreeEntries(renderableFiles);
550-
const treeRevealScope = { collapseScopeKey, diffSelection };
551-
const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope, codeViewFileKeys);
537+
const [codeViewReveal] = useState(createCodeViewFileReveal);
538+
const requestTreeReveal = (fileKey: string) => codeViewReveal.request(codeView, fileKey);
552539
const revealDiffFile = (filePath: string) => {
553540
const index = renderableFileEntries.findIndex(
554541
(candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
@@ -567,6 +554,12 @@ export default function DiffPanel({
567554
return true;
568555
};
569556

557+
// The code view keeps the post-render handler it was given; a file it did not hold yet when
558+
// asked is positioned once it renders it.
559+
const flushCodeViewReveal = useStableCallback(() => codeViewReveal.flush(codeView));
560+
561+
// A file another view asked to reveal (a chat diff link): retried as the diff loads until it
562+
// holds the file, then not again until a new request, so it does not undo what the user did since.
570563
const externalRevealRef = useRef<string | null>(null);
571564
useEffect(() => {
572565
if (!selectedFilePath) {
@@ -1152,6 +1145,7 @@ export default function DiffPanel({
11521145
preferredHighlighter: PREFERRED_HIGHLIGHTER,
11531146
themeType: resolvedTheme as DiffThemeType,
11541147
stickyHeaders: true,
1148+
onPostRender: flushCodeViewReveal,
11551149
...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
11561150
}}
11571151
/>
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import type { CodeViewScrollTarget } from "@pierre/diffs";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { createCodeViewFileReveal } from "./useCodeViewFileReveal";
5+
6+
function viewer(initialItems: ReadonlyArray<string>) {
7+
const items = new Set(initialItems);
8+
const scrolls: CodeViewScrollTarget[] = [];
9+
return {
10+
items,
11+
scrolls,
12+
getInstance: () => ({}),
13+
getItem: (id: string) => (items.has(id) ? {} : undefined),
14+
scrollTo: (target: CodeViewScrollTarget) => scrolls.push(target),
15+
};
16+
}
17+
18+
describe("createCodeViewFileReveal", () => {
19+
it("scrolls at once to a file the viewer holds", () => {
20+
const reveal = createCodeViewFileReveal();
21+
const view = viewer(["a"]);
22+
23+
reveal.request(view, "a");
24+
25+
expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
26+
});
27+
28+
it("keeps a missing file pending until a flush finds it, then drops it", () => {
29+
const reveal = createCodeViewFileReveal();
30+
const view = viewer([]);
31+
32+
reveal.request(view, "a");
33+
reveal.flush(view);
34+
expect(view.scrolls).toEqual([]);
35+
36+
view.items.add("a");
37+
reveal.flush(view);
38+
reveal.flush(view);
39+
expect(view.scrolls).toHaveLength(1);
40+
});
41+
42+
it("drops a pending reveal when another viewer replaces the one it was asked of", () => {
43+
const reveal = createCodeViewFileReveal();
44+
const first = viewer([]);
45+
const second = viewer(["a"]);
46+
47+
reveal.request(first, "a");
48+
reveal.flush(second);
49+
50+
expect(second.scrolls).toEqual([]);
51+
});
52+
});
Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,40 @@
11
import type { CodeViewScrollTarget } from "@pierre/diffs";
2-
import { useEffect, useRef, useState } from "react";
2+
import { useState } from "react";
33

44
interface FileRevealHandle {
55
getInstance(): object | undefined;
6+
getItem(id: string): object | undefined;
67
scrollTo(target: CodeViewScrollTarget): void;
78
}
89

9-
export function useCodeViewFileReveal<TScope>(
10-
viewer: FileRevealHandle | null,
11-
scope: TScope,
12-
readyFileKeys?: ReadonlyArray<string>,
13-
) {
14-
const [request, setRequest] = useState<{ fileKey: string; scope: TScope } | null>(null);
15-
const handledRequest = useRef<typeof request>(null);
16-
17-
useEffect(() => {
18-
if (request === null || handledRequest.current === request) return;
19-
if (request.scope !== scope) {
20-
handledRequest.current = request;
21-
return;
22-
}
23-
if (!viewer?.getInstance() || (readyFileKeys && !readyFileKeys.includes(request.fileKey)))
24-
return;
25-
26-
viewer.scrollTo({ type: "item", id: request.fileKey, align: "start" });
27-
handledRequest.current = request;
28-
}, [request, scope, viewer, readyFileKeys]);
10+
/**
11+
* Scrolls a code view to a file. A file the viewer does not hold yet stays
12+
* pending until `flush` (from the viewer's post-render) finds it. A pending
13+
* reveal belongs to the viewer it was asked of, so a remounted viewer, such as
14+
* one for another diff scope, drops it.
15+
*/
16+
export function createCodeViewFileReveal() {
17+
let pending: { readonly viewer: FileRevealHandle; readonly fileKey: string } | null = null;
18+
const apply = (viewer: FileRevealHandle, fileKey: string) => {
19+
if (!viewer.getInstance() || viewer.getItem(fileKey) === undefined) return false;
20+
viewer.scrollTo({ type: "item", id: fileKey, align: "start" });
21+
return true;
22+
};
23+
return {
24+
/** Whether the viewer was positioned now, rather than left pending or dropped. */
25+
request(viewer: FileRevealHandle | null, fileKey: string): boolean {
26+
const applied = viewer !== null && apply(viewer, fileKey);
27+
pending = viewer === null || applied ? null : { viewer, fileKey };
28+
return applied;
29+
},
30+
flush(viewer: FileRevealHandle | null) {
31+
if (pending === null || pending.viewer !== viewer) return;
32+
if (apply(pending.viewer, pending.fileKey)) pending = null;
33+
},
34+
};
35+
}
2936

30-
return (fileKey: string) => setRequest({ fileKey, scope });
37+
export function useCodeViewFileReveal(viewer: FileRevealHandle | null) {
38+
const [reveal] = useState(createCodeViewFileReveal);
39+
return (fileKey: string) => reveal.request(viewer, fileKey);
3140
}

‎apps/web/src/components/diffs/useReviewFilePatches.ts‎

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
import { RegistryContext, useAtomValue } from "@effect/atom-react";
22
import type { FileDiffMetadata } from "@pierre/diffs";
3-
import type { EnvironmentId, ReviewDiffPreviewSource } from "@t3tools/contracts";
3+
import type {
4+
EnvironmentId,
5+
ReviewDiffPreviewInput,
6+
ReviewDiffPreviewSource,
7+
} from "@t3tools/contracts";
48
import * as AsyncResult from "effect/reactivity/AsyncResult";
59
import * as Atom from "effect/reactivity/Atom";
6-
import { useContext, useEffect, useRef, useState } from "react";
10+
import { useContext, useState } from "react";
711
import { useStableCallback } from "~/hooks/useStableCallback";
812
import { getRenderablePatch, resolveFileDiffPath, type RenderablePatch } from "~/lib/diffRendering";
913
import { reviewEnvironment } from "~/state/review";
@@ -21,7 +25,7 @@ export function useReviewFilePatches({
2125
baseRef,
2226
ignoreWhitespace,
2327
theme,
24-
revision,
28+
previewInput,
2529
preview,
2630
}: {
2731
environmentId: EnvironmentId | undefined;
@@ -30,7 +34,8 @@ export function useReviewFilePatches({
3034
baseRef: string | null;
3135
ignoreWhitespace: boolean;
3236
theme: "light" | "dark";
33-
revision: string | undefined;
37+
/** The preview the file list came from; a newer revision of it refreshes loaded patches. */
38+
previewInput: ReviewDiffPreviewInput | undefined;
3439
preview: RenderablePatch | null;
3540
}) {
3641
const registry = useContext(RegistryContext);
@@ -49,25 +54,13 @@ export function useReviewFilePatches({
4954
source,
5055
baseRef,
5156
ignoreWhitespace,
57+
previewInput,
5258
scope,
5359
requested,
5460
});
5561
const queriedPatchesAtom = reviewPatchesAtom(
5662
JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
5763
);
58-
const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
59-
useEffect(() => {
60-
const previous = previousPreview.current;
61-
previousPreview.current = { scope, revision, queries };
62-
for (const { query } of queries) {
63-
const changed = previous.scope === scope && previous.revision !== revision;
64-
const cached =
65-
!previous.queries.some((entry) => entry.query === query) &&
66-
registry.get(query)._tag !== "Initial" &&
67-
!registry.get(query).waiting;
68-
if (changed || cached) registry.refresh(query);
69-
}
70-
}, [scope, revision, queries, registry]);
7164
const patches = useAtomValue(queriedPatchesAtom);
7265
const retry = useStableCallback((path: string) => {
7366
const files = sortedReviewFiles(source);
@@ -170,6 +163,7 @@ function reviewFileQueries({
170163
source,
171164
baseRef,
172165
ignoreWhitespace,
166+
previewInput,
173167
scope,
174168
requested,
175169
}: {
@@ -178,6 +172,7 @@ function reviewFileQueries({
178172
source: ReviewDiffPreviewSource | null;
179173
baseRef: string | null;
180174
ignoreWhitespace: boolean;
175+
previewInput: ReviewDiffPreviewInput | undefined;
181176
scope: string;
182177
requested: { scope: string; indices: number[] };
183178
}) {
@@ -194,6 +189,7 @@ function reviewFileQueries({
194189
environmentId,
195190
input: {
196191
cacheKey: scope,
192+
...(previewInput ? { preview: previewInput } : {}),
197193
request: {
198194
cwd,
199195
...(baseRef ? { baseRef } : {}),

0 commit comments

Comments
 (0)