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