Open History to see the last commit
1import {
2 EnvironmentId,
3 type ProjectListEntriesResult,
4 ProjectReadFileError,
5 type ProjectReadFileResult,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import { Atom, AtomRegistry } from "effect/reactivity";
9import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
10
11const projectMocks = vi.hoisted(() => ({
12 listEntries: vi.fn(),
13 optimisticFile: vi.fn(),
14 readFile: vi.fn(),
15}));
16
17const atomHooks = vi.hoisted(() => ({
18 registry: null as {
19 get(atom: object): unknown;
20 refresh(atom: object): void;
21 } | null,
22}));
23
24const reactHooks = vi.hoisted(() => {
25 let cursor = 0;
26 let refs: Array<{ current: unknown }> = [];
27 const nextIndex = () => cursor++;
28
29 return {
30 beginRender() {
31 cursor = 0;
32 },
33 reset() {
34 cursor = 0;
35 refs = [];
36 },
37 useCallback<A>(callback: A): A {
38 nextIndex();
39 return callback;
40 },
41 useEffect(effect: () => void): void {
42 nextIndex();
43 effect();
44 },
45 useRef<A>(initialValue: A): { current: A } {
46 const index = nextIndex();
47 refs[index] ??= { current: initialValue };
48 return refs[index] as { current: A };
49 },
50 };
51});
52
53vi.mock("@effect/atom-react", () => ({
54 useAtomRefresh: (atom: object) => () => {
55 atomHooks.registry?.refresh(atom);
56 },
57 useAtomValue: (atom: object) => atomHooks.registry?.get(atom),
58}));
59
60vi.mock("react", async (importOriginal) => {
61 const actual = await importOriginal<typeof import("react")>();
62 return {
63 ...actual,
64 useCallback: reactHooks.useCallback,
65 useEffect: reactHooks.useEffect,
66 useRef: reactHooks.useRef,
67 };
68});
69
70vi.mock("~/state/projects", () => ({
71 projectEnvironment: projectMocks,
72}));
73
74vi.mock("~/state/queries", () => ({
75 useProjectPathSearch: vi.fn(),
76}));
77
78import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
79import { useProjectEntriesQuery, useProjectFileQuery } from "./projectFilesQueryState";
80
81const environmentId = EnvironmentId.make("environment-1");
82
83function deferred<A>() {
84 let resolve!: (value: A) => void;
85 const promise = new Promise<A>((complete) => {
86 resolve = complete;
87 });
88 return { promise, resolve };
89}
90
91function file(contents: string): ProjectReadFileResult {
92 return {
93 relativePath: "src/preview.ts",
94 contents,
95 byteLength: contents.length,
96 truncated: false,
97 };
98}
99
100function projectEntries(paths: readonly string[]): ProjectListEntriesResult {
101 return {
102 entries: paths.map((path) => ({ path, kind: "file" })),
103 truncated: false,
104 };
105}
106
107async function flushEffects(): Promise<void> {
108 await Promise.resolve();
109 await Promise.resolve();
110 await Promise.resolve();
111}
112
113describe("project query refresh", () => {
114 beforeEach(() => {
115 projectMocks.listEntries.mockReset();
116 projectMocks.optimisticFile.mockReset();
117 projectMocks.readFile.mockReset();
118 reactHooks.reset();
119 });
120
121 it("replaces an in-flight initial read when a workspace mutation arrives", async () => {
122 const requests: Array<ReturnType<typeof deferred<ProjectReadFileResult>>> = [];
123 const readAtom = Atom.make(
124 Effect.promise(() => {
125 const request = deferred<ProjectReadFileResult>();
126 requests.push(request);
127 return request.promise;
128 }),
129 ).pipe(Atom.swr({ staleTime: 30_000, revalidateOnMount: true }));
130 const registry = AtomRegistry.make();
131 const unmount = registry.mount(readAtom);
132 projectMocks.readFile.mockReturnValue(readAtom);
133 projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
134 atomHooks.registry = registry;
135 let renderedContents: string | null = null;
136
137 const render = (mutationId: string | null) => {
138 reactHooks.beginRender();
139 const query = useProjectFileQuery(environmentId, "/repo", "src/preview.ts");
140 renderedContents = query.data?.contents ?? null;
141 useWorkspaceMutationRefresh({
142 mutationId,
143 refresh: query.refresh,
144 resourceKey: "file:environment-1:/repo:src/preview.ts",
145 });
146 };
147
148 try {
149 render(null);
150 await flushEffects();
151 expect(requests).toHaveLength(1);
152
153 render("mutation-1");
154 await flushEffects();
155 expect(requests).toHaveLength(2);
156
157 requests[1]!.resolve(file("fresh"));
158 await flushEffects();
159 render("mutation-1");
160 expect(renderedContents).toBe("fresh");
161
162 requests[0]!.resolve(file("stale"));
163 await flushEffects();
164 render("mutation-1");
165 expect(renderedContents).toBe("fresh");
166 } finally {
167 unmount();
168 registry.dispose();
169 atomHooks.registry = null;
170 }
171 });
172
173 it("revalidates cached entries when a workspace mutation is observed after mounting", async () => {
174 const requests: Array<ReturnType<typeof deferred<ProjectListEntriesResult>>> = [];
175 const entriesAtom = Atom.make(
176 Effect.promise(() => {
177 const request = deferred<ProjectListEntriesResult>();
178 requests.push(request);
179 return request.promise;
180 }),
181 ).pipe(Atom.swr({ staleTime: 30_000, revalidateOnMount: true }));
182 const registry = AtomRegistry.make();
183 const unmount = registry.mount(entriesAtom);
184 projectMocks.listEntries.mockReturnValue(entriesAtom);
185 atomHooks.registry = registry;
186 let renderedPaths: readonly string[] = [];
187
188 const render = (mutationId: string | null) => {
189 reactHooks.beginRender();
190 const query = useProjectEntriesQuery(environmentId, "/repo");
191 renderedPaths = query.data?.entries.map((entry) => entry.path) ?? [];
192 useWorkspaceMutationRefresh({
193 mutationId,
194 refresh: query.refresh,
195 resourceKey: "files:environment-1:/repo",
196 });
197 };
198
199 try {
200 await flushEffects();
201 expect(requests).toHaveLength(1);
202 requests[0]!.resolve(projectEntries(["src/old.ts"]));
203 await flushEffects();
204
205 render("mutation-1");
206 expect(renderedPaths).toEqual(["src/old.ts"]);
207 await flushEffects();
208 expect(requests).toHaveLength(2);
209
210 requests[1]!.resolve(projectEntries(["src/new.ts"]));
211 await flushEffects();
212 render("mutation-1");
213 expect(renderedPaths).toEqual(["src/new.ts"]);
214 expect(requests).toHaveLength(2);
215 } finally {
216 unmount();
217 registry.dispose();
218 atomHooks.registry = null;
219 }
220 });
221
222 it("does not issue a file read for a disabled image preview", async () => {
223 const requests: Array<ReturnType<typeof deferred<ProjectReadFileResult>>> = [];
224 const readAtom = Atom.make(
225 Effect.promise(() => {
226 const request = deferred<ProjectReadFileResult>();
227 requests.push(request);
228 return request.promise;
229 }),
230 );
231 const registry = AtomRegistry.make();
232 projectMocks.readFile.mockReturnValue(readAtom);
233 projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
234 atomHooks.registry = registry;
235
236 try {
237 reactHooks.beginRender();
238 const query = useProjectFileQuery(environmentId, "/repo", "preview.png", false);
239 useWorkspaceMutationRefresh({
240 enabled: false,
241 mutationId: "mutation-1",
242 refresh: query.refresh,
243 resourceKey: "file:environment-1:/repo:preview.png",
244 });
245 await flushEffects();
246
247 expect(projectMocks.readFile).not.toHaveBeenCalled();
248 expect(requests).toHaveLength(0);
249 } finally {
250 registry.dispose();
251 atomHooks.registry = null;
252 }
253 });
254
255 it("reports a directory named like an image as not a file", async () => {
256 const readAtom = Atom.make(
257 Effect.fail(
258 new ProjectReadFileError({
259 cwd: "/repo",
260 relativePath: "assets.png",
261 failure: "path_not_file",
262 }),
263 ),
264 );
265 const registry = AtomRegistry.make();
266 const unmount = registry.mount(readAtom);
267 projectMocks.readFile.mockReturnValue(readAtom);
268 projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
269 atomHooks.registry = registry;
270
271 try {
272 await flushEffects();
273 reactHooks.beginRender();
274 const query = useProjectFileQuery(environmentId, "/repo", "assets.png");
275 expect(query.isNotFile).toBe(true);
276 expect(query.data).toBeNull();
277 } finally {
278 unmount();
279 registry.dispose();
280 atomHooks.registry = null;
281 }
282 });
283
284 it("reports a directory read as not a file", async () => {
285 const readAtom = Atom.make(
286 Effect.fail(
287 new ProjectReadFileError({
288 cwd: "/repo",
289 relativePath: ".agents/skills",
290 failure: "path_not_file",
291 }),
292 ),
293 );
294 const registry = AtomRegistry.make();
295 const unmount = registry.mount(readAtom);
296 projectMocks.readFile.mockReturnValue(readAtom);
297 projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
298 atomHooks.registry = registry;
299
300 try {
301 await flushEffects();
302 reactHooks.beginRender();
303 const query = useProjectFileQuery(environmentId, "/repo", ".agents/skills");
304 expect(query.isNotFile).toBe(true);
305 expect(query.data).toBeNull();
306 } finally {
307 unmount();
308 registry.dispose();
309 atomHooks.registry = null;
310 }
311 });
312});