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