Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as RcMap from "effect/RcMap";
9import * as Schema from "effect/Schema";
10
11import type {
12 FilesystemBrowseInput,
13 FilesystemBrowseResult,
14 ProjectEntry,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 ProjectListIgnoredFilesInput,
18 ProjectListIgnoredFilesResult,
19 ProjectSearchContentsInput,
20 ProjectSearchContentsResult,
21 ProjectSearchEntriesInput,
22 ProjectSearchEntriesResult,
23} from "@t3tools/contracts";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
26import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
27
28import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
29import * as VcsProcess from "../vcs/VcsProcess.ts";
30import * as WorkspacePaths from "./WorkspacePaths.ts";
31import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
32
33export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
34 "WorkspaceEntriesWindowsPathUnsupportedError",
35 {
36 cwd: Schema.optional(Schema.String),
37 partialPath: Schema.String,
38 platform: Schema.String,
39 },
40) {
41 override get message(): string {
42 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
43 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
44 }
45}
46
47export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
48 "WorkspaceEntriesCurrentProjectRequiredError",
49 {
50 partialPath: Schema.String,
51 },
52) {
53 override get message(): string {
54 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
55 }
56}
57
58export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
59 "WorkspaceEntriesReadDirectoryError",
60 {
61 cwd: Schema.optional(Schema.String),
62 partialPath: Schema.String,
63 parentPath: Schema.String,
64 cause: Schema.Defect(),
65 },
66) {
67 get pathMissing(): boolean {
68 return (this.cause as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
69 }
70
71 override get message(): string {
72 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
73 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
74 }
75}
76
77export const WorkspaceEntriesBrowseError = Schema.Union([
78 WorkspaceEntriesWindowsPathUnsupportedError,
79 WorkspaceEntriesCurrentProjectRequiredError,
80 WorkspaceEntriesReadDirectoryError,
81]);
82export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
83
84export const WorkspaceEntriesError = Schema.Union([
85 WorkspaceEntriesReadDirectoryError,
86 WorkspacePaths.WorkspaceRootNotExistsError,
87 WorkspacePaths.WorkspaceRootCreateFailedError,
88 WorkspacePaths.WorkspaceRootStatFailedError,
89 WorkspacePaths.WorkspaceRootNotDirectoryError,
90 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
91 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
92 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
93]);
94export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
95
96export class WorkspaceEntries extends Context.Service<
97 WorkspaceEntries,
98 {
99 readonly browse: (
100 input: FilesystemBrowseInput,
101 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
102 readonly list: (
103 input: ProjectListEntriesInput,
104 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
105 readonly search: (
106 input: ProjectSearchEntriesInput,
107 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
108 readonly listIgnoredFiles: (
109 input: ProjectListIgnoredFilesInput,
110 ) => Effect.Effect<ProjectListIgnoredFilesResult, WorkspaceEntriesError>;
111 readonly searchContents: (
112 input: ProjectSearchContentsInput,
113 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
114 readonly refresh: (cwd: string) => Effect.Effect<void>;
115 }
116>()("t3/workspace/WorkspaceEntries") {}
117
118/** Ignored files offered for copying; more than this is a build folder, not config. */
119const IGNORED_FILES_LIMIT = 200;
120
121/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
122const IGNORE_CHECK_CHUNK_SIZE = 1000;
123
124/** Children classified at once when listing a folder; each symlink costs a realpath and a stat. */
125const SYMLINK_RESOLVE_BATCH_SIZE = 64;
126
127const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
128 input: FilesystemBrowseInput,
129 path: Path.Path,
130): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
131 const platform = yield* HostProcess.Platform;
132 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
133 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
134 cwd: input.cwd,
135 partialPath: input.partialPath,
136 platform,
137 });
138 }
139
140 if (!isExplicitRelativePath(input.partialPath)) {
141 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
142 }
143
144 if (!input.cwd) {
145 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
146 partialPath: input.partialPath,
147 });
148 }
149 return path.resolve(
150 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
151 input.partialPath,
152 );
153});
154
155/** @public */
156export const make = Effect.gen(function* () {
157 const path = yield* Path.Path;
158 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
159 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
160 const vcsProcess = yield* VcsProcess.VcsProcess;
161
162 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
163 cwd: string,
164 ): Effect.fn.Return<string, WorkspaceEntriesError> {
165 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
166 });
167
168 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
169 function* (cwd) {
170 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
171 Effect.orElseSucceed(() => cwd),
172 );
173 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
174 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
175 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
176 continue;
177 }
178 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
179 function* (
180 cause:
181 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
182 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
183 ) {
184 yield* Effect.logWarning("Failed to refresh workspace search index", {
185 cwd,
186 variant,
187 cause,
188 });
189 yield* workspaceSearchIndexes.invalidate(indexKey);
190 },
191 );
192 yield* Effect.gen(function* () {
193 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
194 yield* searchIndex.refresh();
195 }).pipe(
196 Effect.provide(workspaceSearchIndexes.get(indexKey)),
197 Effect.catchTags({
198 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
199 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
200 }),
201 );
202 }
203 },
204 );
205
206 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
207 function* (input) {
208 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
209 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
210 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
211 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
212
213 const dirents = yield* Effect.tryPromise({
214 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
215 catch: (cause) =>
216 new WorkspaceEntriesReadDirectoryError({
217 cwd: input.cwd,
218 partialPath: input.partialPath,
219 parentPath,
220 cause,
221 }),
222 }).pipe(
223 Effect.catchIf(
224 (error) => {
225 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
226 return code === "EACCES" || code === "EPERM";
227 },
228 () => Effect.succeed([]),
229 ),
230 );
231
232 const showHidden = endsWithSeparator || prefix.startsWith(".");
233 const lowerPrefix = prefix.toLowerCase();
234 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
235 for (const dirent of dirents) {
236 if (
237 dirent.isDirectory() &&
238 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
239 (showHidden || !dirent.name.startsWith("."))
240 ) {
241 entries.push({
242 name: dirent.name,
243 fullPath: path.join(parentPath, dirent.name),
244 });
245 }
246 }
247
248 return {
249 parentPath,
250 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
251 };
252 },
253 );
254
255 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
256 function* (input) {
257 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
258 const normalizedQuery = normalizeSearchQuery(input.query, {
259 trimLeadingPattern: /^[@./]+/,
260 });
261 const result = yield* Effect.gen(function* () {
262 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
263 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
264 }).pipe(
265 Effect.provide(
266 workspaceSearchIndexes.get(
267 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
268 ),
269 ),
270 );
271 if (input.kind === "directory" || input.imageOnly) return result;
272 const worktreeFiles = yield* findNestedWorktreeFiles(
273 normalizedCwd,
274 input.query,
275 result.entries,
276 );
277 if (worktreeFiles.length === 0) return result;
278 const entries = [...worktreeFiles, ...result.entries];
279 return {
280 entries: entries.slice(0, input.limit),
281 truncated: result.truncated || entries.length > input.limit,
282 };
283 },
284 );
285
286 // The index skips gitignored folders, where agents often put worktrees (`.worktrees/x`).
287 // A path relative to such a worktree is found only when it names an existing file exactly.
288 const findNestedWorktreeFiles = Effect.fn("WorkspaceEntries.findNestedWorktreeFiles")(function* (
289 cwd: string,
290 query: string,
291 indexed: ReadonlyArray<ProjectEntry>,
292 ) {
293 const relativePath = query.trim().replaceAll("\\", "/");
294 if (
295 !relativePath.includes("/") ||
296 relativePath.endsWith("/") ||
297 path.isAbsolute(relativePath) ||
298 isWindowsAbsolutePath(relativePath) ||
299 relativePath.split("/").some((segment) => segment === "..") ||
300 indexed.some(
301 (entry) =>
302 entry.kind === "file" &&
303 (entry.path === relativePath || entry.path.endsWith(`/${relativePath}`)),
304 )
305 ) {
306 return [];
307 }
308 const listWorktrees = (args: ReadonlyArray<string>) =>
309 vcsProcess
310 .run({
311 operation: "WorkspaceEntries.listWorktrees",
312 command: "git",
313 args: ["worktree", "list", "--porcelain", ...args],
314 cwd,
315 allowNonZeroExit: true,
316 timeoutMs: 5_000,
317 })
318 .pipe(
319 Effect.map((result) => (result.exitCode === 0 ? result.stdout : undefined)),
320 Effect.orElseSucceed(() => undefined),
321 );
322 // Only NUL framing keeps a newline in a worktree path. Pre-2.36 Git rejects `-z`.
323 const listed =
324 (yield* listWorktrees(["-z"])) ?? (yield* listWorktrees([]))?.replaceAll("\n", "\0");
325 if (listed === undefined) return [];
326 const realCwd = yield* Effect.promise(() => NodeFSP.realpath(cwd).catch(() => cwd));
327 const worktreeRoots = listed.split("\0\0").flatMap((record) => {
328 const fields = record.split("\0");
329 const worktree = fields.find((field) => field.startsWith("worktree "));
330 // A `prunable` record's directory is gone; another checkout may now sit there.
331 if (worktree === undefined || fields.some((field) => field.startsWith("prunable"))) return [];
332 const root = worktree.slice("worktree ".length);
333 const relativeRoot = path.relative(realCwd, root);
334 return relativeRoot === "" ||
335 relativeRoot === ".." ||
336 relativeRoot.startsWith(`..${path.sep}`) ||
337 path.isAbsolute(relativeRoot)
338 ? []
339 : [relativeRoot.split(path.sep).join("/")];
340 });
341 const matches = yield* Effect.promise(() =>
342 Promise.all(
343 worktreeRoots.map(async (relativeRoot) => {
344 const candidate = `${relativeRoot}/${relativePath}`;
345 const stat = await NodeFSP.stat(path.join(realCwd, candidate)).catch(() => null);
346 return stat?.isFile() ? candidate : null;
347 }),
348 ),
349 );
350 return matches
351 .filter((candidate) => candidate !== null)
352 .map((candidate): ProjectEntry => ({ path: candidate, kind: "file" }));
353 });
354
355 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
356 "WorkspaceEntries.searchContents",
357 )(function* (input) {
358 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
359 return yield* Effect.gen(function* () {
360 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
361 return yield* searchIndex.searchContents(input);
362 }).pipe(
363 Effect.provide(
364 workspaceSearchIndexes.get(
365 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
366 ),
367 ),
368 );
369 });
370
371 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
372 function* (input) {
373 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
374 if (input.directoryPath !== undefined) {
375 const directoryPath = input.directoryPath;
376 const toError = (cause: unknown) =>
377 new WorkspaceEntriesReadDirectoryError({
378 cwd: normalizedCwd,
379 partialPath: directoryPath,
380 parentPath: path.resolve(normalizedCwd, directoryPath),
381 cause,
382 });
383 const target =
384 directoryPath === ""
385 ? { absolutePath: normalizedCwd, relativePath: "" }
386 : yield* workspacePaths
387 .resolveRelativePathWithinRoot({
388 workspaceRoot: normalizedCwd,
389 relativePath: directoryPath,
390 })
391 .pipe(Effect.mapError(toError));
392 const { entries, throughSymlink, nestedGitRoots } = yield* Effect.tryPromise({
393 try: async () => {
394 const root = await NodeFSP.realpath(normalizedCwd);
395 const directory = await NodeFSP.realpath(target.absolutePath);
396 const relative = path.relative(root, directory);
397 if (
398 relative === ".." ||
399 relative.startsWith(`..${path.sep}`) ||
400 path.isAbsolute(relative) ||
401 relative.split(path.sep).includes(".git") ||
402 target.relativePath.split("/").includes(".git")
403 ) {
404 throw new Error("Directory must be inside the workspace and outside .git.");
405 }
406 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
407 const isSameOrInside = (parent: string, child: string) => {
408 const relativeChild = path.relative(parent, child);
409 return (
410 relativeChild !== ".." &&
411 !relativeChild.startsWith(`..${path.sep}`) &&
412 !path.isAbsolute(relativeChild)
413 );
414 };
415 // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.
416 let visitedFolders: Promise<ReadonlyArray<string>> | undefined;
417 const loadVisitedFolders = () =>
418 (visitedFolders ??= (async () => {
419 const folders = [root];
420 let current = normalizedCwd;
421 for (const segment of target.relativePath.split("/").filter(Boolean)) {
422 current = path.join(current, segment);
423 folders.push(await NodeFSP.realpath(current));
424 }
425 return folders;
426 })());
427 const resolveSymlinkKind = async (
428 name: string,
429 ): Promise<ProjectEntry["kind"] | undefined> => {
430 const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(
431 () => undefined,
432 );
433 if (
434 resolved === undefined ||
435 !isSameOrInside(root, resolved) ||
436 path.relative(root, resolved).split(path.sep).includes(".git")
437 ) {
438 return undefined;
439 }
440 const stat = await NodeFSP.stat(resolved).catch(() => undefined);
441 if (stat?.isFile()) return "file";
442 if (!stat?.isDirectory()) return undefined;
443 const folders = await loadVisitedFolders();
444 return folders.some((folder) => isSameOrInside(resolved, folder))
445 ? undefined
446 : "directory";
447 };
448 // Bound filesystem work for directories such as pnpm node_modules.
449 const kinds: Array<ProjectEntry["kind"] | undefined> = [];
450 for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {
451 kinds.push(
452 ...(await Promise.all(
453 children
454 .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)
455 .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {
456 if (child.name === ".git") return undefined;
457 if (child.isDirectory()) return "directory";
458 if (child.isFile()) return "file";
459 return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;
460 }),
461 )),
462 );
463 }
464 const nestedGitRoots: Array<string> = [];
465 const segments = target.relativePath.split("/").filter(Boolean);
466 for (let index = 1; index <= segments.length; index += 1) {
467 const candidate = segments.slice(0, index).join("/");
468 const dotGit = await NodeFSP.lstat(path.join(normalizedCwd, candidate, ".git")).catch(
469 () => null,
470 );
471 if (dotGit) nestedGitRoots.push(candidate);
472 }
473 return {
474 nestedGitRoots,
475 entries: children.flatMap((child, index): ProjectEntry[] => {
476 const kind = kinds[index];
477 if (kind === undefined) return [];
478 return [
479 {
480 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
481 kind,
482 },
483 ];
484 }),
485 // Git refuses to classify paths beyond a symbolic link.
486 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
487 };
488 },
489 catch: toError,
490 });
491 let gitRoot = "";
492 let gitPrefix = "";
493 // stdin avoids argument limits; ignore classification is optional without git/repositories.
494 const checkIgnore = (paths: ReadonlyArray<string>) =>
495 vcsProcess
496 .run({
497 operation: "WorkspaceEntries.list",
498 command: "git",
499 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
500 cwd: path.join(normalizedCwd, gitRoot),
501 stdin: `${paths.map((entryPath) => entryPath.slice(gitPrefix.length)).join("\0")}\0`,
502 allowNonZeroExit: true,
503 timeoutMs: 10_000,
504 maxOutputBytes: 16 * 1024 * 1024,
505 })
506 .pipe(Effect.orElseSucceed(() => undefined));
507 // Git refuses paths inside a submodule (128) but still answers for nested clones.
508 for (const nestedGitRoot of nestedGitRoots) {
509 if ((yield* checkIgnore([`${nestedGitRoot}/.git`]))?.exitCode !== 128) continue;
510 gitRoot = nestedGitRoot;
511 gitPrefix = `${gitRoot}/`;
512 }
513 const directoryGitPath = target.relativePath.slice(gitPrefix.length);
514 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
515 // Symlinks and pathspec magic still need per-child checks.
516 if (
517 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
518 directoryGitPath !== "" &&
519 !throughSymlink &&
520 !/^:|[*?[\\]/.test(directoryGitPath) &&
521 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
522 ) {
523 return {
524 entries: entries.map((entry) => ({ ...entry, ignored: true })),
525 truncated: false,
526 };
527 }
528 const ignored = new Set<string>();
529 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
530 const result = yield* checkIgnore(
531 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
532 );
533 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
534 for (const ignoredPath of result.stdout.split("\0")) ignored.add(gitPrefix + ignoredPath);
535 }
536 return {
537 entries: entries.map((entry) =>
538 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
539 ),
540 truncated: false,
541 };
542 }
543 return yield* Effect.gen(function* () {
544 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
545 return yield* searchIndex.list();
546 }).pipe(
547 Effect.provide(
548 workspaceSearchIndexes.get(
549 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
550 ),
551 ),
552 );
553 },
554 );
555
556 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
557 "WorkspaceEntries.listIgnoredFiles",
558 )(function* (input) {
559 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
560 // `--directory` reports a folder holding nothing but ignored files as one
561 // `name/` entry, which is how `node_modules` and build output drop out.
562 const result = yield* vcsProcess
563 .run({
564 operation: "WorkspaceEntries.listIgnoredFiles",
565 command: "git",
566 args: [
567 "-c",
568 "core.fsmonitor=false",
569 "ls-files",
570 "--others",
571 "--ignored",
572 "--exclude-standard",
573 "--directory",
574 "--no-empty-directory",
575 "-z",
576 ],
577 cwd: normalizedCwd,
578 allowNonZeroExit: true,
579 timeoutMs: 10_000,
580 maxOutputBytes: 4 * 1024 * 1024,
581 })
582 .pipe(Effect.orElseSucceed(() => undefined));
583 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
584 // Filter before the cap so files sorting past it stay reachable by search.
585 const query = input.query?.toLowerCase() ?? "";
586 const paths = result.stdout
587 .split("\0")
588 .filter(
589 (entry) => entry.length > 0 && !entry.endsWith("/") && entry.toLowerCase().includes(query),
590 )
591 .toSorted();
592 const files = yield* Effect.promise(() =>
593 Promise.all(
594 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
595 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
596 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
597 () => null,
598 );
599 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
600 }),
601 ),
602 );
603 return {
604 files: files.filter((file) => file !== null),
605 truncated: paths.length > IGNORED_FILES_LIMIT,
606 };
607 });
608
609 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
610});
611
612export const layer = Layer.effect(WorkspaceEntries, make).pipe(
613 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
614 Layer.provide(VcsProcess.layer),
615);