Skip to content
TypeScript

refactor(web): file breadcrumb menus refetch on a new workspace change, not on every open (#25377)

Julius Marmingea2404082424b
diff --git a/apps/web/src/components/files/FileBreadcrumbs.tsx b/apps/web/src/components/files/FileBreadcrumbs.tsx
index f9927c34360..a2f2120a2db 100644
--- a/apps/web/src/components/files/FileBreadcrumbs.tsx
+++ b/apps/web/src/components/files/FileBreadcrumbs.tsx
@@ -17,7 +17,6 @@ import {
} from "~/components/ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { useTheme } from "~/hooks/useTheme";
-import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
import { cn } from "~/lib/utils";
import { isHostPath } from "@t3tools/shared/path";
@@ -85,12 +84,12 @@ function BreadcrumbMenuContent(props: {
readonly rootPath: string;
readonly workspaceMutationId: string | null;
}) {
- const entriesQuery = useProjectEntriesQuery(props.environmentId, props.cwd, props.directoryPath);
- useWorkspaceMutationRefresh({
- mutationId: props.workspaceMutationId,
- refresh: entriesQuery.refresh,
- resourceKey: `files:${props.environmentId}:${props.cwd}`,
- });
+ const entriesQuery = useProjectEntriesQuery(
+ props.environmentId,
+ props.cwd,
+ props.directoryPath,
+ props.workspaceMutationId,
+ );
const { resolvedTheme } = useTheme();
const entries = entriesQuery.data?.entries ?? [];
const entriesTruncated = entriesQuery.data?.truncated ?? false;
diff --git a/apps/web/src/components/files/projectFilesQueryState.test.tsx b/apps/web/src/components/files/projectFilesQueryState.test.tsx
index 6f6fbece92e..797ed4fa2ac 100644
--- a/apps/web/src/components/files/projectFilesQueryState.test.tsx
+++ b/apps/web/src/components/files/projectFilesQueryState.test.tsx
@@ -161,6 +161,31 @@ describe("project query refresh", () => {
}
});
+ it("refetches a listing when the workspace mutation changes, not when it is first read", () => {
+ let fetches = 0;
+ const listing = Atom.make(() => {
+ fetches += 1;
+ return AsyncResult.success({ entries: [], truncated: false });
+ }).pipe(Atom.keepAlive);
+ projectMocks.listEntries.mockReturnValue(listing);
+ const registry = AtomRegistry.make();
+ atomHooks.registry = registry;
+ const read = (mutationId: string | null) =>
+ useProjectEntriesQuery(environmentId, "/repo", "src", mutationId);
+
+ try {
+ read("mutation-1");
+ read("mutation-1");
+ expect(fetches).toBe(1);
+
+ read("mutation-2");
+ expect(fetches).toBe(2);
+ } finally {
+ registry.dispose();
+ atomHooks.registry = null;
+ }
+ });
+
it("replaces an in-flight initial read when a workspace mutation arrives", async () => {
const requests: Array<ReturnType<typeof deferred<ProjectReadFileResult>>> = [];
const readAtom = Atom.make(
diff --git a/apps/web/src/components/files/projectFilesQueryState.ts b/apps/web/src/components/files/projectFilesQueryState.ts
index df517965b53..3da7fdd6da8 100644
--- a/apps/web/src/components/files/projectFilesQueryState.ts
+++ b/apps/web/src/components/files/projectFilesQueryState.ts
@@ -16,6 +16,7 @@ import { useFilesystemReadAccess } from "~/state/filesystem";
import { projectEnvironment } from "~/state/projects";
import { useProjectPathSearch } from "~/state/queries";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
+import { revisionedQuery } from "~/state/revisionedQuery";
const EMPTY_PROJECT_FILE_PATH = "";
const EMPTY_PROJECT_ENTRIES_QUERY_ATOM = Atom.make(
@@ -190,17 +191,19 @@ function errorMessage(cause: unknown): string | null {
const isProjectReadFileError = Schema.is(ProjectReadFileError);
+/** `revision` is the workspace mutation id; a new one refetches the listing. */
export function useProjectEntriesQuery(
environmentId: EnvironmentId,
cwd: string,
directoryPath?: string,
+ revision?: string | null,
): ProjectQueryState<ProjectListEntriesResult> {
const fileAccess = useFilesystemReadAccess(environmentId);
const { canReadFiles } = fileAccess;
const atom = canReadFiles
? getProjectEntriesQueryAtom(environmentId, cwd, directoryPath)
: EMPTY_PROJECT_ENTRIES_QUERY_ATOM;
- const result = useAtomValue(atom);
+ const result = useAtomValue(revisionedQuery(atom, canReadFiles ? revision : undefined));
const refreshAtom = useAtomRefresh(atom);
const refresh = () => refreshAtom();
return {
diff --git a/apps/web/src/state/revisionedQuery.test.ts b/apps/web/src/state/revisionedQuery.test.ts
new file mode 100644
index 00000000000..055c37ddbc7
--- /dev/null
+++ b/apps/web/src/state/revisionedQuery.test.ts
@@ -0,0 +1,104 @@
+import { Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it } from "vite-plus/test";
+
+import { revisionedQuery } from "./revisionedQuery";
+
+// A stand-in query that counts its fetches.
+function setup() {
+ let fetches = 0;
+ // Node removal runs on the registry's scheduler; releasing flushes it so the
+ // next mount of the same revision builds a fresh node, as a React remount does.
+ const scheduled: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ scheduled.push(task);
+ return () => {};
+ },
+ });
+ const query = Atom.make(() => {
+ fetches += 1;
+ return fetches;
+ }).pipe(Atom.keepAlive);
+ const mount = (revision: string | null | undefined) => {
+ const release = registry.mount(revisionedQuery(query, revision));
+ return () => {
+ release();
+ for (const task of scheduled.splice(0)) task();
+ };
+ };
+ return { registry, query, mount, fetches: () => fetches };
+}
+
+describe("revisionedQuery", () => {
+ it("refetches once per new revision, not on the first read or a remount", () => {
+ const { mount, fetches } = setup();
+
+ mount("mutation-1")();
+ expect(fetches()).toBe(1);
+
+ mount("mutation-1")();
+ expect(fetches()).toBe(1);
+
+ mount("mutation-2")();
+ expect(fetches()).toBe(2);
+ });
+
+ it("does not ping-pong while readers of the old and new revision overlap", () => {
+ const { mount, fetches } = setup();
+
+ const releaseOld = mount("mutation-1");
+ const releaseNew = mount("mutation-2");
+ expect(fetches()).toBe(2);
+ releaseOld();
+ releaseNew();
+ });
+
+ it("refetches when an earlier revision is read again", () => {
+ const { mount, fetches } = setup();
+
+ mount("mutation-1")();
+ mount("mutation-2")();
+ mount("mutation-1")();
+ expect(fetches()).toBe(3);
+ });
+
+ it("refetches a query another reader already cached on its first revisioned read", () => {
+ const { mount, fetches } = setup();
+
+ mount(undefined)();
+ expect(fetches()).toBe(1);
+
+ mount("mutation-1")();
+ expect(fetches()).toBe(2);
+
+ mount("mutation-1")();
+ expect(fetches()).toBe(2);
+ });
+
+ it("does not refetch a cached query on a first read before any workspace change", () => {
+ const { mount, fetches } = setup();
+
+ mount(undefined)();
+ mount(null)();
+ expect(fetches()).toBe(1);
+ });
+
+ it("leaves the query alone when read without a revision", () => {
+ const { mount, query, fetches } = setup();
+
+ mount("mutation-1")();
+ expect(revisionedQuery(query, undefined)).toBe(query);
+ mount(undefined)();
+ mount("mutation-1")();
+ expect(fetches()).toBe(1);
+ });
+
+ it("refetches the query when the reader is refreshed", () => {
+ const { registry, query, mount, fetches } = setup();
+
+ const release = mount("mutation-1");
+ registry.refresh(revisionedQuery(query, "mutation-1"));
+ expect(fetches()).toBe(2);
+ release();
+ });
+});
diff --git a/apps/web/src/state/revisionedQuery.ts b/apps/web/src/state/revisionedQuery.ts
new file mode 100644
index 00000000000..e7832d3ca56
--- /dev/null
+++ b/apps/web/src/state/revisionedQuery.ts
@@ -0,0 +1,66 @@
+import * as Option from "effect/Option";
+import { Atom, type AtomRegistry } from "effect/reactivity";
+
+// Outside the nodes: a node is dropped once unmounted, and the next read must
+// still compare against the revision the query was last read under.
+const readRevisions = new WeakMap<AtomRegistry.AtomRegistry, WeakMap<object, string | null>>();
+
+// The registry keys serializable atoms' nodes by their key, not the atom.
+const queryKey = (query: Atom.Atom<unknown>) =>
+ Atom.isSerializable(query) ? query[Atom.SerializableTypeId].key : query;
+
+const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>
+ Atom.family((revision: string | null) =>
+ Atom.readable(
+ (get) => {
+ // Only a node's first build compares: a node still mounted under the old
+ // revision rebuilds when the query refetches, and must not refetch it again.
+ if (Option.isNone(get.self())) {
+ let revisions = readRevisions.get(get.registry);
+ if (revisions === undefined) {
+ revisions = new WeakMap();
+ readRevisions.set(get.registry, revisions);
+ }
+ const stale = revisions.has(query)
+ ? revisions.get(query) !== revision
+ : // 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);
+ revisions.set(query, revision);
+ }
+ return get(query);
+ },
+ // Refreshing the reader refetches the query it reads.
+ (refresh) => refresh(query),
+ ),
+ );
+
+// Held as long as the query lives, so one (query, revision) pair keeps one atom; an
+// `Atom.family` would hold the inner family only weakly and could swap the atom under a reader.
+const revisionedFamilies = new WeakMap<
+ Atom.Atom<unknown>,
+ ReturnType<typeof makeRevisionedFamily>
+>();
+const revisionedFamily = (query: Atom.Atom<unknown>) => {
+ let family = revisionedFamilies.get(query);
+ if (family === undefined) {
+ family = makeRevisionedFamily(query);
+ revisionedFamilies.set(query, family);
+ }
+ return family;
+};
+
+/**
+ * Reads `query` under a workspace revision (latest mutation id); a different
+ * revision than the last read refetches it. The first read records the revision,
+ * and refetches only a query that a reader without a revision already cached.
+ * `undefined` reads without taking part, for readers that must not refetch now.
+ */
+export function revisionedQuery<A>(
+ query: Atom.Atom<A>,
+ revision: string | null | undefined,
+): Atom.Atom<A> {
+ if (revision === undefined) return query;
+ return revisionedFamily(query)(revision) as Atom.Atom<A>;
+}