Open History to see the last commit
1import {
2 AuthFilesystemReadScope,
3 EnvironmentId,
4 type AuthSessionState,
5 type ProjectFileFailure,
6 ProjectReadFileError,
7 type ProjectReadFileResult,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
13import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
14
15const authorizationMocks = vi.hoisted(() => ({
16 sessionAtom: null as Atom.Atom<
17 AsyncResult.AsyncResult<Pick<AuthSessionState, "authenticated" | "scopes">, Error>
18 > | null,
19 phase: "connected" as "connected" | "offline",
20}));
21
22vi.mock("~/state/session", () => ({
23 environmentSession: { sessionStateAtom: () => authorizationMocks.sessionAtom },
24}));
25
26vi.mock("~/state/presentation", () => ({
27 useEnvironmentPresentation: () => ({
28 isReady: true,
29 presentation: { connection: { phase: authorizationMocks.phase, error: null } },
30 }),
31}));
32
33const projectMocks = vi.hoisted(() => ({
34 listEntries: vi.fn(),
35 optimisticFile: vi.fn(),
36 readFile: vi.fn(),
37}));
38
39const atomHooks = vi.hoisted(() => ({
40 registry: null as {
41 get(atom: object): unknown;
42 refresh(atom: object): void;
43 } | null,
44}));
45
46const reactHooks = vi.hoisted(() => {
47 let cursor = 0;
48 let refs: Array<{ current: unknown }> = [];
49 const nextIndex = () => cursor++;
50
51 return {
52 beginRender() {
53 cursor = 0;
54 },
55 reset() {
56 cursor = 0;
57 refs = [];
58 },
59 useCallback<A>(callback: A): A {
60 nextIndex();
61 return callback;
62 },
63 useEffect(effect: () => void): void {
64 nextIndex();
65 effect();
66 },
67 useRef<A>(initialValue: A): { current: A } {
68 const index = nextIndex();
69 refs[index] ??= { current: initialValue };
70 return refs[index] as { current: A };
71 },
72 };
73});
74
75vi.mock("@effect/atom-react", () => ({
76 useAtomRefresh: (atom: object) => () => {
77 atomHooks.registry?.refresh(atom);
78 },
79 useAtomValue: (atom: object) => atomHooks.registry?.get(atom),
80}));
81
82vi.mock("react", async (importOriginal) => {
83 const actual = await importOriginal<typeof import("react")>();
84 return {
85 ...actual,
86 useCallback: reactHooks.useCallback,
87 useEffect: reactHooks.useEffect,
88 useMemo: <A,>(factory: () => A) => factory(),
89 useRef: reactHooks.useRef,
90 };
91});
92
93vi.mock("~/state/projects", () => ({
94 projectEnvironment: projectMocks,
95}));
96
97vi.mock("~/state/queries", () => ({
98 useProjectPathSearch: vi.fn(),
99}));
100
101import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
102import { useProjectEntriesQuery, useProjectFileQuery } from "./projectFilesQueryState";
103
104const environmentId = EnvironmentId.make("environment-1");
105
106function deferred<A>() {
107 let resolve!: (value: A) => void;
108 const promise = new Promise<A>((complete) => {
109 resolve = complete;
110 });
111 return { promise, resolve };
112}
113
114function file(contents: string): ProjectReadFileResult {
115 return {
116 relativePath: "src/preview.ts",
117 contents,
118 byteLength: contents.length,
119 truncated: false,
120 };
121}
122
123async function flushEffects(): Promise<void> {
124 await Promise.resolve();
125 await Promise.resolve();
126 await Promise.resolve();
127}
128
129describe("project query refresh", () => {
130 beforeEach(() => {
131 authorizationMocks.sessionAtom = Atom.make(
132 AsyncResult.success({ authenticated: true, scopes: [AuthFilesystemReadScope] }),
133 );
134 authorizationMocks.phase = "connected";
135 projectMocks.listEntries.mockReset();
136 projectMocks.optimisticFile.mockReset();
137 projectMocks.readFile.mockReset();
138 reactHooks.reset();
139 });
140
141 it("does not query or expose optimistic file contents without read permission", () => {
142 authorizationMocks.sessionAtom = Atom.make(
143 AsyncResult.success({ authenticated: true, scopes: [] }),
144 );
145 const registry = AtomRegistry.make();
146 atomHooks.registry = registry;
147 projectMocks.optimisticFile.mockReturnValue(Atom.make({ data: file("cached contents") }));
148 try {
149 const query = useProjectFileQuery(environmentId, "/repo", "src/preview.ts");
150 expect(projectMocks.readFile).not.toHaveBeenCalled();
151 expect(query.data).toBeNull();
152 expect(query.error).toBe("This connection cannot read host files.");
153 expect(query.isPending).toBe(false);
154 const entries = useProjectEntriesQuery(environmentId, "/repo");
155 expect(projectMocks.listEntries).not.toHaveBeenCalled();
156 expect(entries.data).toBeNull();
157 expect(entries.error).toBe("This connection cannot read host files.");
158 expect(entries.isPending).toBe(false);
159 } finally {
160 registry.dispose();
161 atomHooks.registry = null;
162 }
163 });
164
165 it("refetches a listing when the workspace mutation changes, not when it is first read", async () => {
166 let fetches = 0;
167 const listing = Atom.make(() => {
168 fetches += 1;
169 return AsyncResult.success({ entries: [], truncated: false });
170 }).pipe(Atom.keepAlive);
171 projectMocks.listEntries.mockReturnValue(listing);
172 const registry = AtomRegistry.make();
173 atomHooks.registry = registry;
174 const read = (mutationId: string | null) =>
175 useProjectEntriesQuery(environmentId, "/repo", "src", mutationId);
176
177 try {
178 read("mutation-1");
179 read("mutation-1");
180 expect(fetches).toBe(1);
181
182 read("mutation-2");
183 // The refetch runs after the render that read the new revision; a reader that is not
184 // subscribed sees it on its next read.
185 await Promise.resolve();
186 read("mutation-2");
187 expect(fetches).toBe(2);
188 } finally {
189 registry.dispose();
190 atomHooks.registry = null;
191 }
192 });
193
194 it("replaces an in-flight initial read when a workspace mutation arrives", async () => {
195 const requests: Array<ReturnType<typeof deferred<ProjectReadFileResult>>> = [];
196 const readAtom = Atom.make(
197 Effect.promise(() => {
198 const request = deferred<ProjectReadFileResult>();
199 requests.push(request);
200 return request.promise;
201 }),
202 ).pipe(Atom.swr({ staleTime: 30_000, revalidateOnMount: true }));
203 const registry = AtomRegistry.make();
204 const unmount = registry.mount(readAtom);
205 projectMocks.readFile.mockReturnValue(readAtom);
206 projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
207 atomHooks.registry = registry;
208 let renderedContents: string | null = null;
209
210 const render = (mutationId: string | null) => {
211 reactHooks.beginRender();
212 const query = useProjectFileQuery(environmentId, "/repo", "src/preview.ts");
213 expect(query.readError).toBeNull();
214 renderedContents = query.data?.contents ?? null;
215 useWorkspaceMutationRefresh({
216 mutationId,
217 refresh: query.refresh,
218 resourceKey: "file:environment-1:/repo:src/preview.ts",
219 });
220 };
221
222 try {
223 render(null);
224 await flushEffects();
225 expect(requests).toHaveLength(1);
226
227 render("mutation-1");
228 await flushEffects();
229 expect(requests).toHaveLength(2);
230
231 requests[1]!.resolve(file("fresh"));
232 await flushEffects();
233 render("mutation-1");
234 expect(renderedContents).toBe("fresh");
235
236 requests[0]!.resolve(file("stale"));
237 await flushEffects();
238 render("mutation-1");
239 expect(renderedContents).toBe("fresh");
240 } finally {
241 unmount();
242 registry.dispose();
243 atomHooks.registry = null;
244 }
245 });
246
247 it("confirms files from reads and preserves that identity until a definitive folder result", () => {
248 const contents = file("# readme");
249 const success = AsyncResult.success(contents);
250 const failure = (kind: ProjectFileFailure, cached = false) =>
251 AsyncResult.failure(
252 Cause.fail(
253 new ProjectReadFileError({ cwd: "/repo", relativePath: "src/preview.ts", failure: kind }),
254 ),
255 { previousSuccess: cached ? Option.some(success) : Option.none() },
256 );
257 const states = [
258 ["initial read", AsyncResult.initial(true), false, false, null],
259 ["unknown path", failure("operation_failed"), false, false, null],
260 ["binary file", failure("binary_file"), true, false, null],
261 ["read success", success, true, false, contents],
262 ["pending refresh", AsyncResult.waiting(success), true, false, contents],
263 ["transient refresh failure", failure("operation_failed", true), true, false, contents],
264 ["became a folder", failure("path_not_file", true), false, true, contents],
265 ] as const;
266 const readAtom = Atom.make<
267 AsyncResult.AsyncResult<ProjectReadFileResult, ProjectReadFileError>
268 >(AsyncResult.initial(true));
269 const registry = AtomRegistry.make();
270 const unmount = registry.mount(readAtom);
271 projectMocks.readFile.mockReturnValue(readAtom);
272 projectMocks.optimisticFile.mockReturnValue(Atom.make(null));
273 atomHooks.registry = registry;
274
275 try {
276 for (const [label, result, isFile, isNotFile, data] of states) {
277 registry.set(readAtom, result);
278 reactHooks.beginRender();
279 const query = useProjectFileQuery(environmentId, "/repo", "src/preview.ts");
280 expect(query.isFile, label).toBe(isFile);
281 expect(query.isNotFile, label).toBe(isNotFile);
282 expect(query.data, label).toBe(data);
283 expect(query.isPending, label).toBe(result.waiting);
284 }
285 } finally {
286 unmount();
287 registry.dispose();
288 atomHooks.registry = null;
289 }
290 });
291});