TypeScript
refactor(web): diff and file reveals are requests, and workspace edits refetch by construction (#25732)
Julius Marmingef6a9315d1928
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 5d7deeebeab..a5034b798ef 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -19,7 +19,6 @@ import {} from "lucide-react";import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";import * as Schema from "effect/Schema";-import * as DateTime from "effect/DateTime";import { useEffect, useRef, useState } from "react";import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";import { useFilesystemReadAccess } from "~/state/filesystem";@@ -28,6 +27,7 @@ import { useFileContextMenuHandler } from "../fileContextMenu";import { type DraftId } from "../composerDraftStore";import { openDiffFilePrimaryAction } from "../diffFileActions";import { useCheckpointDiff } from "~/lib/checkpointDiffState";+import { revisionedQuery } from "~/state/revisionedQuery";import { cn } from "~/lib/utils";import {selectThreadDiffPanelSelection,@@ -48,14 +48,14 @@ import {} from "../lib/diffRendering";import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";-import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";+import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";import { useClientSettings, updateClientSettings } from "../hooks/useSettings";import { formatShortTimestamp } from "../timestampFormat";import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";import { DiffStatLabel } from "./chat/DiffStatLabel";-import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";+import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView";import { DiffFileTree } from "./diffs/DiffFileTree";import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";import { Button } from "./ui/button";@@ -216,7 +216,6 @@ export default function DiffPanel({);const [baseRefQuery, setBaseRefQuery] = useState("");const [codeViewRevision, setCodeViewRevision] = useState(0);- const [codeView, setCodeView] = useState<AnnotatableCodeViewHandle | null>(null);const routeThreadRef = useThreadRouteRef();const activeThreadId = routeThreadRef?.threadId ?? null;@@ -322,20 +321,29 @@ export default function DiffPanel({},{ enabled: isGitRepo && selectedTurn !== undefined },);- const branchDiffPreview = useEnvironmentQuery(+ const branchDiffPreviewInput =canReadFiles && selectedRunId === null && activeThread && activeCwd- ? reviewEnvironment.diffPreview({- environmentId: activeThread.environmentId,- input: {- cwd: activeCwd,- ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),- ignoreWhitespace: diffIgnoreWhitespace,- },- })- : null,- );+ ? {+ cwd: activeCwd,+ ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),+ ignoreWhitespace: diffIgnoreWhitespace,+ }+ : undefined;const canRefreshGitDiff =isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null;+ // Read under the workspace mutation id, so each mutation refetches the diff; the panel stays+ // mounted while hidden, so a mutation made then is already reflected when it shows.+ const branchDiffPreview = useEnvironmentQuery(+ branchDiffPreviewInput && activeThread+ ? revisionedQuery(+ reviewEnvironment.diffPreview({+ environmentId: activeThread.environmentId,+ input: branchDiffPreviewInput,+ }),+ canRefreshGitDiff ? workspaceMutationId : undefined,+ )+ : null,+ );const activeThreadRefreshKey = routeThreadRef? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`: null;@@ -458,51 +466,30 @@ export default function DiffPanel({baseRef: lazySource?.baseRef ?? selectedBaseRef,ignoreWhitespace: diffIgnoreWhitespace,theme: resolvedTheme,- revision: branchDiffPreview.data- ? DateTime.formatIso(branchDiffPreview.data.generatedAt)- : undefined,+ previewInput: branchDiffPreviewInput,preview: renderablePatch,});const refreshBranchDiffPreview = refreshPreviewQuery;- const previewOpenHandledRef = useRef(false);- const refreshDiffForWorkspaceMutation = useStableCallback(() => {- previewOpenHandledRef.current = true;- refreshBranchDiffPreview();- });-- // A mutation refresh also satisfies revalidation for the current opening.- useWorkspaceMutationRefresh({- enabled: canRefreshGitDiff,- mutationId: workspaceMutationId,- refresh: refreshDiffForWorkspaceMutation,- resourceKey: `diff:${activeThreadRefreshKey ?? ""}`,- });-- useEffect(() => {- if (!visible || !canReadFiles || !canRefreshGitDiff) {- previewOpenHandledRef.current = false;- return;- }- if (previewOpenHandledRef.current) return;- previewOpenHandledRef.current = true;- if (branchDiffPreview.data !== null && !branchDiffPreview.isPending) {- refreshBranchDiffPreview();- }- }, [- branchDiffPreview.data,- branchDiffPreview.isPending,- canReadFiles,- canRefreshGitDiff,- refreshBranchDiffPreview,- visible,- ]);+ const diffRefreshKey = `diff:${activeThreadRefreshKey ?? ""}`;- useEffect(() => {- if (!canRefreshGitDiff) return;- const refreshOnFocus = () => refreshBranchDiffPreview();- window.addEventListener("focus", refreshOnFocus);- return () => window.removeEventListener("focus", refreshOnFocus);- }, [canRefreshGitDiff, refreshBranchDiffPreview]);+ // The panel stays mounted while hidden, and edits made outside T3 Code bump no mutation id, so+ // showing it revalidates the diff; that also stands in for focus events missed while hidden.+ // A git diff is too costly to repeat on a timer nobody asked for. A diff read within the floor,+ // such as a mutation's refetch while hidden, already counts as that revalidation.+ useLiveRefresh(+ branchDiffPreview.data !== null && !branchDiffPreview.isPending+ ? () => {+ if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return;+ refreshBranchDiffPreview();+ }+ : null,+ {+ enabled: visible && canReadFiles && canRefreshGitDiff,+ key: diffRefreshKey,+ intervalMs: null,+ refreshOnShow: true,+ },+ );const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;const renderableFileEntries = renderableFiles.map(getCachedFileEntry);@@ -542,13 +529,11 @@ export default function DiffPanel({collapsed:collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,}));- const codeViewFileKeys = codeViewFiles.map((file) => file.fileKey);const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);const fileTreeEntries = diffFileTreeEntries(renderableFiles);- const treeRevealScope = { collapseScopeKey, diffSelection };- const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope, codeViewFileKeys);+ const codeViewReveal = useCodeViewFileReveal();const revealDiffFile = (filePath: string) => {const index = renderableFileEntries.findIndex((candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,@@ -563,10 +548,12 @@ export default function DiffPanel({if (lazySource && index >= settledFileCount) {requestFile(index);}- requestTreeReveal(file.fileKey);+ codeViewReveal.request(file.fileKey);return true;};+ // A file another view asked to reveal (a chat diff link): retried as the diff loads until it+ // holds the file, then not again until a new request, so it does not undo what the user did since.const externalRevealRef = useRef<string | null>(null);useEffect(() => {if (!selectedFilePath) {@@ -1093,7 +1080,7 @@ export default function DiffPanel({><AnnotatableCodeViewkey={collapseScopeKey ?? reviewSectionId}- viewerRef={setCodeView}+ viewerRef={codeViewReveal.attach}codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}className="h-full min-h-0 overflow-auto"files={codeViewFiles}@@ -1152,6 +1139,7 @@ export default function DiffPanel({preferredHighlighter: PREFERRED_HIGHLIGHTER,themeType: resolvedTheme as DiffThemeType,stickyHeaders: true,+ onPostRender: codeViewReveal.flush,...(currentLoadDiffFiles ? { loadDiffFiles } : {}),}}/>diff --git a/apps/web/src/components/diffs/useCodeViewFileReveal.test.ts b/apps/web/src/components/diffs/useCodeViewFileReveal.test.tsnew file mode 100644index 00000000000..c153120d2b4--- /dev/null+++ b/apps/web/src/components/diffs/useCodeViewFileReveal.test.ts@@ -0,0 +1,72 @@+import type { CodeViewScrollTarget } from "@pierre/diffs";+import { describe, expect, it } from "vite-plus/test";++import { createCodeViewFileReveal } from "./useCodeViewFileReveal";++function viewer(initialItems: ReadonlyArray<string>) {+ const items = new Set(initialItems);+ const scrolls: CodeViewScrollTarget[] = [];+ return {+ items,+ scrolls,+ getInstance: () => ({}),+ getItem: (id: string) => (items.has(id) ? {} : undefined),+ scrollTo: (target: CodeViewScrollTarget) => scrolls.push(target),+ };+}++describe("createCodeViewFileReveal", () => {+ it("scrolls at once to a file the viewer holds", () => {+ const reveal = createCodeViewFileReveal();+ const view = viewer(["a"]);+ reveal.attach(view);++ reveal.request("a");++ expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);+ });++ it("keeps a missing file pending until a flush finds it, then drops it", () => {+ const reveal = createCodeViewFileReveal();+ const view = viewer([]);+ reveal.attach(view);++ reveal.request("a");+ reveal.flush();+ expect(view.scrolls).toEqual([]);++ view.items.add("a");+ reveal.flush();+ reveal.flush();+ expect(view.scrolls).toHaveLength(1);+ });++ it("applies a reveal asked before the viewer mounted once it holds the file", () => {+ const reveal = createCodeViewFileReveal();+ const view = viewer([]);++ reveal.request("a");+ reveal.attach(view);+ expect(view.scrolls).toEqual([]);++ view.items.add("a");+ reveal.flush();+ expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);+ });++ it("drops a pending reveal when its viewer detaches, and positions the next viewer on request", () => {+ const reveal = createCodeViewFileReveal();+ const first = viewer([]);+ const second = viewer(["a"]);+ reveal.attach(first);++ reveal.request("a");+ reveal.attach(null);+ reveal.attach(second);+ reveal.flush();+ expect(second.scrolls).toEqual([]);++ reveal.request("a");+ expect(second.scrolls).toHaveLength(1);+ });+});diff --git a/apps/web/src/components/diffs/useCodeViewFileReveal.ts b/apps/web/src/components/diffs/useCodeViewFileReveal.tsindex a3008229c4c..f0779262dd1 100644--- a/apps/web/src/components/diffs/useCodeViewFileReveal.ts+++ b/apps/web/src/components/diffs/useCodeViewFileReveal.ts@@ -1,31 +1,42 @@import type { CodeViewScrollTarget } from "@pierre/diffs";-import { useEffect, useRef, useState } from "react";+import { useState } from "react";interface FileRevealHandle {getInstance(): object | undefined;+ getItem(id: string): object | undefined;scrollTo(target: CodeViewScrollTarget): void;}-export function useCodeViewFileReveal<TScope>(- viewer: FileRevealHandle | null,- scope: TScope,- readyFileKeys?: ReadonlyArray<string>,-) {- const [request, setRequest] = useState<{ fileKey: string; scope: TScope } | null>(null);- const handledRequest = useRef<typeof request>(null);-- useEffect(() => {- if (request === null || handledRequest.current === request) return;- if (request.scope !== scope) {- handledRequest.current = request;- return;- }- if (!viewer?.getInstance() || (readyFileKeys && !readyFileKeys.includes(request.fileKey)))- return;-- viewer.scrollTo({ type: "item", id: request.fileKey, align: "start" });- handledRequest.current = request;- }, [request, scope, viewer, readyFileKeys]);+/**+ * Scrolls a code view to a file. `attach` is the viewer's ref and `flush` its post-render+ * handler, so a reveal asked before the viewer mounts, or for a file it does not hold yet, is+ * positioned once it does. A reveal belongs to the diff it was asked of, so detaching the viewer,+ * such as remounting it for another diff scope, drops it.+ */+export function createCodeViewFileReveal() {+ let viewer: FileRevealHandle | null = null;+ let pending: string | null = null;+ const flush = () => {+ if (pending === null || viewer === null) return;+ if (!viewer.getInstance() || viewer.getItem(pending) === undefined) return;+ viewer.scrollTo({ type: "item", id: pending, align: "start" });+ pending = null;+ };+ return {+ attach(next: FileRevealHandle | null) {+ if (viewer !== null && next !== viewer) pending = null;+ viewer = next;+ flush();+ },+ request(fileKey: string) {+ pending = fileKey;+ flush();+ },+ flush,+ };+}- return (fileKey: string) => setRequest({ fileKey, scope });+export function useCodeViewFileReveal() {+ const [reveal] = useState(createCodeViewFileReveal);+ return reveal;}diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.tsindex e7fbfc4116f..b683e13a8f6 100644--- a/apps/web/src/components/diffs/useReviewFilePatches.ts+++ b/apps/web/src/components/diffs/useReviewFilePatches.ts@@ -1,9 +1,13 @@import { RegistryContext, useAtomValue } from "@effect/atom-react";import type { FileDiffMetadata } from "@pierre/diffs";-import type { EnvironmentId, ReviewDiffPreviewSource } from "@t3tools/contracts";+import type {+ EnvironmentId,+ ReviewDiffPreviewInput,+ ReviewDiffPreviewSource,+} from "@t3tools/contracts";import * as AsyncResult from "effect/reactivity/AsyncResult";import * as Atom from "effect/reactivity/Atom";-import { useContext, useEffect, useRef, useState } from "react";+import { useContext, useState } from "react";import { useStableCallback } from "~/hooks/useStableCallback";import { getRenderablePatch, resolveFileDiffPath, type RenderablePatch } from "~/lib/diffRendering";import { reviewEnvironment } from "~/state/review";@@ -21,7 +25,7 @@ export function useReviewFilePatches({baseRef,ignoreWhitespace,theme,- revision,+ previewInput,preview,}: {environmentId: EnvironmentId | undefined;@@ -30,7 +34,8 @@ export function useReviewFilePatches({baseRef: string | null;ignoreWhitespace: boolean;theme: "light" | "dark";- revision: string | undefined;+ /** The preview the file list came from; a newer revision of it refreshes loaded patches. */+ previewInput: ReviewDiffPreviewInput | undefined;preview: RenderablePatch | null;}) {const registry = useContext(RegistryContext);@@ -49,25 +54,13 @@ export function useReviewFilePatches({source,baseRef,ignoreWhitespace,+ previewInput,scope,requested,});const queriedPatchesAtom = reviewPatchesAtom(JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),);- const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });- useEffect(() => {- const previous = previousPreview.current;- previousPreview.current = { scope, revision, queries };- for (const { query } of queries) {- const changed = previous.scope === scope && previous.revision !== revision;- const cached =- !previous.queries.some((entry) => entry.query === query) &&- registry.get(query)._tag !== "Initial" &&- !registry.get(query).waiting;- if (changed || cached) registry.refresh(query);- }- }, [scope, revision, queries, registry]);const patches = useAtomValue(queriedPatchesAtom);const retry = useStableCallback((path: string) => {const files = sortedReviewFiles(source);@@ -170,6 +163,7 @@ function reviewFileQueries({source,baseRef,ignoreWhitespace,+ previewInput,scope,requested,}: {@@ -178,6 +172,7 @@ function reviewFileQueries({source: ReviewDiffPreviewSource | null;baseRef: string | null;ignoreWhitespace: boolean;+ previewInput: ReviewDiffPreviewInput | undefined;scope: string;requested: { scope: string; indices: number[] };}) {@@ -194,6 +189,7 @@ function reviewFileQueries({environmentId,input: {cacheKey: scope,+ ...(previewInput ? { preview: previewInput } : {}),request: {cwd,...(baseRef ? { baseRef } : {}),diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex 9be8dfbaf49..a788c3542d0 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -18,7 +18,8 @@ import {officePreviewKind,binaryPreviewKind,} from "@t3tools/shared/filePreview";-import { useAtomValue } from "@effect/atom-react";+import { useAtomMount, useAtomValue } from "@effect/atom-react";+import { Atom } from "effect/reactivity";import {DEFAULT_TOKENIZE_MAX_LENGTH,VirtualizedFile,@@ -58,7 +59,6 @@ import { useRemoteOpenState } from "~/remoteOpen";import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";import { useTheme } from "~/hooks/useTheme";import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";-import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";import { resolveDiffThemeName } from "~/lib/diffRendering";import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";import { cn } from "~/lib/utils";@@ -118,13 +118,17 @@ import {workspaceAssetResource,} from "./filePreviewMode";import { useFileSaveCoordinator } from "./useFileSaveCoordinator";+import { revisionedQuery } from "~/state/revisionedQuery";import {getOptimisticProjectFileQueryData,getProjectFileContents,+ getProjectFileQueryAtom,setProjectFileQueryData,useProjectFileQuery,} from "./projectFilesQueryState";+const NO_FILE_REVISION_ATOM = Atom.make(null);+interface FilePreviewPanelProps {environmentId: EnvironmentId;cwd: string;@@ -279,15 +283,13 @@ function WorkspaceVideoPreview(props: {workspaceRoot: props.workspaceRoot,absolutePath: props.absolutePath,});- const assetUrl = useAssetUrlState(props.environmentId, resource);+ // Each workspace mutation re-mints the URL, so an edited file loads its new bytes.+ const assetUrl = useAssetUrlState(+ props.environmentId,+ resource,+ props.workspaceMutationId ?? undefined,+ );const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);- useWorkspaceMutationRefresh({- mutationId: props.workspaceMutationId,- resourceKey: JSON.stringify([props.environmentId, resource]),- refresh: () => {- void refreshAssetUrl().catch(() => undefined);- },- });// Servers that report the file's revision let an unchanged file stay loaded; older ones// only offer the workspace mutation, which changes after every command. The revision also// goes in the URL, since two mints in the same millisecond sign identical URLs.@@ -337,16 +339,13 @@ function WorkspaceAudioPreview(props: {workspaceRoot: props.workspaceRoot,absolutePath: props.absolutePath,});- const assetUrl = useAssetUrlState(props.environmentId, resource);+ const assetUrl = useAssetUrlState(+ props.environmentId,+ resource,+ props.workspaceMutationId ?? undefined,+ );const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);const [failedUrl, setFailedUrl] = useState<string | null>(null);- useWorkspaceMutationRefresh({- mutationId: props.workspaceMutationId,- resourceKey: JSON.stringify([props.environmentId, resource]),- refresh: () => {- void refreshAssetUrl().catch(() => undefined);- },- });const fileRevision = assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined;const revision = fileRevision ?? props.workspaceMutationId;const revisionSuffix =@@ -1157,17 +1156,20 @@ export default function FilePreviewPanel({? resolvePathLinkTarget(relativePath, cwd): null;const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);- useWorkspaceMutationRefresh({- enabled:+ // Mounting the file read under the workspace mutation id refetches it after each mutation.+ useAtomMount(+ canReadFiles &&attachment === undefined &&relativePath !== null &&// Skip mutation reads for media and documents; folders still detect conversion to files.(isFolder || (!isMedia && !isPdf && !isDocument)) &&- !selectedFilePending,- mutationId: workspaceMutationId,- refresh: file.refresh,- resourceKey: `file:${environmentId}:${cwd}:${relativePath ?? ""}`,- });+ !selectedFilePending+ ? revisionedQuery(+ getProjectFileQueryAtom(environmentId, cwd, relativePath),+ workspaceMutationId,+ )+ : NO_FILE_REVISION_ATOM,+ );useEffect(() => {const crumbs = breadcrumbRef.current?.querySelectorAll<HTMLElement>("[data-file-crumb]");@@ -1578,15 +1580,13 @@ export function WorkspaceLargeTextPreview(props: {description: cause instanceof Error ? cause.message : "Try again.",});};- const assetUrl = useAssetUrlState(props.environmentId, resource);+ // Each workspace mutation re-mints the URL, so an edited file loads its new bytes.+ const assetUrl = useAssetUrlState(+ props.environmentId,+ resource,+ props.workspaceMutationId ?? undefined,+ );const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);- useWorkspaceMutationRefresh({- mutationId: props.workspaceMutationId,- resourceKey: JSON.stringify([props.environmentId, resource]),- refresh: () => {- void refreshAssetUrl().catch(() => undefined);- },- });const contentRevision = JSON.stringify([props.environmentId,resource,diff --git a/apps/web/src/components/files/projectFilesQueryState.test.tsx b/apps/web/src/components/files/projectFilesQueryState.test.tsxindex 797ed4fa2ac..d775d901185 100644--- a/apps/web/src/components/files/projectFilesQueryState.test.tsx+++ b/apps/web/src/components/files/projectFilesQueryState.test.tsx@@ -161,7 +161,7 @@ describe("project query refresh", () => {}});- it("refetches a listing when the workspace mutation changes, not when it is first read", () => {+ it("refetches a listing when the workspace mutation changes, not when it is first read", async () => {let fetches = 0;const listing = Atom.make(() => {fetches += 1;@@ -178,6 +178,10 @@ describe("project query refresh", () => {read("mutation-1");expect(fetches).toBe(1);+ read("mutation-2");+ // The refetch runs after the render that read the new revision; a reader that is not+ // subscribed sees it on its next read.+ await Promise.resolve();read("mutation-2");expect(fetches).toBe(2);} finally {diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsxindex 34a1c1ddfd6..9fac8aa9544 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx@@ -9,27 +9,49 @@ import { expect, it, vi } from "vite-plus/test";import "~/index.css";-const { diffAtom } = await vi.hoisted(async () => {+const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {const { AsyncResult, Atom } = await import("effect/reactivity");- const firstPage: PullRequestDiffResult = {- patch: [- "diff --git a/a.ts b/a.ts",+ const filePatch = (path: string) =>+ [+ `diff --git a/${path} b/${path}`,"index 1111111..2222222 100644",- "--- a/a.ts",- "+++ b/a.ts",- "@@ -1 +1 @@",+ `--- a/${path}`,+ `+++ b/${path}`,+ "@@ -1,6 +1,6 @@","-before()","+after()",+ " one()",+ " two()",+ " three()",+ " four()",+ " five()","",- ].join("\n"),+ ].join("\n");+ const firstPage: PullRequestDiffResult = {+ patch: filePatch("a.ts"),truncated: false,nextCursor: null,};- // An environment query whose refetch returns equal content hands back the previous value- // itself, so a refresh publishes a new result around the very same page.- return { diffAtom: Atom.make(() => AsyncResult.success(firstPage)) };+ const pages: Record<string, PullRequestDiffResult> = {+ first: {+ patch: Array.from({ length: 40 }, (_, index) => filePatch(`early-${index}.ts`)).join(""),+ truncated: true,+ nextCursor: "page-2",+ },+ "page-2": { patch: filePatch("late.ts"), truncated: false, nextCursor: null },+ };+ return {+ // An environment query whose refetch returns equal content hands back the previous value+ // itself, so a refresh publishes a new result around the very same page.+ diffAtom: Atom.make(() => AsyncResult.success(firstPage)),+ pagedDiffAtom: Atom.family((cursor: string) =>+ Atom.make(() => AsyncResult.success(pages[cursor]!)),+ ),+ };});+const mocks = vi.hoisted(() => ({ paged: false }));+vi.mock(import("~/state/use-atom-command"), async (original) => ({...(await original()),useAtomCommand: (() => vi.fn()) as never,@@ -40,7 +62,8 @@ vi.mock(import("~/state/pullRequests"), async (original) => {...actual,pullRequestEnvironment: {...actual.pullRequestEnvironment,- diff: (() => diffAtom) as never,+ diff: (({ input }: { input: { cursor?: string } }) =>+ mocks.paged ? pagedDiffAtom(input.cursor ?? "first") : diffAtom) as never,},};});@@ -100,7 +123,14 @@ const detail: PullRequestDetailView = {},};-const tab = (refreshToken: number) => (+function setup({ paged }: { paged: boolean }) {+ mocks.paged = paged;+}++const tab = (+ refreshToken: number,+ revealRequest: { readonly path: string; readonly nonce: number } | null = null,+) => (<PullRequestCodeTabscrollerRef={() => {}}environmentId={EnvironmentId.make("environment")}@@ -110,10 +140,12 @@ const tab = (refreshToken: number) => (onSelectedCommitChange={() => {}}onRefresh={() => {}}refreshToken={refreshToken}+ revealRequest={revealRequest}/>);it("keeps the diff after a refresh that brings back the same page", async () => {+ setup({ paged: false });const container = document.createElement("div");container.className = "flex h-[700px] w-[900px]";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 () =>.not.toBeInTheDocument();await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();});++function pagedContainer() {+ const container = document.createElement("div");+ container.className = "flex h-[500px] w-[900px]";+ return container;+}++// Rows are virtualized, so a header far down is not rendered until the view scrolls to it.+async function expectFileHeaderShown(+ screen: Awaited<ReturnType<typeof render>>,+ container: HTMLElement,+ path: string,+) {+ const header = screen.getByText(path, { exact: true }).first();+ await expect.element(header).toBeInTheDocument();+ await vi.waitFor(() => {+ const top = header.element().getBoundingClientRect().top;+ const bounds = container.getBoundingClientRect();+ expect(top).toBeGreaterThanOrEqual(bounds.top);+ expect(top).toBeLessThan(bounds.top + bounds.height / 2);+ });+}++it("scrolls to a file asked for as the tab opens", async () => {+ setup({ paged: true });+ const container = pagedContainer();+ await using screen = await render(tab(0, { path: "early-39.ts", nonce: 1 }), { container });++ await expectFileHeaderShown(screen, container, "early-39.ts");+});++it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {+ setup({ paged: true });+ const container = pagedContainer();+ await using screen = await render(tab(0), { container });+ await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();++ await screen.rerender(tab(0, { path: "late.ts", nonce: 1 }));++ await expectFileHeaderShown(screen, container, "late.ts");+});diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 2a84e557e32..517e3540d7d 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -3,7 +3,7 @@ import {sourceControlClients,} from "@t3tools/client-runtime/source-control-clients";import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";-import type { CodeViewAnnotationArgs, CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";+import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react";import type {EnvironmentId,PullRequestDetailView,@@ -41,6 +41,7 @@ import {type ReactNode,} from "react";+import { observeIntersection } from "~/lib/observeIntersection";import { useLocalStorage } from "~/hooks/useLocalStorage";import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";import { useRenderedAppearance } from "~/hooks/useTheme";@@ -311,9 +312,6 @@ function PullRequestCodeTab({readonly cursor: string | null;readonly slices: ReadonlyArray<DiffSlice>;}>({ key: "", cursor: null, slices: NO_SLICES });- const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup, undefined> | null>(- null,- );const referenceKey = pullRequestReviewKey(reference);const commit = selectedCommitOid;@@ -452,10 +450,8 @@ function PullRequestCodeTab({refreshFilesViewed();}, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]);- // The viewer mounts its footer later; state ensures the observer sees the sentinel.- const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);- const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);- const answeredReveal = useRef<number | null>(null);+ const codeViewReveal = useCodeViewFileReveal();+ const answeredRevealNonce = useRef<number | null>(null);const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, {environmentId,@@ -667,6 +663,16 @@ function PullRequestCodeTab({if (nextCursor === null) return;setSliceState((previous) => ({ ...previous, cursor: nextCursor }));};+ const sentinelRef = (node: HTMLDivElement | null) => {+ if (node === null || !canLoadNextSlice) return;+ return observeIntersection(+ node,+ (entry) => {+ if (entry.isIntersecting) loadNextSlice();+ },+ { rootMargin: "240px" },+ );+ };const toggleFile = (fileKey: string) =>setToggledFiles((current) => {@@ -692,8 +698,13 @@ function PullRequestCodeTab({const revealFile = (path: string) => {const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);if (item === undefined) return;- if (item.collapsed === true) toggleFile(item.id);- requestTreeReveal(item.id);+ // Unfold only: a second reveal before the unfold renders must not fold the file again.+ if (item.collapsed === true) {+ setToggledFiles((current) =>+ toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),+ );+ }+ codeViewReveal.request(item.id);};const toggleAllFiles = () => {@@ -762,7 +773,7 @@ function PullRequestCodeTab({const renderCodeViewFooter = () =>nextCursor === null ? null : (<div- ref={setSentinel}+ ref={sentinelRef}className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground">{diffQuery.error !== null ? (@@ -833,6 +844,7 @@ function PullRequestCodeTab({enableLineSelection: canSelectLines && draft === null,onGutterUtilityClick: beginComment,onLineSelectionEnd: beginComment,+ onPostRender: codeViewReveal.flush,};const runThreadCommand = async (@@ -1269,25 +1281,15 @@ function PullRequestCodeTab({</div></div>);- // Hooks between diff derivations and their readers break compiler caching.- useEffect(() => {- if (sentinel === null || !canLoadNextSlice) return;- const observer = new IntersectionObserver(- (observed) => {- if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();- },- { rootMargin: "240px" },- );- observer.observe(sentinel);- return () => observer.disconnect();- }, [canLoadNextSlice, loadNextSlice, sentinel]);+ // A file not loaded yet pages forward each time a slice arrives; once loaded, the viewer+ // positions it when it renders it.const answerReveal = useEffectEvent(() => {- if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;+ if (revealRequest === null || answeredRevealNonce.current === revealRequest.nonce) return;if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {if (canLoadNextSlice) loadNextSlice();return;}- answeredReveal.current = revealRequest.nonce;+ answeredRevealNonce.current = revealRequest.nonce;revealFile(revealRequest.path);});useEffect(() => {@@ -1430,7 +1432,7 @@ function PullRequestCodeTab({<StyledDiffCodeView<ReviewAnnotationGroup>className="@container h-full overflow-auto [scrollbar-gutter:stable]"containerRef={scrollerRef}- viewerRef={setViewer}+ viewerRef={codeViewReveal.attach}items={items}selectedLines={selectedLines}onSelectedLinesChange={setSelectedLines}diff --git a/apps/web/src/components/pullRequest/filesViewedStore.test.ts b/apps/web/src/components/pullRequest/filesViewedStore.test.tsnew file mode 100644index 00000000000..9633e130668--- /dev/null+++ b/apps/web/src/components/pullRequest/filesViewedStore.test.ts@@ -0,0 +1,213 @@+import {+ EnvironmentId,+ ProjectId,+ type PullRequestFilesViewedResult,+ type PullRequestRef,+} from "@t3tools/contracts";+import { Cause } from "effect";+import { AsyncResult } from "effect/reactivity";+import { describe, expect, it, vi } from "vite-plus/test";++import {+ createFilesViewedStore,+ type FilesViewedStoreDeps,+ type FilesViewedTarget,+} from "./filesViewedStore";++const reference = (number: number): PullRequestRef => ({+ projectId: ProjectId.make("project"),+ repository: "t3/code",+ number,+});++const first: FilesViewedTarget = {+ environmentId: EnvironmentId.make("files-viewed"),+ reference: reference(1),+};+const second: FilesViewedTarget = { ...first, reference: reference(2) };++const answer = (viewed: boolean): PullRequestFilesViewedResult => ({+ files: [{ path: "a.ts", state: viewed ? "viewed" : "unviewed" }],+ truncated: false,+});++function setup(initial: PullRequestFilesViewedResult | null = answer(false)) {+ vi.useFakeTimers();+ const answers = new Map<string, (answer: PullRequestFilesViewedResult | null) => void>();+ const settles: Array<(result: AsyncResult.AsyncResult<unknown, unknown>) => void> = [];+ const send = vi.fn<FilesViewedStoreDeps["send"]>(+ () =>+ new Promise((resolve) => {+ settles.push((result) => resolve(result as never));+ }),+ );+ const refresh = vi.fn();+ const reportFailure = vi.fn();+ const store = createFilesViewedStore({+ flushDelayMs: 400,+ subscribeAnswers: (target, onAnswer) => {+ const key = String(target.reference.number);+ answers.set(key, onAnswer);+ onAnswer(initial);+ return () => answers.delete(key);+ },+ send,+ refresh,+ reportFailure,+ });+ const answerFor = (target: FilesViewedTarget, next: PullRequestFilesViewedResult | null) =>+ answers.get(String(target.reference.number))?.(next);+ return {+ store,+ send,+ refresh,+ reportFailure,+ settles,+ answerFor,+ answers,+ [Symbol.dispose]: () => vi.useRealTimers(),+ };+}++describe("createFilesViewedStore", () => {+ it("batches presses and holds them until a read that could have seen them", async () => {+ using t = setup();+ const scope = t.store.scope(first);+ const release = scope.subscribe(() => {});+ scope.setViewed("a.ts", true);+ expect(scope.getSnapshot().get("a.ts")).toBe(true);+ await vi.advanceTimersByTimeAsync(400);+ expect(t.send).toHaveBeenCalledTimes(1);+ expect(t.send.mock.calls[0]?.[1]).toEqual([{ path: "a.ts", viewed: true }]);++ t.settles[0]?.(AsyncResult.success(undefined));+ await vi.advanceTimersByTimeAsync(0);+ expect(t.refresh).toHaveBeenCalledWith(first);+ expect(scope.getSnapshot().get("a.ts")).toBe(true);++ // A push landed between the write and the next read: the host's answer wins.+ t.answerFor(first, {+ files: [{ path: "a.ts", state: "dismissed" }],+ truncated: false,+ });+ expect(scope.getSnapshot().size).toBe(0);+ release();+ });++ it("puts a failed press back and reports it", async () => {+ using t = setup();+ const scope = t.store.scope(first);+ const release = scope.subscribe(() => {});+ scope.setViewed("a.ts", true);+ await vi.advanceTimersByTimeAsync(400);+ t.settles[0]?.(AsyncResult.failure(Cause.fail("nope")));+ await vi.advanceTimersByTimeAsync(0);+ expect(scope.getSnapshot().size).toBe(0);+ expect(t.reportFailure).toHaveBeenCalledTimes(1);+ expect(t.refresh).toHaveBeenCalledWith(first);+ release();+ });++ it("refreshes the answer for a press that lands after its scope was left", async () => {+ using t = setup();+ const left = t.store.scope(first);+ const release = left.subscribe(() => {});+ left.setViewed("a.ts", true);+ release();+ expect(t.send).toHaveBeenCalledTimes(1);++ t.settles[0]?.(AsyncResult.success(undefined));+ await vi.advanceTimersByTimeAsync(0);+ expect(t.refresh).toHaveBeenCalledWith(first);+ });++ it("forgets a scope's handle once its last reader leaves", () => {+ using t = setup();+ const handle = t.store.scope(first);+ const release = handle.subscribe(() => {});+ expect(t.store.scope(first)).toBe(handle);+ release();+ expect(t.store.scope(first)).not.toBe(handle);+ });++ it("keeps the handle and the debounce across a release and re-subscribe through it", async () => {+ using t = setup();+ const handle = t.store.scope(first);+ // StrictMode subscribes, releases, then subscribes again through the same handle.+ handle.subscribe(() => {})();+ const release = handle.subscribe(() => {});+ expect(t.store.scope(first)).toBe(handle);++ handle.setViewed("a.ts", true);+ expect(t.store.scope(first)).toBe(handle);+ expect(t.send).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(400);+ expect(t.send).toHaveBeenCalledTimes(1);+ release();+ });++ it("does not keep a handle no reader subscribed through", () => {+ using t = setup();+ const discarded = t.store.scope(first);+ const committed = t.store.scope(first);+ expect(committed).not.toBe(discarded);+ const release = committed.subscribe(() => {});+ expect(t.store.scope(first)).toBe(committed);+ release();+ });++ it("sends the last presses to the scope being left, and ignores their answer", async () => {+ using t = setup();+ const left = t.store.scope(first);+ const releaseLeft = left.subscribe(() => {});+ left.setViewed("a.ts", true);+ releaseLeft();+ const entered = t.store.scope(second);+ const releaseEntered = entered.subscribe(() => {});++ expect(t.send).toHaveBeenCalledTimes(1);+ expect(t.send.mock.calls[0]?.[0]).toEqual(first);+ expect(t.answers.has("1")).toBe(false);+ expect(left.getSnapshot().size).toBe(0);++ t.settles[0]?.(AsyncResult.failure(Cause.fail("nope")));+ await vi.advanceTimersByTimeAsync(400);+ expect(t.reportFailure).not.toHaveBeenCalled();+ expect(t.refresh).toHaveBeenCalledWith(first);+ expect(t.send).toHaveBeenCalledTimes(1);+ releaseEntered();+ });++ it("keeps the scope while another reader still holds it", async () => {+ using t = setup();+ const scope = t.store.scope(first);+ const releaseA = scope.subscribe(() => {});+ const releaseB = scope.subscribe(() => {});+ scope.setViewed("a.ts", true);+ releaseA();+ expect(t.send).not.toHaveBeenCalled();+ expect(scope.getSnapshot().get("a.ts")).toBe(true);+ await vi.advanceTimersByTimeAsync(400);+ expect(t.send).toHaveBeenCalledTimes(1);+ releaseB();+ });++ it("holds a queued press over an answer that cannot have seen it", async () => {+ using t = setup();+ const scope = t.store.scope(first);+ const release = scope.subscribe(() => {});+ scope.setViewed("a.ts", true);+ const agreeing = answer(true);+ t.answerFor(first, agreeing);+ expect(scope.getSnapshot().get("a.ts")).toBe(true);+ await vi.advanceTimersByTimeAsync(400);+ t.settles[0]?.(AsyncResult.success(undefined));+ await vi.advanceTimersByTimeAsync(0);+ // The same answer published again is not a new read.+ t.answerFor(first, agreeing);+ expect(scope.getSnapshot().get("a.ts")).toBe(true);+ t.answerFor(first, answer(false));+ expect(scope.getSnapshot().size).toBe(0);+ release();+ });+});diff --git a/apps/web/src/components/pullRequest/filesViewedStore.ts b/apps/web/src/components/pullRequest/filesViewedStore.tsnew file mode 100644index 00000000000..64ae67a3551--- /dev/null+++ b/apps/web/src/components/pullRequest/filesViewedStore.ts@@ -0,0 +1,257 @@+import {+ type AtomCommandResult,+ isAtomCommandInterrupted,+ runAtomCommand,+} from "@t3tools/client-runtime/state/runtime";+import type {+ EnvironmentId,+ PullRequestFilesViewedResult,+ PullRequestRef,+} from "@t3tools/contracts";+import * as Option from "effect/Option";+import { AsyncResult } from "effect/reactivity";++import { appAtomRegistry } from "~/rpc/atomRegistry";+import { pullRequestEnvironment } from "~/state/pullRequests";++import { toastManager } from "../ui/toast";+import {+ revertFileViewedOverlay,+ settleFileViewedOverlay,+ toFileViewedBatch,+ toFileViewedStates,+ type FileViewedOverlay,+} from "./pullRequestFilesViewed.logic";++export interface FilesViewedTarget {+ readonly environmentId: EnvironmentId;+ readonly reference: PullRequestRef;+}++type FilesViewedBatch = ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>;++export interface FilesViewedStoreDeps {+ readonly flushDelayMs: number;+ /** Calls `onAnswer` with the host's current answer at once, then with every later one. */+ readonly subscribeAnswers: (+ target: FilesViewedTarget,+ onAnswer: (answer: PullRequestFilesViewedResult | null) => void,+ ) => () => void;+ readonly send: (+ target: FilesViewedTarget,+ batch: FilesViewedBatch,+ ) => Promise<AtomCommandResult<unknown, unknown>>;+ readonly refresh: (target: FilesViewedTarget) => void;+ readonly reportFailure: () => void;+}++export interface FilesViewedScopeHandle {+ /** Holds the scope open while subscribed; the last reader to leave sends its last presses. */+ readonly subscribe: (listener: () => void) => () => void;+ readonly getSnapshot: () => FileViewedOverlay;+ readonly setViewed: (path: string, viewed: boolean) => void;+}++const NO_OVERLAY: FileViewedOverlay = new Map();++interface FilesViewedScope {+ readonly target: FilesViewedTarget;+ readonly listeners: Set<() => void>;+ readonly unsubscribeAnswers: () => void;+ overlay: FileViewedOverlay;+ queued: Map<string, boolean>;+ readonly sentBy: Map<string, number>;+ requests: number;+ timer: ReturnType<typeof setTimeout> | null;+ answer: PullRequestFilesViewedResult | null;+ /**+ * The host's answer as it stood when a completed write was acknowledged, per path. The first+ * answer that differs from it is the first read that could have seen the write, which is what+ * retires the press rather than the host happening to agree with it.+ */+ readonly answeredFrom: Map<string, PullRequestFilesViewedResult | null>;+}++/**+ * Presses on one change request on one environment. The environment is part of the scope: two of+ * them can hand out the same project id, and a press made against one must never be answered for+ * by the other.+ */+export function createFilesViewedStore(deps: FilesViewedStoreDeps) {+ const scopes = new Map<string, FilesViewedScope>();+ const handles = new Map<string, FilesViewedScopeHandle>();++ const publish = (scope: FilesViewedScope, overlay: FileViewedOverlay) => {+ if (overlay === scope.overlay) return;+ scope.overlay = overlay;+ for (const listener of scope.listeners) listener();+ };++ const isLive = (key: string, scope: FilesViewedScope) => scopes.get(key) === scope;++ const settle = (scope: FilesViewedScope, answer: PullRequestFilesViewedResult | null) => {+ if (answer === scope.answer) return;+ scope.answer = answer;+ const pending = new Set([...scope.queued.keys(), ...scope.sentBy.keys()]);+ const answered = new Set<string>();+ for (const [path, from] of scope.answeredFrom) {+ if (pending.has(path) || from === answer) continue;+ answered.add(path);+ scope.answeredFrom.delete(path);+ }+ publish(+ scope,+ settleFileViewedOverlay(scope.overlay, toFileViewedStates(answer), pending, answered),+ );+ };++ const flush = (key: string, scope: FilesViewedScope) => {+ scope.timer = null;+ const batch = toFileViewedBatch(scope.queued);+ if (batch.length === 0) return;+ scope.queued = new Map();+ const request = ++scope.requests;+ for (const file of batch) scope.sentBy.set(file.path, request);+ void deps.send(scope.target, batch).then((result) => {+ const mine = batch+ .map((file) => file.path)+ .filter((path) => scope.sentBy.get(path) === request);+ for (const path of mine) scope.sentBy.delete(path);+ if (!isLive(key, scope)) {+ // The overlay this press stood in is gone, but the cached answer still predates the+ // write, and a reader coming back to this change request would be shown that.+ if (result._tag === "Success" || !isAtomCommandInterrupted(result)) {+ deps.refresh(scope.target);+ }+ return;+ }+ if (result._tag === "Failure") {+ const owned = new Set(mine.filter((path) => !scope.queued.has(path)));+ publish(scope, revertFileViewedOverlay(scope.overlay, batch, owned));+ if (owned.size > 0 && !isAtomCommandInterrupted(result)) {+ deps.reportFailure();+ deps.refresh(scope.target);+ }+ return;+ }+ // Answered for from the next read on, whatever it says. A push landing between the write+ // and that read comes back as `dismissed`, and the press must not stand over it.+ for (const path of mine) scope.answeredFrom.set(path, scope.answer);+ deps.refresh(scope.target);+ });+ };++ const acquire = (+ key: string,+ target: FilesViewedTarget,+ handle: FilesViewedScopeHandle,+ listener: () => void,+ ) => {+ // Registered from `subscribe`, which runs at commit, so a render that never commits leaves+ // nothing behind. Re-registering here also carries a handle across StrictMode's+ // subscribe-release-subscribe, so later renders keep returning it.+ if (!handles.has(key)) handles.set(key, handle);+ let scope = scopes.get(key);+ if (scope === undefined) {+ const listeners = new Set<() => void>();+ let created: FilesViewedScope | undefined;+ let initial: PullRequestFilesViewedResult | null = null;+ const unsubscribeAnswers = deps.subscribeAnswers(target, (answer) => {+ if (created === undefined) initial = answer;+ else settle(created, answer);+ });+ created = {+ target,+ listeners,+ unsubscribeAnswers,+ overlay: NO_OVERLAY,+ queued: new Map(),+ sentBy: new Map(),+ requests: 0,+ timer: null,+ answer: initial,+ answeredFrom: new Map(),+ };+ scope = created;+ scopes.set(key, scope);+ }+ const owned = scope;+ owned.listeners.add(listener);+ return () => {+ if (!owned.listeners.delete(listener) || owned.listeners.size > 0) return;+ // Leaving a change request, the environment it lives on, or the page itself records what+ // was pressed and then drops the rest, sending those last presses to the scope being left.+ if (owned.timer !== null) {+ clearTimeout(owned.timer);+ flush(key, owned);+ }+ scopes.delete(key);+ handles.delete(key);+ owned.unsubscribeAnswers();+ };+ };++ return {+ /**+ * One stable handle per open scope, so readers keep their subscription across renders. Pure+ * during render: an uncommitted handle is not cached, and any handle for a key behaves the same.+ */+ scope(target: FilesViewedTarget): FilesViewedScopeHandle {+ const key = filesViewedScopeKey(target);+ const cached = handles.get(key);+ if (cached !== undefined) return cached;+ const owned = { environmentId: target.environmentId, reference: { ...target.reference } };+ const handle: FilesViewedScopeHandle = {+ subscribe: (listener) => acquire(key, owned, handle, listener),+ getSnapshot: () => scopes.get(key)?.overlay ?? NO_OVERLAY,+ setViewed: (path, viewed) => {+ const scope = scopes.get(key);+ if (scope === undefined) return;+ scope.queued.set(path, viewed);+ publish(scope, new Map(scope.overlay).set(path, viewed));+ if (scope.timer !== null) clearTimeout(scope.timer);+ scope.timer = setTimeout(() => flush(key, scope), deps.flushDelayMs);+ },+ };+ return handle;+ },+ };+}++function filesViewedScopeKey({ environmentId, reference }: FilesViewedTarget): string {+ return JSON.stringify([+ environmentId,+ reference.projectId,+ reference.host ?? null,+ reference.expectedAccountId ?? null,+ reference.allowStale ?? null,+ reference.repository,+ reference.number,+ ]);+}++const filesViewedAtom = ({ environmentId, reference }: FilesViewedTarget) =>+ pullRequestEnvironment.filesViewed({ environmentId, input: reference });++const filesViewedStore = createFilesViewedStore({+ flushDelayMs: 400,+ subscribeAnswers: (target, onAnswer) =>+ appAtomRegistry.subscribe(+ filesViewedAtom(target),+ (result) => onAnswer(Option.getOrNull(AsyncResult.value(result))),+ { immediate: true },+ ),+ send: ({ environmentId, reference }, files) =>+ runAtomCommand(+ appAtomRegistry,+ pullRequestEnvironment.setFilesViewed,+ { environmentId, input: { ...reference, files } },+ { reportFailure: false },+ ),+ refresh: (target) => appAtomRegistry.refresh(filesViewedAtom(target)),+ reportFailure: () => toastManager.add({ type: "error", title: "Could not update viewed files" }),+});++export function filesViewedScope(target: FilesViewedTarget): FilesViewedScopeHandle {+ return filesViewedStore.scope(target);+}diff --git a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.tsindex a8199cf4936..f71b135b604 100644--- a/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts+++ b/apps/web/src/components/pullRequest/usePullRequestFilesViewed.ts@@ -1,28 +1,16 @@-import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";-import { useEffect, useEffectEvent, useRef, useState } from "react";+import { useSyncExternalStore } from "react";import { pullRequestEnvironment } from "~/state/pullRequests";import { useEnvironmentQuery } from "~/state/query";-import { useAtomCommand } from "~/state/use-atom-command";-import { useStableCallback } from "~/hooks/useStableCallback";-import { toastManager } from "../ui/toast";+import { filesViewedScope } from "./filesViewedStore";import {isFileViewed,isStaleViewedState,- revertFileViewedOverlay,- settleFileViewedOverlay,- toFileViewedBatch,toFileViewedStates,- type FileViewedOverlay,- type FileViewedStates,} from "./pullRequestFilesViewed.logic";-const FLUSH_DELAY_MS = 400;--const NO_OVERLAY: FileViewedOverlay = new Map();-export interface PullRequestFilesViewedView {readonly enabled: boolean;readonly isViewed: (path: string) => boolean;@@ -33,6 +21,14 @@ export interface PullRequestFilesViewedView {readonly refresh: () => void;}+const NO_OVERLAY = new Map<string, boolean>();+// Without this a change request that cannot record views would still be handed a scope handle.+const DISABLED_SCOPE = {+ subscribe: () => () => {},+ getSnapshot: () => NO_OVERLAY,+ setViewed: () => {},+};+export function usePullRequestFilesViewed(options: {readonly environmentId: EnvironmentId;readonly reference: PullRequestRef;@@ -42,109 +38,18 @@ export function usePullRequestFilesViewed(options: {const query = useEnvironmentQuery(enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,);- const refresh = query.refresh;const states = toFileViewedStates(query.data);- const truncated = query.data?.truncated === true;- const error = query.error;- const [overlay, setOverlay] = useState<FileViewedOverlay>(NO_OVERLAY);- const setFilesViewed = useAtomCommand(pullRequestEnvironment.setFilesViewed, {- reportFailure: false,- });-- const queued = useRef<Map<string, boolean>>(new Map());- const sentBy = useRef<Map<string, number>>(new Map());- const requests = useRef(0);- const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);-- // Project ids can repeat across environments.- const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;- const scope = useRef(scopeKey);-- // Retire presses only after a post-write read, even if an older response agrees.- const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());- const committedStates = useRef(states);-- useEffect(() => {- committedStates.current = states;- const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);- const answered = new Set<string>();- for (const [path, from] of answeredFrom.current) {- if (pending.has(path) || from === states) continue;- answered.add(path);- answeredFrom.current.delete(path);- }- setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));- }, [states]);-- // Explicit targets keep departing scopes' presses in their original scope.- const flush = (target: {- readonly environmentId: EnvironmentId;- readonly reference: PullRequestRef;- }) => {- flushTimer.current = null;- const batch = toFileViewedBatch(queued.current);- if (batch.length === 0) return;- queued.current = new Map();- const sentFrom = scope.current;- const request = ++requests.current;- for (const file of batch) sentBy.current.set(file.path, request);- void setFilesViewed({- environmentId: target.environmentId,- input: { ...target.reference, files: batch },- }).then((result) => {- const mine = batch- .map((file) => file.path)- .filter((path) => sentBy.current.get(path) === request);- for (const path of mine) sentBy.current.delete(path);- if (scope.current !== sentFrom) return;- if (result._tag === "Failure") {- const owned = new Set(mine.filter((path) => !queued.current.has(path)));- setOverlay((current) => revertFileViewedOverlay(current, batch, owned));- if (owned.size > 0 && !isAtomCommandInterrupted(result)) {- toastManager.add({ type: "error", title: "Could not update viewed files" });- refresh();- }- return;- }- // The next read can report dismissed after a push; retire presses regardless of its value.- for (const path of mine) answeredFrom.current.set(path, committedStates.current);- refresh();- });- };-- const currentTarget = useEffectEvent(() => ({ environmentId, reference }));- const flushTarget = useEffectEvent(flush);-- useEffect(() => {- const leaving = currentTarget();- scope.current = scopeKey;- return () => {- if (flushTimer.current !== null) {- clearTimeout(flushTimer.current);- flushTarget(leaving);- }- queued.current = new Map();- sentBy.current = new Map();- answeredFrom.current = new Map();- setOverlay(NO_OVERLAY);- };- }, [scopeKey]);-- const setViewed = useStableCallback((path: string, viewed: boolean) => {- setOverlay((current) => new Map(current).set(path, viewed));- queued.current.set(path, viewed);- if (flushTimer.current !== null) clearTimeout(flushTimer.current);- const target = { environmentId, reference };- flushTimer.current = setTimeout(() => flush(target), FLUSH_DELAY_MS);- });+ // Stable per scope: `setViewed` is handed to every file header the viewer draws.+ const scope = enabled ? filesViewedScope({ environmentId, reference }) : DISABLED_SCOPE;+ const overlay = useSyncExternalStore(scope.subscribe, scope.getSnapshot);return {enabled,isViewed: (path: string) => isFileViewed(path, states, overlay),isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),- setViewed,- truncated,- error,- refresh,+ setViewed: scope.setViewed,+ truncated: query.data?.truncated === true,+ error: query.error,+ refresh: query.refresh,};}diff --git a/apps/web/src/hooks/useLiveRefresh.browser.test.tsx b/apps/web/src/hooks/useLiveRefresh.browser.test.tsxnew file mode 100644index 00000000000..393ba06a872--- /dev/null+++ b/apps/web/src/hooks/useLiveRefresh.browser.test.tsx@@ -0,0 +1,65 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { act, fakeTimers, render } from "../../test/render";+import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "./useLiveRefresh";++function Probe(props: {+ readonly refresh: () => void;+ readonly viewKey: string;+ readonly enabled?: boolean;+ readonly intervalMs?: number | null;+ readonly refreshOnShow?: boolean;+}) {+ useLiveRefresh(props.refresh, {+ key: props.viewKey,+ enabled: props.enabled ?? true,+ ...(props.intervalMs !== undefined ? { intervalMs: props.intervalMs } : {}),+ ...(props.refreshOnShow !== undefined ? { refreshOnShow: props.refreshOnShow } : {}),+ });+ return null;+}++describe("useLiveRefresh", () => {+ it("with refreshOnShow, reads on every show unless it read within the floor", async () => {+ const refresh = vi.fn();+ // The first enable reads the clock.+ using _timers = fakeTimers({ now: 1_000_000 });+ const probe = (enabled: boolean) => (+ <Probe refresh={refresh} viewKey="show" enabled={enabled} refreshOnShow intervalMs={null} />+ );+ // A bare hook probe; nothing here navigates.+ await using screen = await render(probe(true), { router: false });+ expect(refresh).toHaveBeenCalledTimes(1);++ await screen.rerender(probe(false));+ await act(() => vi.advanceTimersByTime(LIVE_REFRESH_MIN_INTERVAL_MS - 1));+ await screen.rerender(probe(true));+ expect(refresh).toHaveBeenCalledTimes(1);++ await screen.rerender(probe(false));+ await act(() => vi.advanceTimersByTime(1));+ await screen.rerender(probe(true));+ expect(refresh).toHaveBeenCalledTimes(2);+ });++ it("with intervalMs null, never refreshes on a timer", async () => {+ const periodic = vi.fn();+ const untimed = vi.fn();+ // The interaction clock starts when the first view mounts.+ using _timers = fakeTimers({ now: 1_000_000 });+ await using _screen = await render(+ <>+ <Probe refresh={periodic} viewKey="periodic" intervalMs={60_000} />+ <Probe refresh={untimed} viewKey="untimed" intervalMs={null} />+ </>,+ // A bare hook probe; nothing here navigates.+ { router: false },+ );++ // Past the default 5 minute interval, but inside the 6 minute idle cutoff.+ await act(() => vi.advanceTimersByTime(5.5 * 60_000));++ expect(periodic).toHaveBeenCalledTimes(5);+ expect(untimed).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/hooks/useLiveRefresh.ts b/apps/web/src/hooks/useLiveRefresh.tsindex 7083c38723e..b355b0a91ba 100644--- a/apps/web/src/hooks/useLiveRefresh.ts+++ b/apps/web/src/hooks/useLiveRefresh.ts@@ -1,6 +1,6 @@import { useEffect, useEffectEvent, useId } from "react";-const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;+export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;const LIVE_REFRESH_INTERVAL_MS = 5 * 60_000;@@ -75,10 +75,22 @@ export function useLiveRefresh(options: {readonly enabled?: boolean;readonly key?: string;- readonly intervalMs?: number;+ /** `null` turns off the periodic refresh, for a read too costly to repeat unasked. */+ readonly intervalMs?: number | null;+ /**+ * Refresh every time the view is enabled unless it read within the floor, skipping the+ * first-read rule: for a view that stays mounted while hidden, so its mount-time read can be+ * long stale when shown.+ */+ readonly refreshOnShow?: boolean;} = {},): void {- const { enabled = true, key, intervalMs = LIVE_REFRESH_INTERVAL_MS } = options;+ const {+ enabled = true,+ key,+ intervalMs = LIVE_REFRESH_INTERVAL_MS,+ refreshOnShow = false,+ } = options;const runRefresh = useEffectEvent((viewId: string, now: number) => {if (refresh === null) return;lastRefreshedAtByView.set(viewId, now);@@ -112,7 +124,7 @@ export function useLiveRefresh(let timer: ReturnType<typeof setInterval> | undefined;const syncTimer = () => {clearInterval(timer);- timer = visible() ? setInterval(onInterval, intervalMs) : undefined;+ timer = visible() && intervalMs !== null ? setInterval(onInterval, intervalMs) : undefined;};const onVisibilityChange = () => {onArrival();@@ -123,7 +135,13 @@ export function useLiveRefresh(onArrival();syncTimer();});- onArrival();+ if (refreshOnShow) {+ const now = Date.now();+ const lastRefreshedAt = lastRefreshedAtByView.get(viewId);+ if (lastRefreshedAt === undefined || now - lastRefreshedAt >= LIVE_REFRESH_MIN_INTERVAL_MS) {+ read(now);+ }+ } else onArrival();syncTimer();window.addEventListener("focus", onArrival);document.addEventListener("visibilitychange", onVisibilityChange);@@ -133,5 +151,5 @@ export function useLiveRefresh(document.removeEventListener("visibilitychange", onVisibilityChange);stopWatchingInteraction();};- }, [enabled, viewId, intervalMs]);+ }, [enabled, viewId, intervalMs, refreshOnShow]);}diff --git a/apps/web/src/state/revisionedQuery.browser.test.tsx b/apps/web/src/state/revisionedQuery.browser.test.tsxnew file mode 100644index 00000000000..118aac4f1f2--- /dev/null+++ b/apps/web/src/state/revisionedQuery.browser.test.tsx@@ -0,0 +1,36 @@+import { RegistryContext, useAtomValue } from "@effect/atom-react";+import { Atom, AtomRegistry } from "effect/reactivity";+import { describe, expect, it, vi } from "vite-plus/test";++import { render } from "../../test/render";+import { revisionedQuery } from "./revisionedQuery";++describe("revisionedQuery in React", () => {+ it("refetches for a new revision without updating a component during render", async () => {+ let fetches = 0;+ const query = Atom.make(() => {+ fetches += 1;+ return fetches;+ }).pipe(Atom.keepAlive);+ const registry = AtomRegistry.make();+ function Reader({ revision }: { revision: string }) {+ return <span>fetch {useAtomValue(revisionedQuery(query, revision))}</span>;+ }+ const ui = (revision: string) => (+ <RegistryContext.Provider value={registry}>+ <Reader revision={revision} />+ </RegistryContext.Provider>+ );+ using consoleError = vi.spyOn(console, "error");+ // A bare atom reader: no links or navigation to route.+ await using screen = await render(ui("mutation-1"), { router: false });+ await expect.element(screen.getByText("fetch 1")).toBeInTheDocument();++ await screen.rerender(ui("mutation-2"));++ await expect.element(screen.getByText("fetch 2")).toBeInTheDocument();+ expect(consoleError.mock.calls.map(([message]) => String(message))).not.toContainEqual(+ expect.stringContaining("Cannot update a component"),+ );+ });+});diff --git a/apps/web/src/state/revisionedQuery.test.ts b/apps/web/src/state/revisionedQuery.test.tsindex 055c37ddbc7..7dda15de230 100644--- a/apps/web/src/state/revisionedQuery.test.ts+++ b/apps/web/src/state/revisionedQuery.test.ts@@ -19,8 +19,10 @@ function setup() {fetches += 1;return fetches;}).pipe(Atom.keepAlive);- const mount = (revision: string | null | undefined) => {+ const mount = async (revision: string | null | undefined) => {const release = registry.mount(revisionedQuery(query, revision));+ // A stale read refetches in a microtask, after the render that read it.+ await Promise.resolve();return () => {release();for (const task of scheduled.splice(0)) task();@@ -30,75 +32,87 @@ function setup() {}describe("revisionedQuery", () => {- it("refetches once per new revision, not on the first read or a remount", () => {+ it("refetches once per new revision, not on the first read or a remount", async () => {const { mount, fetches } = setup();- mount("mutation-1")();+ (await mount("mutation-1"))();expect(fetches()).toBe(1);- mount("mutation-1")();+ (await mount("mutation-1"))();expect(fetches()).toBe(1);- mount("mutation-2")();+ (await mount("mutation-2"))();expect(fetches()).toBe(2);});- it("does not ping-pong while readers of the old and new revision overlap", () => {+ it("does not ping-pong while readers of the old and new revision overlap", async () => {const { mount, fetches } = setup();- const releaseOld = mount("mutation-1");- const releaseNew = mount("mutation-2");+ const releaseOld = await mount("mutation-1");+ const releaseNew = await mount("mutation-2");expect(fetches()).toBe(2);releaseOld();releaseNew();});- it("refetches when an earlier revision is read again", () => {+ it("refetches when an earlier revision is read again", async () => {const { mount, fetches } = setup();- mount("mutation-1")();- mount("mutation-2")();- mount("mutation-1")();+ (await mount("mutation-1"))();+ (await mount("mutation-2"))();+ (await mount("mutation-1"))();expect(fetches()).toBe(3);});- it("refetches a query another reader already cached on its first revisioned read", () => {+ it("refetches a query another reader already cached on its first revisioned read", async () => {const { mount, fetches } = setup();- mount(undefined)();+ (await mount(undefined))();expect(fetches()).toBe(1);- mount("mutation-1")();+ (await mount("mutation-1"))();expect(fetches()).toBe(2);- mount("mutation-1")();+ (await mount("mutation-1"))();expect(fetches()).toBe(2);});- it("does not refetch a cached query on a first read before any workspace change", () => {+ it("does not refetch a cached query on a first read before any workspace change", async () => {const { mount, fetches } = setup();- mount(undefined)();- mount(null)();+ (await mount(undefined))();+ (await mount(null))();expect(fetches()).toBe(1);});- it("leaves the query alone when read without a revision", () => {+ it("leaves the query alone when read without a revision", async () => {const { mount, query, fetches } = setup();- mount("mutation-1")();+ (await mount("mutation-1"))();expect(revisionedQuery(query, undefined)).toBe(query);- mount(undefined)();- mount("mutation-1")();+ (await mount(undefined))();+ (await mount("mutation-1"))();expect(fetches()).toBe(1);});- it("refetches the query when the reader is refreshed", () => {+ it("refetches the query when the reader is refreshed", async () => {const { registry, query, mount, fetches } = setup();- const release = mount("mutation-1");+ const release = await mount("mutation-1");registry.refresh(revisionedQuery(query, "mutation-1"));expect(fetches()).toBe(2);release();});++ it("drops a pending refetch when the registry is disposed before it runs", async () => {+ const { registry, query, mount } = setup();++ (await mount("mutation-1"))();+ const release = registry.mount(revisionedQuery(query, "mutation-2"));+ release();+ registry.dispose();++ // A refetch that ran now would throw "registry is disposed" as an uncaught error.+ await Promise.resolve();+ });});diff --git a/apps/web/src/state/revisionedQuery.ts b/apps/web/src/state/revisionedQuery.tsindex e7832d3ca56..73e18b36161 100644--- a/apps/web/src/state/revisionedQuery.ts+++ b/apps/web/src/state/revisionedQuery.ts@@ -26,7 +26,15 @@ const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>: // A reader without a revision may have cached it before the latest// workspace change; a query nobody has read yet fetches fresh anyway.revision !== null && get.registry.getNodes().has(queryKey(query));- if (stale) get.refresh(query);+ // Deferred: this builds while React renders, and a refresh would synchronously+ // re-render the query's other readers, which React rejects.+ if (stale) {+ const registry = get.registry;+ queueMicrotask(() => {+ // No node, as after the registry is disposed: nothing cached to refetch.+ if (registry.getNodes().has(queryKey(query))) registry.refresh(query);+ });+ }revisions.set(query, revision);}return get(query);