@devries-cameron20 / t3code-1 / commits / f6a9315d19
Fork 0

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

refactor(web): diff and file reveals are requests, and workspace edits refetch by construction (#25732)

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

Julius Marminge committed Oct 26, 2026 at 20:39 UTC f6a9315d19284422e2f2718e487c16acda4ba24e
16 files changed +979 -317
apps/web/src/components/DiffPanel.tsx
+49 -61
@@ -19,7 +19,6 @@ import {
19 } from "lucide-react";
20 import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
21 import * as Schema from "effect/Schema";
22 -import * as DateTime from "effect/DateTime";
22 import { useEffect, useRef, useState } from "react";
23 import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
24 import { useFilesystemReadAccess } from "~/state/filesystem";
@@ -28,6 +27,7 @@ import { useFileContextMenuHandler } from "../fileContextMenu";
27 import { type DraftId } from "../composerDraftStore";
28 import { openDiffFilePrimaryAction } from "../diffFileActions";
29 import { useCheckpointDiff } from "~/lib/checkpointDiffState";
30 +import { revisionedQuery } from "~/state/revisionedQuery";
31 import { cn } from "~/lib/utils";
32 import {
33 selectThreadDiffPanelSelection,
@@ -48,14 +48,14 @@ import {
48 } from "../lib/diffRendering";
49 import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
50 import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
51 -import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
51 +import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";
52 import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";
53 import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
54 import { formatShortTimestamp } from "../timestampFormat";
55 import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
56 import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
57 import { DiffStatLabel } from "./chat/DiffStatLabel";
58 -import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
58 +import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView";
59 import { DiffFileTree } from "./diffs/DiffFileTree";
60 import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";
61 import { Button } from "./ui/button";
@@ -216,7 +216,6 @@ export default function DiffPanel({
216 );
217 const [baseRefQuery, setBaseRefQuery] = useState("");
218 const [codeViewRevision, setCodeViewRevision] = useState(0);
219 - const [codeView, setCodeView] = useState<AnnotatableCodeViewHandle | null>(null);
219
220 const routeThreadRef = useThreadRouteRef();
221 const activeThreadId = routeThreadRef?.threadId ?? null;
@@ -322,20 +321,29 @@ export default function DiffPanel({
321 },
322 { enabled: isGitRepo && selectedTurn !== undefined },
323 );
325 - const branchDiffPreview = useEnvironmentQuery(
324 + const branchDiffPreviewInput =
325 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 - );
326 + ? {
327 + cwd: activeCwd,
328 + ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
329 + ignoreWhitespace: diffIgnoreWhitespace,
330 + }
331 + : undefined;
332 const canRefreshGitDiff =
333 isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null;
334 + // Read under the workspace mutation id, so each mutation refetches the diff; the panel stays
335 + // mounted while hidden, so a mutation made then is already reflected when it shows.
336 + const branchDiffPreview = useEnvironmentQuery(
337 + branchDiffPreviewInput && activeThread
338 + ? revisionedQuery(
339 + reviewEnvironment.diffPreview({
340 + environmentId: activeThread.environmentId,
341 + input: branchDiffPreviewInput,
342 + }),
343 + canRefreshGitDiff ? workspaceMutationId : undefined,
344 + )
345 + : null,
346 + );
347 const activeThreadRefreshKey = routeThreadRef
348 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
349 : null;
@@ -458,51 +466,30 @@ export default function DiffPanel({
466 baseRef: lazySource?.baseRef ?? selectedBaseRef,
467 ignoreWhitespace: diffIgnoreWhitespace,
468 theme: resolvedTheme,
461 - revision: branchDiffPreview.data
462 - ? DateTime.formatIso(branchDiffPreview.data.generatedAt)
463 - : undefined,
469 + previewInput: branchDiffPreviewInput,
470 preview: renderablePatch,
471 });
472 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 - ]);
473 + const diffRefreshKey = `diff:${activeThreadRefreshKey ?? ""}`;
474
500 - useEffect(() => {
501 - if (!canRefreshGitDiff) return;
502 - const refreshOnFocus = () => refreshBranchDiffPreview();
503 - window.addEventListener("focus", refreshOnFocus);
504 - return () => window.removeEventListener("focus", refreshOnFocus);
505 - }, [canRefreshGitDiff, refreshBranchDiffPreview]);
475 + // The panel stays mounted while hidden, and edits made outside T3 Code bump no mutation id, so
476 + // showing it revalidates the diff; that also stands in for focus events missed while hidden.
477 + // A git diff is too costly to repeat on a timer nobody asked for. A diff read within the floor,
478 + // such as a mutation's refetch while hidden, already counts as that revalidation.
479 + useLiveRefresh(
480 + branchDiffPreview.data !== null && !branchDiffPreview.isPending
481 + ? () => {
482 + if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return;
483 + refreshBranchDiffPreview();
484 + }
485 + : null,
486 + {
487 + enabled: visible && canReadFiles && canRefreshGitDiff,
488 + key: diffRefreshKey,
489 + intervalMs: null,
490 + refreshOnShow: true,
491 + },
492 + );
493
494 const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
495 const renderableFileEntries = renderableFiles.map(getCachedFileEntry);
@@ -542,13 +529,11 @@ export default function DiffPanel({
529 collapsed:
530 collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
531 }));
545 - const codeViewFileKeys = codeViewFiles.map((file) => file.fileKey);
532 const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));
533 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
534 const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
535 const fileTreeEntries = diffFileTreeEntries(renderableFiles);
550 - const treeRevealScope = { collapseScopeKey, diffSelection };
551 - const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope, codeViewFileKeys);
536 + const codeViewReveal = useCodeViewFileReveal();
537 const revealDiffFile = (filePath: string) => {
538 const index = renderableFileEntries.findIndex(
539 (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
@@ -563,10 +548,12 @@ export default function DiffPanel({
548 if (lazySource && index >= settledFileCount) {
549 requestFile(index);
550 }
566 - requestTreeReveal(file.fileKey);
551 + codeViewReveal.request(file.fileKey);
552 return true;
553 };
554
555 + // A file another view asked to reveal (a chat diff link): retried as the diff loads until it
556 + // holds the file, then not again until a new request, so it does not undo what the user did since.
557 const externalRevealRef = useRef<string | null>(null);
558 useEffect(() => {
559 if (!selectedFilePath) {
@@ -1093,7 +1080,7 @@ export default function DiffPanel({
1080 >
1081 <AnnotatableCodeView
1082 key={collapseScopeKey ?? reviewSectionId}
1096 - viewerRef={setCodeView}
1083 + viewerRef={codeViewReveal.attach}
1084 codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1085 className="h-full min-h-0 overflow-auto"
1086 files={codeViewFiles}
@@ -1152,6 +1139,7 @@ export default function DiffPanel({
1139 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1140 themeType: resolvedTheme as DiffThemeType,
1141 stickyHeaders: true,
1142 + onPostRender: codeViewReveal.flush,
1143 ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
1144 }}
1145 />
apps/web/src/components/diffs/useCodeViewFileReveal.test.ts new
+72
@@ -0,0 +1,72 @@
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 + reveal.attach(view);
23 +
24 + reveal.request("a");
25 +
26 + expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
27 + });
28 +
29 + it("keeps a missing file pending until a flush finds it, then drops it", () => {
30 + const reveal = createCodeViewFileReveal();
31 + const view = viewer([]);
32 + reveal.attach(view);
33 +
34 + reveal.request("a");
35 + reveal.flush();
36 + expect(view.scrolls).toEqual([]);
37 +
38 + view.items.add("a");
39 + reveal.flush();
40 + reveal.flush();
41 + expect(view.scrolls).toHaveLength(1);
42 + });
43 +
44 + it("applies a reveal asked before the viewer mounted once it holds the file", () => {
45 + const reveal = createCodeViewFileReveal();
46 + const view = viewer([]);
47 +
48 + reveal.request("a");
49 + reveal.attach(view);
50 + expect(view.scrolls).toEqual([]);
51 +
52 + view.items.add("a");
53 + reveal.flush();
54 + expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
55 + });
56 +
57 + it("drops a pending reveal when its viewer detaches, and positions the next viewer on request", () => {
58 + const reveal = createCodeViewFileReveal();
59 + const first = viewer([]);
60 + const second = viewer(["a"]);
61 + reveal.attach(first);
62 +
63 + reveal.request("a");
64 + reveal.attach(null);
65 + reveal.attach(second);
66 + reveal.flush();
67 + expect(second.scrolls).toEqual([]);
68 +
69 + reveal.request("a");
70 + expect(second.scrolls).toHaveLength(1);
71 + });
72 +});
apps/web/src/components/diffs/useCodeViewFileReveal.ts
+33 -22
@@ -1,31 +1,42 @@
1 import type { CodeViewScrollTarget } from "@pierre/diffs";
2 -import { useEffect, useRef, useState } from "react";
2 +import { useState } from "react";
3
4 interface FileRevealHandle {
5 getInstance(): object | undefined;
6 + getItem(id: string): object | undefined;
7 scrollTo(target: CodeViewScrollTarget): void;
8 }
9
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. `attach` is the viewer's ref and `flush` its post-render
12 + * handler, so a reveal asked before the viewer mounts, or for a file it does not hold yet, is
13 + * positioned once it does. A reveal belongs to the diff it was asked of, so detaching the viewer,
14 + * such as remounting it for another diff scope, drops it.
15 + */
16 +export function createCodeViewFileReveal() {
17 + let viewer: FileRevealHandle | null = null;
18 + let pending: string | null = null;
19 + const flush = () => {
20 + if (pending === null || viewer === null) return;
21 + if (!viewer.getInstance() || viewer.getItem(pending) === undefined) return;
22 + viewer.scrollTo({ type: "item", id: pending, align: "start" });
23 + pending = null;
24 + };
25 + return {
26 + attach(next: FileRevealHandle | null) {
27 + if (viewer !== null && next !== viewer) pending = null;
28 + viewer = next;
29 + flush();
30 + },
31 + request(fileKey: string) {
32 + pending = fileKey;
33 + flush();
34 + },
35 + flush,
36 + };
37 +}
38
30 - return (fileKey: string) => setRequest({ fileKey, scope });
39 +export function useCodeViewFileReveal() {
40 + const [reveal] = useState(createCodeViewFileReveal);
41 + return reveal;
42 }
apps/web/src/components/diffs/useReviewFilePatches.ts
+13 -17
@@ -1,9 +1,13 @@
1 import { RegistryContext, useAtomValue } from "@effect/atom-react";
2 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";
8 import * as AsyncResult from "effect/reactivity/AsyncResult";
9 import * as Atom from "effect/reactivity/Atom";
6 -import { useContext, useEffect, useRef, useState } from "react";
10 +import { useContext, useState } from "react";
11 import { useStableCallback } from "~/hooks/useStableCallback";
12 import { getRenderablePatch, resolveFileDiffPath, type RenderablePatch } from "~/lib/diffRendering";
13 import { reviewEnvironment } from "~/state/review";
@@ -21,7 +25,7 @@ export function useReviewFilePatches({
25 baseRef,
26 ignoreWhitespace,
27 theme,
24 - revision,
28 + previewInput,
29 preview,
30 }: {
31 environmentId: EnvironmentId | undefined;
@@ -30,7 +34,8 @@ export function useReviewFilePatches({
34 baseRef: string | null;
35 ignoreWhitespace: boolean;
36 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;
39 preview: RenderablePatch | null;
40 }) {
41 const registry = useContext(RegistryContext);
@@ -49,25 +54,13 @@ export function useReviewFilePatches({
54 source,
55 baseRef,
56 ignoreWhitespace,
57 + previewInput,
58 scope,
59 requested,
60 });
61 const queriedPatchesAtom = reviewPatchesAtom(
62 JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
63 );
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]);
64 const patches = useAtomValue(queriedPatchesAtom);
65 const retry = useStableCallback((path: string) => {
66 const files = sortedReviewFiles(source);
@@ -170,6 +163,7 @@ function reviewFileQueries({
163 source,
164 baseRef,
165 ignoreWhitespace,
166 + previewInput,
167 scope,
168 requested,
169 }: {
@@ -178,6 +172,7 @@ function reviewFileQueries({
172 source: ReviewDiffPreviewSource | null;
173 baseRef: string | null;
174 ignoreWhitespace: boolean;
175 + previewInput: ReviewDiffPreviewInput | undefined;
176 scope: string;
177 requested: { scope: string; indices: number[] };
178 }) {
@@ -194,6 +189,7 @@ function reviewFileQueries({
189 environmentId,
190 input: {
191 cacheKey: scope,
192 + ...(previewInput ? { preview: previewInput } : {}),
193 request: {
194 cwd,
195 ...(baseRef ? { baseRef } : {}),
apps/web/src/components/files/FilePreviewPanel.tsx
+33 -33
@@ -18,7 +18,8 @@ import {
18 officePreviewKind,
19 binaryPreviewKind,
20 } from "@t3tools/shared/filePreview";
21 -import { useAtomValue } from "@effect/atom-react";
21 +import { useAtomMount, useAtomValue } from "@effect/atom-react";
22 +import { Atom } from "effect/reactivity";
23 import {
24 DEFAULT_TOKENIZE_MAX_LENGTH,
25 VirtualizedFile,
@@ -58,7 +59,6 @@ import { useRemoteOpenState } from "~/remoteOpen";
59 import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
60 import { useTheme } from "~/hooks/useTheme";
61 import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
61 -import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
62 import { resolveDiffThemeName } from "~/lib/diffRendering";
63 import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
64 import { cn } from "~/lib/utils";
@@ -118,13 +118,17 @@ import {
118 workspaceAssetResource,
119 } from "./filePreviewMode";
120 import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
121 +import { revisionedQuery } from "~/state/revisionedQuery";
122 import {
123 getOptimisticProjectFileQueryData,
124 getProjectFileContents,
125 + getProjectFileQueryAtom,
126 setProjectFileQueryData,
127 useProjectFileQuery,
128 } from "./projectFilesQueryState";
129
130 +const NO_FILE_REVISION_ATOM = Atom.make(null);
131 +
132 interface FilePreviewPanelProps {
133 environmentId: EnvironmentId;
134 cwd: string;
@@ -279,15 +283,13 @@ function WorkspaceVideoPreview(props: {
283 workspaceRoot: props.workspaceRoot,
284 absolutePath: props.absolutePath,
285 });
282 - const assetUrl = useAssetUrlState(props.environmentId, resource);
286 + // Each workspace mutation re-mints the URL, so an edited file loads its new bytes.
287 + const assetUrl = useAssetUrlState(
288 + props.environmentId,
289 + resource,
290 + props.workspaceMutationId ?? undefined,
291 + );
292 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
284 - useWorkspaceMutationRefresh({
285 - mutationId: props.workspaceMutationId,
286 - resourceKey: JSON.stringify([props.environmentId, resource]),
287 - refresh: () => {
288 - void refreshAssetUrl().catch(() => undefined);
289 - },
290 - });
293 // Servers that report the file's revision let an unchanged file stay loaded; older ones
294 // only offer the workspace mutation, which changes after every command. The revision also
295 // goes in the URL, since two mints in the same millisecond sign identical URLs.
@@ -337,16 +339,13 @@ function WorkspaceAudioPreview(props: {
339 workspaceRoot: props.workspaceRoot,
340 absolutePath: props.absolutePath,
341 });
340 - const assetUrl = useAssetUrlState(props.environmentId, resource);
342 + const assetUrl = useAssetUrlState(
343 + props.environmentId,
344 + resource,
345 + props.workspaceMutationId ?? undefined,
346 + );
347 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
348 const [failedUrl, setFailedUrl] = useState<string | null>(null);
343 - useWorkspaceMutationRefresh({
344 - mutationId: props.workspaceMutationId,
345 - resourceKey: JSON.stringify([props.environmentId, resource]),
346 - refresh: () => {
347 - void refreshAssetUrl().catch(() => undefined);
348 - },
349 - });
349 const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined;
350 const revision = fileRevision ?? props.workspaceMutationId;
351 const revisionSuffix =
@@ -1157,17 +1156,20 @@ export default function FilePreviewPanel({
1156 ? resolvePathLinkTarget(relativePath, cwd)
1157 : null;
1158 const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
1160 - useWorkspaceMutationRefresh({
1161 - enabled:
1159 + // Mounting the file read under the workspace mutation id refetches it after each mutation.
1160 + useAtomMount(
1161 + canReadFiles &&
1162 attachment === undefined &&
1163 relativePath !== null &&
1164 // Skip mutation reads for media and documents; folders still detect conversion to files.
1165 (isFolder || (!isMedia && !isPdf && !isDocument)) &&
1166 - !selectedFilePending,
1167 - mutationId: workspaceMutationId,
1168 - refresh: file.refresh,
1169 - resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,
1170 - });
1166 + !selectedFilePending
1167 + ? revisionedQuery(
1168 + getProjectFileQueryAtom(environmentId, cwd, relativePath),
1169 + workspaceMutationId,
1170 + )
1171 + : NO_FILE_REVISION_ATOM,
1172 + );
1173
1174 useEffect(() => {
1175 const crumbs = breadcrumbRef.current?.querySelectorAll<HTMLElement>("[data-file-crumb]");
@@ -1578,15 +1580,13 @@ export function WorkspaceLargeTextPreview(props: {
1580 description: cause instanceof Error ? cause.message : "Try again.",
1581 });
1582 };
1581 - const assetUrl = useAssetUrlState(props.environmentId, resource);
1583 + // Each workspace mutation re-mints the URL, so an edited file loads its new bytes.
1584 + const assetUrl = useAssetUrlState(
1585 + props.environmentId,
1586 + resource,
1587 + props.workspaceMutationId ?? undefined,
1588 + );
1589 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
1583 - useWorkspaceMutationRefresh({
1584 - mutationId: props.workspaceMutationId,
1585 - resourceKey: JSON.stringify([props.environmentId, resource]),
1586 - refresh: () => {
1587 - void refreshAssetUrl().catch(() => undefined);
1588 - },
1589 - });
1590 const contentRevision = JSON.stringify([
1591 props.environmentId,
1592 resource,
apps/web/src/components/files/projectFilesQueryState.test.tsx
+5 -1
@@ -161,7 +161,7 @@ describe("project query refresh", () => {
161 }
162 });
163
164 - it("refetches a listing when the workspace mutation changes, not when it is first read", () => {
164 + it("refetches a listing when the workspace mutation changes, not when it is first read", async () => {
165 let fetches = 0;
166 const listing = Atom.make(() => {
167 fetches += 1;
@@ -178,6 +178,10 @@ describe("project query refresh", () => {
178 read("mutation-1");
179 expect(fetches).toBe(1);
180
181 + read("mutation-2");
182 + // The refetch runs after the render that read the new revision; a reader that is not
183 + // subscribed sees it on its next read.
184 + await Promise.resolve();
185 read("mutation-2");
186 expect(fetches).toBe(2);
187 } finally {
apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx
+86 -13
@@ -9,27 +9,49 @@ import { expect, it, vi } from "vite-plus/test";
9
10 import "~/index.css";
11
12 -const { diffAtom } = await vi.hoisted(async () => {
12 +const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
13 const { AsyncResult, Atom } = await import("effect/reactivity");
14 - const firstPage: PullRequestDiffResult = {
15 - patch: [
16 - "diff --git a/a.ts b/a.ts",
14 + const filePatch = (path: string) =>
15 + [
16 + `diff --git a/${path} b/${path}`,
17 "index 1111111..2222222 100644",
18 - "--- a/a.ts",
19 - "+++ b/a.ts",
20 - "@@ -1 +1 @@",
18 + `--- a/${path}`,
19 + `+++ b/${path}`,
20 + "@@ -1,6 +1,6 @@",
21 "-before()",
22 "+after()",
23 + " one()",
24 + " two()",
25 + " three()",
26 + " four()",
27 + " five()",
28 "",
24 - ].join("\n"),
29 + ].join("\n");
30 + const firstPage: PullRequestDiffResult = {
31 + patch: filePatch("a.ts"),
32 truncated: false,
33 nextCursor: null,
34 };
28 - // An environment query whose refetch returns equal content hands back the previous value
29 - // itself, so a refresh publishes a new result around the very same page.
30 - return { diffAtom: Atom.make(() => AsyncResult.success(firstPage)) };
35 + const pages: Record<string, PullRequestDiffResult> = {
36 + first: {
37 + patch: Array.from({ length: 40 }, (_, index) => filePatch(`early-${index}.ts`)).join(""),
38 + truncated: true,
39 + nextCursor: "page-2",
40 + },
41 + "page-2": { patch: filePatch("late.ts"), truncated: false, nextCursor: null },
42 + };
43 + return {
44 + // An environment query whose refetch returns equal content hands back the previous value
45 + // itself, so a refresh publishes a new result around the very same page.
46 + diffAtom: Atom.make(() => AsyncResult.success(firstPage)),
47 + pagedDiffAtom: Atom.family((cursor: string) =>
48 + Atom.make(() => AsyncResult.success(pages[cursor]!)),
49 + ),
50 + };
51 });
52
53 +const mocks = vi.hoisted(() => ({ paged: false }));
54 +
55 vi.mock(import("~/state/use-atom-command"), async (original) => ({
56 ...(await original()),
57 useAtomCommand: (() => vi.fn()) as never,
@@ -40,7 +62,8 @@ vi.mock(import("~/state/pullRequests"), async (original) => {
62 ...actual,
63 pullRequestEnvironment: {
64 ...actual.pullRequestEnvironment,
43 - diff: (() => diffAtom) as never,
65 + diff: (({ input }: { input: { cursor?: string } }) =>
66 + mocks.paged ? pagedDiffAtom(input.cursor ?? "first") : diffAtom) as never,
67 },
68 };
69 });
@@ -100,7 +123,14 @@ const detail: PullRequestDetailView = {
123 },
124 };
125
103 -const tab = (refreshToken: number) => (
126 +function setup({ paged }: { paged: boolean }) {
127 + mocks.paged = paged;
128 +}
129 +
130 +const tab = (
131 + refreshToken: number,
132 + revealRequest: { readonly path: string; readonly nonce: number } | null = null,
133 +) => (
134 <PullRequestCodeTab
135 scrollerRef={() => {}}
136 environmentId={EnvironmentId.make("environment")}
@@ -110,10 +140,12 @@ const tab = (refreshToken: number) => (
140 onSelectedCommitChange={() => {}}
141 onRefresh={() => {}}
142 refreshToken={refreshToken}
143 + revealRequest={revealRequest}
144 />
145 );
146
147 it("keeps the diff after a refresh that brings back the same page", async () => {
148 + setup({ paged: false });
149 const container = document.createElement("div");
150 container.className = "flex h-[700px] w-[900px]";
151 await using screen = await render(tab(0), { container });
@@ -126,3 +158,44 @@ it("keeps the diff after a refresh that brings back the same page", async () =>
158 .not.toBeInTheDocument();
159 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
160 });
161 +
162 +function pagedContainer() {
163 + const container = document.createElement("div");
164 + container.className = "flex h-[500px] w-[900px]";
165 + return container;
166 +}
167 +
168 +// Rows are virtualized, so a header far down is not rendered until the view scrolls to it.
169 +async function expectFileHeaderShown(
170 + screen: Awaited<ReturnType<typeof render>>,
171 + container: HTMLElement,
172 + path: string,
173 +) {
174 + const header = screen.getByText(path, { exact: true }).first();
175 + await expect.element(header).toBeInTheDocument();
176 + await vi.waitFor(() => {
177 + const top = header.element().getBoundingClientRect().top;
178 + const bounds = container.getBoundingClientRect();
179 + expect(top).toBeGreaterThanOrEqual(bounds.top);
180 + expect(top).toBeLessThan(bounds.top + bounds.height / 2);
181 + });
182 +}
183 +
184 +it("scrolls to a file asked for as the tab opens", async () => {
185 + setup({ paged: true });
186 + const container = pagedContainer();
187 + await using screen = await render(tab(0, { path: "early-39.ts", nonce: 1 }), { container });
188 +
189 + await expectFileHeaderShown(screen, container, "early-39.ts");
190 +});
191 +
192 +it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
193 + setup({ paged: true });
194 + const container = pagedContainer();
195 + await using screen = await render(tab(0), { container });
196 + await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();
197 +
198 + await screen.rerender(tab(0, { path: "late.ts", nonce: 1 }));
199 +
200 + await expectFileHeaderShown(screen, container, "late.ts");
201 +});
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+28 -26
@@ -3,7 +3,7 @@ import {
3 sourceControlClients,
4 } from "@t3tools/client-runtime/source-control-clients";
5 import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
6 -import type { CodeViewAnnotationArgs, CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
6 +import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react";
7 import type {
8 EnvironmentId,
9 PullRequestDetailView,
@@ -41,6 +41,7 @@ import {
41 type ReactNode,
42 } from "react";
43
44 +import { observeIntersection } from "~/lib/observeIntersection";
45 import { useLocalStorage } from "~/hooks/useLocalStorage";
46 import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
47 import { useRenderedAppearance } from "~/hooks/useTheme";
@@ -311,9 +312,6 @@ function PullRequestCodeTab({
312 readonly cursor: string | null;
313 readonly slices: ReadonlyArray<DiffSlice>;
314 }>({ key: "", cursor: null, slices: NO_SLICES });
314 - const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup, undefined> | null>(
315 - null,
316 - );
315
316 const referenceKey = pullRequestReviewKey(reference);
317 const commit = selectedCommitOid;
@@ -452,10 +450,8 @@ function PullRequestCodeTab({
450 refreshFilesViewed();
451 }, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]);
452
455 - // The viewer mounts its footer later; state ensures the observer sees the sentinel.
456 - const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
457 - const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
458 - const answeredReveal = useRef<number | null>(null);
453 + const codeViewReveal = useCodeViewFileReveal();
454 + const answeredRevealNonce = useRef<number | null>(null);
455
456 const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {
457 environmentId,
@@ -667,6 +663,16 @@ function PullRequestCodeTab({
663 if (nextCursor === null) return;
664 setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
665 };
666 + const sentinelRef = (node: HTMLDivElement | null) => {
667 + if (node === null || !canLoadNextSlice) return;
668 + return observeIntersection(
669 + node,
670 + (entry) => {
671 + if (entry.isIntersecting) loadNextSlice();
672 + },
673 + { rootMargin: "240px" },
674 + );
675 + };
676
677 const toggleFile = (fileKey: string) =>
678 setToggledFiles((current) => {
@@ -692,8 +698,13 @@ function PullRequestCodeTab({
698 const revealFile = (path: string) => {
699 const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
700 if (item === undefined) return;
695 - if (item.collapsed === true) toggleFile(item.id);
696 - requestTreeReveal(item.id);
701 + // Unfold only: a second reveal before the unfold renders must not fold the file again.
702 + if (item.collapsed === true) {
703 + setToggledFiles((current) =>
704 + toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
705 + );
706 + }
707 + codeViewReveal.request(item.id);
708 };
709
710 const toggleAllFiles = () => {
@@ -762,7 +773,7 @@ function PullRequestCodeTab({
773 const renderCodeViewFooter = () =>
774 nextCursor === null ? null : (
775 <div
765 - ref={setSentinel}
776 + ref={sentinelRef}
777 className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
778 >
779 {diffQuery.error !== null ? (
@@ -833,6 +844,7 @@ function PullRequestCodeTab({
844 enableLineSelection: canSelectLines && draft === null,
845 onGutterUtilityClick: beginComment,
846 onLineSelectionEnd: beginComment,
847 + onPostRender: codeViewReveal.flush,
848 };
849
850 const runThreadCommand = async (
@@ -1269,25 +1281,15 @@ function PullRequestCodeTab({
1281 </div>
1282 </div>
1283 );
1272 - // Hooks between diff derivations and their readers break compiler caching.
1273 - useEffect(() => {
1274 - if (sentinel === null || !canLoadNextSlice) return;
1275 - const observer = new IntersectionObserver(
1276 - (observed) => {
1277 - if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
1278 - },
1279 - { rootMargin: "240px" },
1280 - );
1281 - observer.observe(sentinel);
1282 - return () => observer.disconnect();
1283 - }, [canLoadNextSlice, loadNextSlice, sentinel]);
1284 + // A file not loaded yet pages forward each time a slice arrives; once loaded, the viewer
1285 + // positions it when it renders it.
1286 const answerReveal = useEffectEvent(() => {
1285 - if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
1287 + if (revealRequest === null || answeredRevealNonce.current === revealRequest.nonce) return;
1288 if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
1289 if (canLoadNextSlice) loadNextSlice();
1290 return;
1291 }
1290 - answeredReveal.current = revealRequest.nonce;
1292 + answeredRevealNonce.current = revealRequest.nonce;
1293 revealFile(revealRequest.path);
1294 });
1295 useEffect(() => {
@@ -1430,7 +1432,7 @@ function PullRequestCodeTab({
1432 <StyledDiffCodeView<ReviewAnnotationGroup>
1433 className="@container h-full overflow-auto [scrollbar-gutter:stable]"
1434 containerRef={scrollerRef}
1433 - viewerRef={setViewer}
1435 + viewerRef={codeViewReveal.attach}
1436 items={items}
1437 selectedLines={selectedLines}
1438 onSelectedLinesChange={setSelectedLines}
apps/web/src/components/pullRequest/filesViewedStore.test.ts new
+213
@@ -0,0 +1,213 @@
1 +import {
2 + EnvironmentId,
3 + ProjectId,
4 + type PullRequestFilesViewedResult,
5 + type PullRequestRef,
6 +} from "@t3tools/contracts";
7 +import { Cause } from "effect";
8 +import { AsyncResult } from "effect/reactivity";
9 +import { describe, expect, it, vi } from "vite-plus/test";
10 +
11 +import {
12 + createFilesViewedStore,
13 + type FilesViewedStoreDeps,
14 + type FilesViewedTarget,
15 +} from "./filesViewedStore";
16 +
17 +const reference = (number: number): PullRequestRef => ({
18 + projectId: ProjectId.make("project"),
19 + repository: "t3/code",
20 + number,
21 +});
22 +
23 +const first: FilesViewedTarget = {
24 + environmentId: EnvironmentId.make("files-viewed"),
25 + reference: reference(1),
26 +};
27 +const second: FilesViewedTarget = { ...first, reference: reference(2) };
28 +
29 +const answer = (viewed: boolean): PullRequestFilesViewedResult => ({
30 + files: [{ path: "a.ts", state: viewed ? "viewed" : "unviewed" }],
31 + truncated: false,
32 +});
33 +
34 +function setup(initial: PullRequestFilesViewedResult | null = answer(false)) {
35 + vi.useFakeTimers();
36 + const answers = new Map<string, (answer: PullRequestFilesViewedResult | null) => void>();
37 + const settles: Array<(result: AsyncResult.AsyncResult<unknown, unknown>) => void> = [];
38 + const send = vi.fn<FilesViewedStoreDeps["send"]>(
39 + () =>
40 + new Promise((resolve) => {
41 + settles.push((result) => resolve(result as never));
42 + }),
43 + );
44 + const refresh = vi.fn();
45 + const reportFailure = vi.fn();
46 + const store = createFilesViewedStore({
47 + flushDelayMs: 400,
48 + subscribeAnswers: (target, onAnswer) => {
49 + const key = String(target.reference.number);
50 + answers.set(key, onAnswer);
51 + onAnswer(initial);
52 + return () => answers.delete(key);
53 + },
54 + send,
55 + refresh,
56 + reportFailure,
57 + });
58 + const answerFor = (target: FilesViewedTarget, next: PullRequestFilesViewedResult | null) =>
59 + answers.get(String(target.reference.number))?.(next);
60 + return {
61 + store,
62 + send,
63 + refresh,
64 + reportFailure,
65 + settles,
66 + answerFor,
67 + answers,
68 + [Symbol.dispose]: () => vi.useRealTimers(),
69 + };
70 +}
71 +
72 +describe("createFilesViewedStore", () => {
73 + it("batches presses and holds them until a read that could have seen them", async () => {
74 + using t = setup();
75 + const scope = t.store.scope(first);
76 + const release = scope.subscribe(() => {});
77 + scope.setViewed("a.ts", true);
78 + expect(scope.getSnapshot().get("a.ts")).toBe(true);
79 + await vi.advanceTimersByTimeAsync(400);
80 + expect(t.send).toHaveBeenCalledTimes(1);
81 + expect(t.send.mock.calls[0]?.[1]).toEqual([{ path: "a.ts", viewed: true }]);
82 +
83 + t.settles[0]?.(AsyncResult.success(undefined));
84 + await vi.advanceTimersByTimeAsync(0);
85 + expect(t.refresh).toHaveBeenCalledWith(first);
86 + expect(scope.getSnapshot().get("a.ts")).toBe(true);
87 +
88 + // A push landed between the write and the next read: the host's answer wins.
89 + t.answerFor(first, {
90 + files: [{ path: "a.ts", state: "dismissed" }],
91 + truncated: false,
92 + });
93 + expect(scope.getSnapshot().size).toBe(0);
94 + release();
95 + });
96 +
97 + it("puts a failed press back and reports it", async () => {
98 + using t = setup();
99 + const scope = t.store.scope(first);
100 + const release = scope.subscribe(() => {});
101 + scope.setViewed("a.ts", true);
102 + await vi.advanceTimersByTimeAsync(400);
103 + t.settles[0]?.(AsyncResult.failure(Cause.fail("nope")));
104 + await vi.advanceTimersByTimeAsync(0);
105 + expect(scope.getSnapshot().size).toBe(0);
106 + expect(t.reportFailure).toHaveBeenCalledTimes(1);
107 + expect(t.refresh).toHaveBeenCalledWith(first);
108 + release();
109 + });
110 +
111 + it("refreshes the answer for a press that lands after its scope was left", async () => {
112 + using t = setup();
113 + const left = t.store.scope(first);
114 + const release = left.subscribe(() => {});
115 + left.setViewed("a.ts", true);
116 + release();
117 + expect(t.send).toHaveBeenCalledTimes(1);
118 +
119 + t.settles[0]?.(AsyncResult.success(undefined));
120 + await vi.advanceTimersByTimeAsync(0);
121 + expect(t.refresh).toHaveBeenCalledWith(first);
122 + });
123 +
124 + it("forgets a scope's handle once its last reader leaves", () => {
125 + using t = setup();
126 + const handle = t.store.scope(first);
127 + const release = handle.subscribe(() => {});
128 + expect(t.store.scope(first)).toBe(handle);
129 + release();
130 + expect(t.store.scope(first)).not.toBe(handle);
131 + });
132 +
133 + it("keeps the handle and the debounce across a release and re-subscribe through it", async () => {
134 + using t = setup();
135 + const handle = t.store.scope(first);
136 + // StrictMode subscribes, releases, then subscribes again through the same handle.
137 + handle.subscribe(() => {})();
138 + const release = handle.subscribe(() => {});
139 + expect(t.store.scope(first)).toBe(handle);
140 +
141 + handle.setViewed("a.ts", true);
142 + expect(t.store.scope(first)).toBe(handle);
143 + expect(t.send).not.toHaveBeenCalled();
144 + await vi.advanceTimersByTimeAsync(400);
145 + expect(t.send).toHaveBeenCalledTimes(1);
146 + release();
147 + });
148 +
149 + it("does not keep a handle no reader subscribed through", () => {
150 + using t = setup();
151 + const discarded = t.store.scope(first);
152 + const committed = t.store.scope(first);
153 + expect(committed).not.toBe(discarded);
154 + const release = committed.subscribe(() => {});
155 + expect(t.store.scope(first)).toBe(committed);
156 + release();
157 + });
158 +
159 + it("sends the last presses to the scope being left, and ignores their answer", async () => {
160 + using t = setup();
161 + const left = t.store.scope(first);
162 + const releaseLeft = left.subscribe(() => {});
163 + left.setViewed("a.ts", true);
164 + releaseLeft();
165 + const entered = t.store.scope(second);
166 + const releaseEntered = entered.subscribe(() => {});
167 +
168 + expect(t.send).toHaveBeenCalledTimes(1);
169 + expect(t.send.mock.calls[0]?.[0]).toEqual(first);
170 + expect(t.answers.has("1")).toBe(false);
171 + expect(left.getSnapshot().size).toBe(0);
172 +
173 + t.settles[0]?.(AsyncResult.failure(Cause.fail("nope")));
174 + await vi.advanceTimersByTimeAsync(400);
175 + expect(t.reportFailure).not.toHaveBeenCalled();
176 + expect(t.refresh).toHaveBeenCalledWith(first);
177 + expect(t.send).toHaveBeenCalledTimes(1);
178 + releaseEntered();
179 + });
180 +
181 + it("keeps the scope while another reader still holds it", async () => {
182 + using t = setup();
183 + const scope = t.store.scope(first);
184 + const releaseA = scope.subscribe(() => {});
185 + const releaseB = scope.subscribe(() => {});
186 + scope.setViewed("a.ts", true);
187 + releaseA();
188 + expect(t.send).not.toHaveBeenCalled();
189 + expect(scope.getSnapshot().get("a.ts")).toBe(true);
190 + await vi.advanceTimersByTimeAsync(400);
191 + expect(t.send).toHaveBeenCalledTimes(1);
192 + releaseB();
193 + });
194 +
195 + it("holds a queued press over an answer that cannot have seen it", async () => {
196 + using t = setup();
197 + const scope = t.store.scope(first);
198 + const release = scope.subscribe(() => {});
199 + scope.setViewed("a.ts", true);
200 + const agreeing = answer(true);
201 + t.answerFor(first, agreeing);
202 + expect(scope.getSnapshot().get("a.ts")).toBe(true);
203 + await vi.advanceTimersByTimeAsync(400);
204 + t.settles[0]?.(AsyncResult.success(undefined));
205 + await vi.advanceTimersByTimeAsync(0);
206 + // The same answer published again is not a new read.
207 + t.answerFor(first, agreeing);
208 + expect(scope.getSnapshot().get("a.ts")).toBe(true);
209 + t.answerFor(first, answer(false));
210 + expect(scope.getSnapshot().size).toBe(0);
211 + release();
212 + });
213 +});
apps/web/src/components/pullRequest/filesViewedStore.ts new
+257
@@ -0,0 +1,257 @@
1 +import {
2 + type AtomCommandResult,
3 + isAtomCommandInterrupted,
4 + runAtomCommand,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import type {
7 + EnvironmentId,
8 + PullRequestFilesViewedResult,
9 + PullRequestRef,
10 +} from "@t3tools/contracts";
11 +import * as Option from "effect/Option";
12 +import { AsyncResult } from "effect/reactivity";
13 +
14 +import { appAtomRegistry } from "~/rpc/atomRegistry";
15 +import { pullRequestEnvironment } from "~/state/pullRequests";
16 +
17 +import { toastManager } from "../ui/toast";
18 +import {
19 + revertFileViewedOverlay,
20 + settleFileViewedOverlay,
21 + toFileViewedBatch,
22 + toFileViewedStates,
23 + type FileViewedOverlay,
24 +} from "./pullRequestFilesViewed.logic";
25 +
26 +export interface FilesViewedTarget {
27 + readonly environmentId: EnvironmentId;
28 + readonly reference: PullRequestRef;
29 +}
30 +
31 +type FilesViewedBatch = ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>;
32 +
33 +export interface FilesViewedStoreDeps {
34 + readonly flushDelayMs: number;
35 + /** Calls `onAnswer` with the host's current answer at once, then with every later one. */
36 + readonly subscribeAnswers: (
37 + target: FilesViewedTarget,
38 + onAnswer: (answer: PullRequestFilesViewedResult | null) => void,
39 + ) => () => void;
40 + readonly send: (
41 + target: FilesViewedTarget,
42 + batch: FilesViewedBatch,
43 + ) => Promise<AtomCommandResult<unknown, unknown>>;
44 + readonly refresh: (target: FilesViewedTarget) => void;
45 + readonly reportFailure: () => void;
46 +}
47 +
48 +export interface FilesViewedScopeHandle {
49 + /** Holds the scope open while subscribed; the last reader to leave sends its last presses. */
50 + readonly subscribe: (listener: () => void) => () => void;
51 + readonly getSnapshot: () => FileViewedOverlay;
52 + readonly setViewed: (path: string, viewed: boolean) => void;
53 +}
54 +
55 +const NO_OVERLAY: FileViewedOverlay = new Map();
56 +
57 +interface FilesViewedScope {
58 + readonly target: FilesViewedTarget;
59 + readonly listeners: Set<() => void>;
60 + readonly unsubscribeAnswers: () => void;
61 + overlay: FileViewedOverlay;
62 + queued: Map<string, boolean>;
63 + readonly sentBy: Map<string, number>;
64 + requests: number;
65 + timer: ReturnType<typeof setTimeout> | null;
66 + answer: PullRequestFilesViewedResult | null;
67 + /**
68 + * The host's answer as it stood when a completed write was acknowledged, per path. The first
69 + * answer that differs from it is the first read that could have seen the write, which is what
70 + * retires the press rather than the host happening to agree with it.
71 + */
72 + readonly answeredFrom: Map<string, PullRequestFilesViewedResult | null>;
73 +}
74 +
75 +/**
76 + * Presses on one change request on one environment. The environment is part of the scope: two of
77 + * them can hand out the same project id, and a press made against one must never be answered for
78 + * by the other.
79 + */
80 +export function createFilesViewedStore(deps: FilesViewedStoreDeps) {
81 + const scopes = new Map<string, FilesViewedScope>();
82 + const handles = new Map<string, FilesViewedScopeHandle>();
83 +
84 + const publish = (scope: FilesViewedScope, overlay: FileViewedOverlay) => {
85 + if (overlay === scope.overlay) return;
86 + scope.overlay = overlay;
87 + for (const listener of scope.listeners) listener();
88 + };
89 +
90 + const isLive = (key: string, scope: FilesViewedScope) => scopes.get(key) === scope;
91 +
92 + const settle = (scope: FilesViewedScope, answer: PullRequestFilesViewedResult | null) => {
93 + if (answer === scope.answer) return;
94 + scope.answer = answer;
95 + const pending = new Set([...scope.queued.keys(), ...scope.sentBy.keys()]);
96 + const answered = new Set<string>();
97 + for (const [path, from] of scope.answeredFrom) {
98 + if (pending.has(path) || from === answer) continue;
99 + answered.add(path);
100 + scope.answeredFrom.delete(path);
101 + }
102 + publish(
103 + scope,
104 + settleFileViewedOverlay(scope.overlay, toFileViewedStates(answer), pending, answered),
105 + );
106 + };
107 +
108 + const flush = (key: string, scope: FilesViewedScope) => {
109 + scope.timer = null;
110 + const batch = toFileViewedBatch(scope.queued);
111 + if (batch.length === 0) return;
112 + scope.queued = new Map();
113 + const request = ++scope.requests;
114 + for (const file of batch) scope.sentBy.set(file.path, request);
115 + void deps.send(scope.target, batch).then((result) => {
116 + const mine = batch
117 + .map((file) => file.path)
118 + .filter((path) => scope.sentBy.get(path) === request);
119 + for (const path of mine) scope.sentBy.delete(path);
120 + if (!isLive(key, scope)) {
121 + // The overlay this press stood in is gone, but the cached answer still predates the
122 + // write, and a reader coming back to this change request would be shown that.
123 + if (result._tag === "Success" || !isAtomCommandInterrupted(result)) {
124 + deps.refresh(scope.target);
125 + }
126 + return;
127 + }
128 + if (result._tag === "Failure") {
129 + const owned = new Set(mine.filter((path) => !scope.queued.has(path)));
130 + publish(scope, revertFileViewedOverlay(scope.overlay, batch, owned));
131 + if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
132 + deps.reportFailure();
133 + deps.refresh(scope.target);
134 + }
135 + return;
136 + }
137 + // Answered for from the next read on, whatever it says. A push landing between the write
138 + // and that read comes back as `dismissed`, and the press must not stand over it.
139 + for (const path of mine) scope.answeredFrom.set(path, scope.answer);
140 + deps.refresh(scope.target);
141 + });
142 + };
143 +
144 + const acquire = (
145 + key: string,
146 + target: FilesViewedTarget,
147 + handle: FilesViewedScopeHandle,
148 + listener: () => void,
149 + ) => {
150 + // Registered from `subscribe`, which runs at commit, so a render that never commits leaves
151 + // nothing behind. Re-registering here also carries a handle across StrictMode's
152 + // subscribe-release-subscribe, so later renders keep returning it.
153 + if (!handles.has(key)) handles.set(key, handle);
154 + let scope = scopes.get(key);
155 + if (scope === undefined) {
156 + const listeners = new Set<() => void>();
157 + let created: FilesViewedScope | undefined;
158 + let initial: PullRequestFilesViewedResult | null = null;
159 + const unsubscribeAnswers = deps.subscribeAnswers(target, (answer) => {
160 + if (created === undefined) initial = answer;
161 + else settle(created, answer);
162 + });
163 + created = {
164 + target,
165 + listeners,
166 + unsubscribeAnswers,
167 + overlay: NO_OVERLAY,
168 + queued: new Map(),
169 + sentBy: new Map(),
170 + requests: 0,
171 + timer: null,
172 + answer: initial,
173 + answeredFrom: new Map(),
174 + };
175 + scope = created;
176 + scopes.set(key, scope);
177 + }
178 + const owned = scope;
179 + owned.listeners.add(listener);
180 + return () => {
181 + if (!owned.listeners.delete(listener) || owned.listeners.size > 0) return;
182 + // Leaving a change request, the environment it lives on, or the page itself records what
183 + // was pressed and then drops the rest, sending those last presses to the scope being left.
184 + if (owned.timer !== null) {
185 + clearTimeout(owned.timer);
186 + flush(key, owned);
187 + }
188 + scopes.delete(key);
189 + handles.delete(key);
190 + owned.unsubscribeAnswers();
191 + };
192 + };
193 +
194 + return {
195 + /**
196 + * One stable handle per open scope, so readers keep their subscription across renders. Pure
197 + * during render: an uncommitted handle is not cached, and any handle for a key behaves the same.
198 + */
199 + scope(target: FilesViewedTarget): FilesViewedScopeHandle {
200 + const key = filesViewedScopeKey(target);
201 + const cached = handles.get(key);
202 + if (cached !== undefined) return cached;
203 + const owned = { environmentId: target.environmentId, reference: { ...target.reference } };
204 + const handle: FilesViewedScopeHandle = {
205 + subscribe: (listener) => acquire(key, owned, handle, listener),
206 + getSnapshot: () => scopes.get(key)?.overlay ?? NO_OVERLAY,
207 + setViewed: (path, viewed) => {
208 + const scope = scopes.get(key);
209 + if (scope === undefined) return;
210 + scope.queued.set(path, viewed);
211 + publish(scope, new Map(scope.overlay).set(path, viewed));
212 + if (scope.timer !== null) clearTimeout(scope.timer);
213 + scope.timer = setTimeout(() => flush(key, scope), deps.flushDelayMs);
214 + },
215 + };
216 + return handle;
217 + },
218 + };
219 +}
220 +
221 +function filesViewedScopeKey({ environmentId, reference }: FilesViewedTarget): string {
222 + return JSON.stringify([
223 + environmentId,
224 + reference.projectId,
225 + reference.host ?? null,
226 + reference.expectedAccountId ?? null,
227 + reference.allowStale ?? null,
228 + reference.repository,
229 + reference.number,
230 + ]);
231 +}
232 +
233 +const filesViewedAtom = ({ environmentId, reference }: FilesViewedTarget) =>
234 + pullRequestEnvironment.filesViewed({ environmentId, input: reference });
235 +
236 +const filesViewedStore = createFilesViewedStore({
237 + flushDelayMs: 400,
238 + subscribeAnswers: (target, onAnswer) =>
239 + appAtomRegistry.subscribe(
240 + filesViewedAtom(target),
241 + (result) => onAnswer(Option.getOrNull(AsyncResult.value(result))),
242 + { immediate: true },
243 + ),
244 + send: ({ environmentId, reference }, files) =>
245 + runAtomCommand(
246 + appAtomRegistry,
247 + pullRequestEnvironment.setFilesViewed,
248 + { environmentId, input: { ...reference, files } },
249 + { reportFailure: false },
250 + ),
251 + refresh: (target) => appAtomRegistry.refresh(filesViewedAtom(target)),
252 + reportFailure: () => toastManager.add({ type: "error", title: "Could not update viewed files" }),
253 +});
254 +
255 +export function filesViewedScope(target: FilesViewedTarget): FilesViewedScopeHandle {
256 + return filesViewedStore.scope(target);
257 +}
apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts
+17 -112
@@ -1,28 +1,16 @@
1 -import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
1 import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
3 -import { useEffect, useEffectEvent, useRef, useState } from "react";
2 +import { useSyncExternalStore } from "react";
3
4 import { pullRequestEnvironment } from "~/state/pullRequests";
5 import { useEnvironmentQuery } from "~/state/query";
7 -import { useAtomCommand } from "~/state/use-atom-command";
8 -import { useStableCallback } from "~/hooks/useStableCallback";
6
10 -import { toastManager } from "../ui/toast";
7 +import { filesViewedScope } from "./filesViewedStore";
8 import {
9 isFileViewed,
10 isStaleViewedState,
14 - revertFileViewedOverlay,
15 - settleFileViewedOverlay,
16 - toFileViewedBatch,
11 toFileViewedStates,
18 - type FileViewedOverlay,
19 - type FileViewedStates,
12 } from "./pullRequestFilesViewed.logic";
13
22 -const FLUSH_DELAY_MS = 400;
23 -
24 -const NO_OVERLAY: FileViewedOverlay = new Map();
25 -
14 export interface PullRequestFilesViewedView {
15 readonly enabled: boolean;
16 readonly isViewed: (path: string) => boolean;
@@ -33,6 +21,14 @@ export interface PullRequestFilesViewedView {
21 readonly refresh: () => void;
22 }
23
24 +const NO_OVERLAY = new Map<string, boolean>();
25 +// Without this a change request that cannot record views would still be handed a scope handle.
26 +const DISABLED_SCOPE = {
27 + subscribe: () => () => {},
28 + getSnapshot: () => NO_OVERLAY,
29 + setViewed: () => {},
30 +};
31 +
32 export function usePullRequestFilesViewed(options: {
33 readonly environmentId: EnvironmentId;
34 readonly reference: PullRequestRef;
@@ -42,109 +38,18 @@ export function usePullRequestFilesViewed(options: {
38 const query = useEnvironmentQuery(
39 enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
40 );
45 - const refresh = query.refresh;
41 const states = toFileViewedStates(query.data);
47 - const truncated = query.data?.truncated === true;
48 - const error = query.error;
49 - const [overlay, setOverlay] = useState<FileViewedOverlay>(NO_OVERLAY);
50 - const setFilesViewed = useAtomCommand(pullRequestEnvironment.setFilesViewed, {
51 - reportFailure: false,
52 - });
53 -
54 - const queued = useRef<Map<string, boolean>>(new Map());
55 - const sentBy = useRef<Map<string, number>>(new Map());
56 - const requests = useRef(0);
57 - const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
58 -
59 - // Project ids can repeat across environments.
60 - const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;
61 - const scope = useRef(scopeKey);
62 -
63 - // Retire presses only after a post-write read, even if an older response agrees.
64 - const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());
65 - const committedStates = useRef(states);
66 -
67 - useEffect(() => {
68 - committedStates.current = states;
69 - const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);
70 - const answered = new Set<string>();
71 - for (const [path, from] of answeredFrom.current) {
72 - if (pending.has(path) || from === states) continue;
73 - answered.add(path);
74 - answeredFrom.current.delete(path);
75 - }
76 - setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));
77 - }, [states]);
78 -
79 - // Explicit targets keep departing scopes' presses in their original scope.
80 - const flush = (target: {
81 - readonly environmentId: EnvironmentId;
82 - readonly reference: PullRequestRef;
83 - }) => {
84 - flushTimer.current = null;
85 - const batch = toFileViewedBatch(queued.current);
86 - if (batch.length === 0) return;
87 - queued.current = new Map();
88 - const sentFrom = scope.current;
89 - const request = ++requests.current;
90 - for (const file of batch) sentBy.current.set(file.path, request);
91 - void setFilesViewed({
92 - environmentId: target.environmentId,
93 - input: { ...target.reference, files: batch },
94 - }).then((result) => {
95 - const mine = batch
96 - .map((file) => file.path)
97 - .filter((path) => sentBy.current.get(path) === request);
98 - for (const path of mine) sentBy.current.delete(path);
99 - if (scope.current !== sentFrom) return;
100 - if (result._tag === "Failure") {
101 - const owned = new Set(mine.filter((path) => !queued.current.has(path)));
102 - setOverlay((current) => revertFileViewedOverlay(current, batch, owned));
103 - if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
104 - toastManager.add({ type: "error", title: "Could not update viewed files" });
105 - refresh();
106 - }
107 - return;
108 - }
109 - // The next read can report dismissed after a push; retire presses regardless of its value.
110 - for (const path of mine) answeredFrom.current.set(path, committedStates.current);
111 - refresh();
112 - });
113 - };
114 -
115 - const currentTarget = useEffectEvent(() => ({ environmentId, reference }));
116 - const flushTarget = useEffectEvent(flush);
117 -
118 - useEffect(() => {
119 - const leaving = currentTarget();
120 - scope.current = scopeKey;
121 - return () => {
122 - if (flushTimer.current !== null) {
123 - clearTimeout(flushTimer.current);
124 - flushTarget(leaving);
125 - }
126 - queued.current = new Map();
127 - sentBy.current = new Map();
128 - answeredFrom.current = new Map();
129 - setOverlay(NO_OVERLAY);
130 - };
131 - }, [scopeKey]);
132 -
133 - const setViewed = useStableCallback((path: string, viewed: boolean) => {
134 - setOverlay((current) => new Map(current).set(path, viewed));
135 - queued.current.set(path, viewed);
136 - if (flushTimer.current !== null) clearTimeout(flushTimer.current);
137 - const target = { environmentId, reference };
138 - flushTimer.current = setTimeout(() => flush(target), FLUSH_DELAY_MS);
139 - });
42 + // Stable per scope: `setViewed` is handed to every file header the viewer draws.
43 + const scope = enabled ? filesViewedScope({ environmentId, reference }) : DISABLED_SCOPE;
44 + const overlay = useSyncExternalStore(scope.subscribe, scope.getSnapshot);
45
46 return {
47 enabled,
48 isViewed: (path: string) => isFileViewed(path, states, overlay),
49 isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
145 - setViewed,
146 - truncated,
147 - error,
148 - refresh,
50 + setViewed: scope.setViewed,
51 + truncated: query.data?.truncated === true,
52 + error: query.error,
53 + refresh: query.refresh,
54 };
55 }
apps/web/src/hooks/useLiveRefresh.browser.test.tsx new
+65
@@ -0,0 +1,65 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { act, fakeTimers, render } from "../../test/render";
4 +import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "./useLiveRefresh";
5 +
6 +function Probe(props: {
7 + readonly refresh: () => void;
8 + readonly viewKey: string;
9 + readonly enabled?: boolean;
10 + readonly intervalMs?: number | null;
11 + readonly refreshOnShow?: boolean;
12 +}) {
13 + useLiveRefresh(props.refresh, {
14 + key: props.viewKey,
15 + enabled: props.enabled ?? true,
16 + ...(props.intervalMs !== undefined ? { intervalMs: props.intervalMs } : {}),
17 + ...(props.refreshOnShow !== undefined ? { refreshOnShow: props.refreshOnShow } : {}),
18 + });
19 + return null;
20 +}
21 +
22 +describe("useLiveRefresh", () => {
23 + it("with refreshOnShow, reads on every show unless it read within the floor", async () => {
24 + const refresh = vi.fn();
25 + // The first enable reads the clock.
26 + using _timers = fakeTimers({ now: 1_000_000 });
27 + const probe = (enabled: boolean) => (
28 + <Probe refresh={refresh} viewKey="show" enabled={enabled} refreshOnShow intervalMs={null} />
29 + );
30 + // A bare hook probe; nothing here navigates.
31 + await using screen = await render(probe(true), { router: false });
32 + expect(refresh).toHaveBeenCalledTimes(1);
33 +
34 + await screen.rerender(probe(false));
35 + await act(() => vi.advanceTimersByTime(LIVE_REFRESH_MIN_INTERVAL_MS - 1));
36 + await screen.rerender(probe(true));
37 + expect(refresh).toHaveBeenCalledTimes(1);
38 +
39 + await screen.rerender(probe(false));
40 + await act(() => vi.advanceTimersByTime(1));
41 + await screen.rerender(probe(true));
42 + expect(refresh).toHaveBeenCalledTimes(2);
43 + });
44 +
45 + it("with intervalMs null, never refreshes on a timer", async () => {
46 + const periodic = vi.fn();
47 + const untimed = vi.fn();
48 + // The interaction clock starts when the first view mounts.
49 + using _timers = fakeTimers({ now: 1_000_000 });
50 + await using _screen = await render(
51 + <>
52 + <Probe refresh={periodic} viewKey="periodic" intervalMs={60_000} />
53 + <Probe refresh={untimed} viewKey="untimed" intervalMs={null} />
54 + </>,
55 + // A bare hook probe; nothing here navigates.
56 + { router: false },
57 + );
58 +
59 + // Past the default 5 minute interval, but inside the 6 minute idle cutoff.
60 + await act(() => vi.advanceTimersByTime(5.5 * 60_000));
61 +
62 + expect(periodic).toHaveBeenCalledTimes(5);
63 + expect(untimed).not.toHaveBeenCalled();
64 + });
65 +});
apps/web/src/hooks/useLiveRefresh.ts
+24 -6
@@ -1,6 +1,6 @@
1 import { useEffect, useEffectEvent, useId } from "react";
2
3 -const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;
3 +export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;
4
5 const LIVE_REFRESH_INTERVAL_MS = 5 * 60_000;
6
@@ -75,10 +75,22 @@ export function useLiveRefresh(
75 options: {
76 readonly enabled?: boolean;
77 readonly key?: string;
78 - readonly intervalMs?: number;
78 + /** `null` turns off the periodic refresh, for a read too costly to repeat unasked. */
79 + readonly intervalMs?: number | null;
80 + /**
81 + * Refresh every time the view is enabled unless it read within the floor, skipping the
82 + * first-read rule: for a view that stays mounted while hidden, so its mount-time read can be
83 + * long stale when shown.
84 + */
85 + readonly refreshOnShow?: boolean;
86 } = {},
87 ): void {
81 - const { enabled = true, key, intervalMs = LIVE_REFRESH_INTERVAL_MS } = options;
88 + const {
89 + enabled = true,
90 + key,
91 + intervalMs = LIVE_REFRESH_INTERVAL_MS,
92 + refreshOnShow = false,
93 + } = options;
94 const runRefresh = useEffectEvent((viewId: string, now: number) => {
95 if (refresh === null) return;
96 lastRefreshedAtByView.set(viewId, now);
@@ -112,7 +124,7 @@ export function useLiveRefresh(
124 let timer: ReturnType<typeof setInterval> | undefined;
125 const syncTimer = () => {
126 clearInterval(timer);
115 - timer = visible() ? setInterval(onInterval, intervalMs) : undefined;
127 + timer = visible() && intervalMs !== null ? setInterval(onInterval, intervalMs) : undefined;
128 };
129 const onVisibilityChange = () => {
130 onArrival();
@@ -123,7 +135,13 @@ export function useLiveRefresh(
135 onArrival();
136 syncTimer();
137 });
126 - onArrival();
138 + if (refreshOnShow) {
139 + const now = Date.now();
140 + const lastRefreshedAt = lastRefreshedAtByView.get(viewId);
141 + if (lastRefreshedAt === undefined || now - lastRefreshedAt >= LIVE_REFRESH_MIN_INTERVAL_MS) {
142 + read(now);
143 + }
144 + } else onArrival();
145 syncTimer();
146 window.addEventListener("focus", onArrival);
147 document.addEventListener("visibilitychange", onVisibilityChange);
@@ -133,5 +151,5 @@ export function useLiveRefresh(
151 document.removeEventListener("visibilitychange", onVisibilityChange);
152 stopWatchingInteraction();
153 };
136 - }, [enabled, viewId, intervalMs]);
154 + }, [enabled, viewId, intervalMs, refreshOnShow]);
155 }
apps/web/src/state/revisionedQuery.browser.test.tsx new
+36
@@ -0,0 +1,36 @@
1 +import { RegistryContext, useAtomValue } from "@effect/atom-react";
2 +import { Atom, AtomRegistry } from "effect/reactivity";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { render } from "../../test/render";
6 +import { revisionedQuery } from "./revisionedQuery";
7 +
8 +describe("revisionedQuery in React", () => {
9 + it("refetches for a new revision without updating a component during render", async () => {
10 + let fetches = 0;
11 + const query = Atom.make(() => {
12 + fetches += 1;
13 + return fetches;
14 + }).pipe(Atom.keepAlive);
15 + const registry = AtomRegistry.make();
16 + function Reader({ revision }: { revision: string }) {
17 + return <span>fetch {useAtomValue(revisionedQuery(query, revision))}</span>;
18 + }
19 + const ui = (revision: string) => (
20 + <RegistryContext.Provider value={registry}>
21 + <Reader revision={revision} />
22 + </RegistryContext.Provider>
23 + );
24 + using consoleError = vi.spyOn(console, "error");
25 + // A bare atom reader: no links or navigation to route.
26 + await using screen = await render(ui("mutation-1"), { router: false });
27 + await expect.element(screen.getByText("fetch 1")).toBeInTheDocument();
28 +
29 + await screen.rerender(ui("mutation-2"));
30 +
31 + await expect.element(screen.getByText("fetch 2")).toBeInTheDocument();
32 + expect(consoleError.mock.calls.map(([message]) => String(message))).not.toContainEqual(
33 + expect.stringContaining("Cannot update a component"),
34 + );
35 + });
36 +});
apps/web/src/state/revisionedQuery.test.ts
+39 -25
@@ -19,8 +19,10 @@ function setup() {
19 fetches += 1;
20 return fetches;
21 }).pipe(Atom.keepAlive);
22 - const mount = (revision: string | null | undefined) => {
22 + const mount = async (revision: string | null | undefined) => {
23 const release = registry.mount(revisionedQuery(query, revision));
24 + // A stale read refetches in a microtask, after the render that read it.
25 + await Promise.resolve();
26 return () => {
27 release();
28 for (const task of scheduled.splice(0)) task();
@@ -30,75 +32,87 @@ function setup() {
32 }
33
34 describe("revisionedQuery", () => {
33 - it("refetches once per new revision, not on the first read or a remount", () => {
35 + it("refetches once per new revision, not on the first read or a remount", async () => {
36 const { mount, fetches } = setup();
37
36 - mount("mutation-1")();
38 + (await mount("mutation-1"))();
39 expect(fetches()).toBe(1);
40
39 - mount("mutation-1")();
41 + (await mount("mutation-1"))();
42 expect(fetches()).toBe(1);
43
42 - mount("mutation-2")();
44 + (await mount("mutation-2"))();
45 expect(fetches()).toBe(2);
46 });
47
46 - it("does not ping-pong while readers of the old and new revision overlap", () => {
48 + it("does not ping-pong while readers of the old and new revision overlap", async () => {
49 const { mount, fetches } = setup();
50
49 - const releaseOld = mount("mutation-1");
50 - const releaseNew = mount("mutation-2");
51 + const releaseOld = await mount("mutation-1");
52 + const releaseNew = await mount("mutation-2");
53 expect(fetches()).toBe(2);
54 releaseOld();
55 releaseNew();
56 });
57
56 - it("refetches when an earlier revision is read again", () => {
58 + it("refetches when an earlier revision is read again", async () => {
59 const { mount, fetches } = setup();
60
59 - mount("mutation-1")();
60 - mount("mutation-2")();
61 - mount("mutation-1")();
61 + (await mount("mutation-1"))();
62 + (await mount("mutation-2"))();
63 + (await mount("mutation-1"))();
64 expect(fetches()).toBe(3);
65 });
66
65 - it("refetches a query another reader already cached on its first revisioned read", () => {
67 + it("refetches a query another reader already cached on its first revisioned read", async () => {
68 const { mount, fetches } = setup();
69
68 - mount(undefined)();
70 + (await mount(undefined))();
71 expect(fetches()).toBe(1);
72
71 - mount("mutation-1")();
73 + (await mount("mutation-1"))();
74 expect(fetches()).toBe(2);
75
74 - mount("mutation-1")();
76 + (await mount("mutation-1"))();
77 expect(fetches()).toBe(2);
78 });
79
78 - it("does not refetch a cached query on a first read before any workspace change", () => {
80 + it("does not refetch a cached query on a first read before any workspace change", async () => {
81 const { mount, fetches } = setup();
82
81 - mount(undefined)();
82 - mount(null)();
83 + (await mount(undefined))();
84 + (await mount(null))();
85 expect(fetches()).toBe(1);
86 });
87
86 - it("leaves the query alone when read without a revision", () => {
88 + it("leaves the query alone when read without a revision", async () => {
89 const { mount, query, fetches } = setup();
90
89 - mount("mutation-1")();
91 + (await mount("mutation-1"))();
92 expect(revisionedQuery(query, undefined)).toBe(query);
91 - mount(undefined)();
92 - mount("mutation-1")();
93 + (await mount(undefined))();
94 + (await mount("mutation-1"))();
95 expect(fetches()).toBe(1);
96 });
97
96 - it("refetches the query when the reader is refreshed", () => {
98 + it("refetches the query when the reader is refreshed", async () => {
99 const { registry, query, mount, fetches } = setup();
100
99 - const release = mount("mutation-1");
101 + const release = await mount("mutation-1");
102 registry.refresh(revisionedQuery(query, "mutation-1"));
103 expect(fetches()).toBe(2);
104 release();
105 });
106 +
107 + it("drops a pending refetch when the registry is disposed before it runs", async () => {
108 + const { registry, query, mount } = setup();
109 +
110 + (await mount("mutation-1"))();
111 + const release = registry.mount(revisionedQuery(query, "mutation-2"));
112 + release();
113 + registry.dispose();
114 +
115 + // A refetch that ran now would throw "registry is disposed" as an uncaught error.
116 + await Promise.resolve();
117 + });
118 });
apps/web/src/state/revisionedQuery.ts
+9 -1
@@ -26,7 +26,15 @@ const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>
26 : // A reader without a revision may have cached it before the latest
27 // workspace change; a query nobody has read yet fetches fresh anyway.
28 revision !== null && get.registry.getNodes().has(queryKey(query));
29 - if (stale) get.refresh(query);
29 + // Deferred: this builds while React renders, and a refresh would synchronously
30 + // re-render the query's other readers, which React rejects.
31 + if (stale) {
32 + const registry = get.registry;
33 + queueMicrotask(() => {
34 + // No node, as after the registry is disposed: nothing cached to refetch.
35 + if (registry.getNodes().has(queryKey(query))) registry.refresh(query);
36 + });
37 + }
38 revisions.set(query, revision);
39 }
40 return get(query);