Open History to see the last commit
1import {
2 FileFinder,
3 type FileItem,
4 type GrepCursor,
5 type GrepOptions,
6 type GrepResult,
7} from "@ff-labs/fff-node";
8import { afterEach, expect, it } from "@effect/vitest";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import { vi } from "vite-plus/test";
13
14import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
15
16afterEach(() => {
17 vi.restoreAllMocks();
18});
19
20function fileItem(relativePath: string): FileItem {
21 return {
22 relativePath,
23 fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
24 size: 1,
25 modified: 0,
26 accessFrecencyScore: 0,
27 modificationFrecencyScore: 0,
28 totalFrecencyScore: 0,
29 gitStatus: "clean",
30 };
31}
32
33it.effect("filters image searches before applying the result limit", () =>
34 Effect.scoped(
35 Effect.gen(function* () {
36 const items = [
37 ...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)),
38 fileItem("public/icon.svg"),
39 ];
40 const fileSearch = vi.fn(() => ({
41 ok: true as const,
42 value: {
43 items,
44 scores: [],
45 totalMatched: items.length,
46 totalFiles: items.length,
47 },
48 }));
49 const finder = {
50 destroy: vi.fn(),
51 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
52 fileSearch,
53 } as unknown as FileFinder;
54 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
55
56 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
57 const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true);
58 const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true);
59
60 expect(resultWithoutKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
61 expect(resultWithDirectoryKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
62 expect(fileSearch).toHaveBeenCalledTimes(2);
63 expect(fileSearch).toHaveBeenCalledWith("", { pageSize: 25_002 });
64 }),
65 ),
66);
67
68it.effect("preserves unexpected FileFinder creation failures", () =>
69 Effect.gen(function* () {
70 const cause = new Error("native initialization failed");
71 vi.spyOn(FileFinder, "create").mockImplementationOnce(() => {
72 throw cause;
73 });
74
75 const error = yield* Effect.flip(
76 Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")),
77 );
78
79 expect(error).toMatchObject({
80 _tag: "WorkspaceSearchIndexCreateFailed",
81 cwd: "/workspace/project",
82 reason: "FileFinder.create threw unexpectedly.",
83 cause,
84 });
85 }),
86);
87
88it.effect("keeps returned FileFinder creation diagnostics out of the cause chain", () =>
89 Effect.gen(function* () {
90 vi.spyOn(FileFinder, "create").mockReturnValueOnce({
91 ok: false,
92 error: "native index rejected the directory",
93 });
94
95 const error = yield* Effect.flip(
96 Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")),
97 );
98
99 expect(error).toMatchObject({
100 _tag: "WorkspaceSearchIndexCreateFailed",
101 cwd: "/workspace/project",
102 reason: "native index rejected the directory",
103 });
104 expect(error.cause).toBeUndefined();
105 }),
106);
107
108it.effect("waits for the full content index warmup before returning", () =>
109 Effect.gen(function* () {
110 const waitForIndexReady = vi.fn(async () => ({ ok: true as const, value: true }));
111 const finder = {
112 destroy: vi.fn(),
113 waitForIndexReady,
114 } as unknown as FileFinder;
115 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
116
117 yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content"));
118
119 expect(waitForIndexReady).toHaveBeenCalledWith(15_000);
120 }),
121);
122
123it.effect("preserves a full-index warmup timeout as a structured error", () =>
124 Effect.gen(function* () {
125 const finder = {
126 destroy: vi.fn(),
127 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
128 } as unknown as FileFinder;
129 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
130
131 const error = yield* Effect.flip(
132 Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content")),
133 );
134
135 expect(error).toMatchObject({
136 _tag: "WorkspaceSearchIndexScanTimedOut",
137 cwd: "/workspace/project",
138 timeout: "15 seconds",
139 });
140 }),
141);
142
143it.effect("preserves FileFinder destroy failures as structured defects", () =>
144 Effect.gen(function* () {
145 const cause = new Error("native destroy failed");
146 const finder = {
147 destroy: vi.fn(() => {
148 throw cause;
149 }),
150 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
151 } as unknown as FileFinder;
152 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
153
154 const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
155 Effect.exit,
156 );
157
158 expect(Exit.isFailure(exit)).toBe(true);
159 if (Exit.isFailure(exit)) {
160 expect(Cause.hasDies(exit.cause)).toBe(true);
161 const error = Cause.squash(exit.cause);
162 expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
163 expect(error).toMatchObject({
164 _tag: "WorkspaceSearchIndexDestroyFailed",
165 cwd: "/workspace/project",
166 cause,
167 });
168 }
169 }),
170);
171
172it.effect("preserves search and refresh failures with operation context", () =>
173 Effect.scoped(
174 Effect.gen(function* () {
175 const searchCause = new Error("native search failed");
176 const refreshCause = new Error("native scan failed");
177 const contentSearchCause = new Error("native grep failed");
178 const finder = {
179 destroy: vi.fn(),
180 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
181 mixedSearch: vi.fn(() => {
182 throw searchCause;
183 }),
184 grep: vi.fn(() => {
185 throw contentSearchCause;
186 }),
187 scanFiles: vi.fn(() => {
188 throw refreshCause;
189 }),
190 } as unknown as FileFinder;
191 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
192
193 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
194 const query = "authorization: Bearer secret-token";
195 const searchError = yield* Effect.flip(searchIndex.search(query, 3));
196 const contentSearchError = yield* Effect.flip(
197 searchIndex.searchContents({
198 query,
199 limit: 3,
200 caseSensitive: false,
201 wholeWord: false,
202 useRegex: false,
203 }),
204 );
205 const refreshError = yield* Effect.flip(searchIndex.refresh());
206
207 expect(searchError).toMatchObject({
208 _tag: "WorkspaceSearchIndexSearchFailed",
209 cwd: "/workspace/project",
210 queryLength: query.length,
211 pageSize: 4,
212 reason: "FileFinder.mixedSearch threw unexpectedly.",
213 cause: searchCause,
214 });
215 expect(searchError).not.toHaveProperty("query");
216 expect(searchError.message).not.toMatch(/Bearer|secret-token/);
217 expect(contentSearchError).toMatchObject({
218 _tag: "WorkspaceSearchIndexSearchFailed",
219 cwd: "/workspace/project",
220 queryLength: query.length,
221 pageSize: 3,
222 reason: "FileFinder.grep threw unexpectedly.",
223 cause: contentSearchCause,
224 });
225 expect(contentSearchError).not.toHaveProperty("query");
226 expect(contentSearchError.message).not.toMatch(/Bearer|secret-token/);
227 expect(refreshError).toMatchObject({
228 _tag: "WorkspaceSearchIndexRefreshFailed",
229 cwd: "/workspace/project",
230 reason: "FileFinder.scanFiles threw unexpectedly.",
231 cause: refreshCause,
232 });
233 }),
234 ),
235);
236
237it.effect("keeps returned search diagnostics out of the cause chain", () =>
238 Effect.scoped(
239 Effect.gen(function* () {
240 const finder = {
241 destroy: vi.fn(),
242 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
243 mixedSearch: vi.fn(() => ({ ok: false, error: "native query rejected" })),
244 scanFiles: vi.fn(() => ({ ok: false, error: "native refresh rejected" })),
245 } as unknown as FileFinder;
246 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
247
248 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
249 const query = "authorization: Bearer secret-token";
250 const searchError = yield* Effect.flip(searchIndex.search(query, 3));
251 const refreshError = yield* Effect.flip(searchIndex.refresh());
252
253 expect(searchError).toMatchObject({
254 _tag: "WorkspaceSearchIndexSearchFailed",
255 cwd: "/workspace/project",
256 queryLength: query.length,
257 pageSize: 4,
258 reason: "native query rejected",
259 });
260 expect(searchError).not.toHaveProperty("query");
261 expect(searchError.message).not.toMatch(/Bearer|secret-token/);
262 expect(searchError.cause).toBeUndefined();
263 expect(refreshError).toMatchObject({
264 _tag: "WorkspaceSearchIndexRefreshFailed",
265 cwd: "/workspace/project",
266 reason: "native refresh rejected",
267 });
268 expect(refreshError.cause).toBeUndefined();
269 }),
270 ),
271);
272
273it.effect("continues whole-word searches after a filtered grep page", () =>
274 Effect.scoped(
275 Effect.gen(function* () {
276 const nextCursor = {
277 __brand: "GrepCursor",
278 _offset: 1,
279 } as GrepCursor;
280 const grepResult = (
281 lineContent: string,
282 matchRanges: Array<[number, number]>,
283 cursor: GrepCursor | null,
284 ): GrepResult => ({
285 items: [
286 {
287 relativePath: "src/words.ts",
288 fileName: "words.ts",
289 gitStatus: "unmodified",
290 size: lineContent.length,
291 modified: 0,
292 isBinary: false,
293 totalFrecencyScore: 0,
294 accessFrecencyScore: 0,
295 modificationFrecencyScore: 0,
296 lineNumber: 1,
297 col: 0,
298 byteOffset: 0,
299 lineContent,
300 matchRanges,
301 },
302 ],
303 totalMatched: 1,
304 totalFilesSearched: 1,
305 totalFiles: 1,
306 filteredFileCount: 1,
307 nextCursor: cursor,
308 });
309 const grep = vi.fn((_query: string, options?: GrepOptions) =>
310 options?.cursor
311 ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
312 : {
313 ok: true as const,
314 value: grepResult("needleSuffix", [[0, 6]], nextCursor),
315 },
316 );
317 const finder = {
318 destroy: vi.fn(),
319 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
320 grep,
321 } as unknown as FileFinder;
322 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
323
324 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
325 const result = yield* searchIndex.searchContents({
326 query: "needle",
327 limit: 1,
328 caseSensitive: true,
329 wholeWord: true,
330 useRegex: false,
331 });
332
333 expect(result).toEqual({
334 matches: [
335 {
336 path: "src/words.ts",
337 lineNumber: 1,
338 lineContent: "needle",
339 matchRanges: [{ start: 0, end: 6 }],
340 },
341 ],
342 truncated: false,
343 });
344 expect(grep).toHaveBeenCalledTimes(2);
345 expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
346 }),
347 ),
348);