Add project file picker (⌘P) and project content search (⇧⌘F) (#4855)

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-07-30 16:39:15 +02:00
1 parent 1877237c7a
commit abc409c2d4
39 files changed
+2932 -480

No files matched your search

+1
View File
@@ -55,6 +55,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
[WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,
[WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,
[WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,
[WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
+2
View File
@@ -198,6 +198,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("filePicker.toggle"), "mod+p");
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
+13 -8
View File
@@ -547,19 +547,24 @@ const make = Effect.gen(function* () {
});
}
const nextConfig = [...customConfig, ...missingDefaults];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS_COUNT
? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
: nextConfig;
if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
yield* Effect.logWarning("truncating keybindings config to max entries", {
// Startup backfill must never evict persisted user rules: append only
// the defaults that fit and skip the rest.
const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);
const defaultsToAppend = missingDefaults.slice(0, availableSlots);
const skippedDefaults = missingDefaults.slice(availableSlots);
if (skippedDefaults.length > 0) {
yield* Effect.logWarning("skipping default keybinding backfill at max entries", {
path: keybindingsConfigPath,
maxEntries: MAX_KEYBINDINGS_COUNT,
commands: skippedDefaults.map((rule) => rule.command),
});
}
if (defaultsToAppend.length === 0) {
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
return;
}
yield* writeConfigAtomically(cappedConfig);
yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
}),
);
@@ -72,7 +72,12 @@ const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv)
return result.stdout.trim();
});
const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) =>
const searchWorkspaceEntries = (input: {
cwd: string;
query: string;
limit: number;
kind?: "file" | "directory";
}) =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
return yield* workspaceEntries.search(input);
@@ -200,6 +205,62 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
}),
);
it.effect("applies the file filter before limiting search results", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-file-limit-" });
yield* writeTextFile(cwd, "src/index.ts");
yield* writeTextFile(cwd, "src/internal.ts");
const result = yield* searchWorkspaceEntries({
cwd,
query: "src",
limit: 1,
kind: "file",
});
expect(result.entries).toEqual([{ path: "src/index.ts", kind: "file" }]);
expect(result.truncated).toBe(true);
}),
);
it.effect("answers an empty file-filtered query with a bounded file listing", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-empty-query-" });
yield* writeTextFile(cwd, "src/index.ts");
yield* writeTextFile(cwd, "README.md");
const result = yield* searchWorkspaceEntries({
cwd,
query: "",
limit: 10,
kind: "file",
});
const paths = result.entries.map((entry) => entry.path);
expect(paths).toHaveLength(2);
expect(paths).toContain("src/index.ts");
expect(paths).toContain("README.md");
expect(result.entries.every((entry) => entry.kind === "file")).toBe(true);
}),
);
it.effect("returns only directories for the directory filter", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-directory-filter-" });
yield* writeTextFile(cwd, "src/index.ts");
const result = yield* searchWorkspaceEntries({
cwd,
query: "src",
limit: 10,
kind: "directory",
});
expect(result.entries).toEqual([{ path: "src", kind: "directory" }]);
expect(result.truncated).toBe(false);
}),
);
it.effect("excludes gitignored paths for git repositories", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
@@ -292,6 +353,287 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
);
});
describe("searchContents", () => {
it.effect("returns content matches with file paths, line numbers, and ranges", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-search-" });
yield* writeTextFile(
cwd,
"src/shapes.ts",
"export const square = 4;\nexport const Square = 16;\nexport const squareSize = 8;\n",
);
yield* writeTextFile(cwd, "src/other.ts", "const circle = true;\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "Square",
limit: 100,
caseSensitive: false,
wholeWord: true,
useRegex: false,
});
expect(result.matches.map((match) => [match.path, match.lineNumber])).toEqual([
["src/shapes.ts", 1],
["src/shapes.ts", 2],
]);
expect(result.matches[0]?.matchRanges).toEqual([{ start: 13, end: 19 }]);
expect(result.truncated).toBe(false);
}),
);
it.effect("honors case sensitivity and gitignore rules", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-ignore-", git: true });
yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n");
yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n");
yield* writeTextFile(cwd, "ignored.txt", "Square\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "Square",
limit: 100,
caseSensitive: true,
wholeWord: false,
useRegex: false,
});
expect(result.matches).toHaveLength(1);
expect(result.matches[0]).toMatchObject({ path: "src/keep.ts", lineNumber: 2 });
}),
);
it.effect("filters whole-word matches by word boundaries without widening ranges", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-whole-word-" });
yield* writeTextFile(cwd, "src/words.ts", "note notes denote\nfootnote note\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "note",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
// "notes", "denote", and "footnote" are word-adjacent and excluded;
// ranges cover exactly the query, never boundary characters.
expect(result.matches).toEqual([
expect.objectContaining({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [{ start: 0, end: 4 }],
}),
expect.objectContaining({
path: "src/words.ts",
lineNumber: 2,
matchRanges: [{ start: 9, end: 13 }],
}),
]);
}),
);
it.effect("finds later whole-word matches in a file after rejected raw matches", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" });
yield* writeTextFile(cwd, "src/words.ts", `${"afoo\n".repeat(10)}foo\n`);
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo",
limit: 1,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
expect(result.matches).toEqual([
expect.objectContaining({
path: "src/words.ts",
lineNumber: 11,
matchRanges: [{ start: 0, end: 3 }],
}),
]);
}),
);
it.effect("treats astral-plane letters as whole word characters", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-astral-word-" });
yield* writeTextFile(cwd, "src/words.ts", "𐐀foo foo foo𐐀\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
expect(result.matches).toEqual([
expect.objectContaining({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [{ start: 6, end: 9 }],
}),
]);
}),
);
it.effect("matches punctuation-edged whole-word queries including adjacent occurrences", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-punctuation-" });
yield* writeTextFile(cwd, "src/words.ts", "-foo- -foo- -foo-\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "-foo-",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
// Consuming-boundary regex would swallow the separating spaces and
// drop the middle occurrence; boundary post-filtering keeps all three.
expect(result.matches).toHaveLength(1);
expect(result.matches[0]).toMatchObject({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [
{ start: 0, end: 5 },
{ start: 6, end: 11 },
{ start: 12, end: 17 },
],
});
}),
);
it.effect("matches punctuation-edged regex queries as whole words", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-punctuation-" });
yield* writeTextFile(cwd, "src/words.ts", "foo- foo-\nafoo-b\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo-",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: true,
});
// wholeWord + useRegex must not silently drop non-word-edged patterns
// like "foo-", and "afoo-" is excluded because 'a'/'f' are both word
// characters at the match's left edge.
expect(result.matches).toHaveLength(1);
expect(result.matches[0]).toMatchObject({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [
{ start: 0, end: 4 },
{ start: 5, end: 9 },
],
});
}),
);
it.effect("caps matches per file so one dense file cannot fill the page", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" });
yield* writeTextFile(cwd, "src/dense.ts", "needle\n".repeat(300));
yield* writeTextFile(cwd, "src/other.ts", "needle\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "needle",
limit: 500,
caseSensitive: true,
wholeWord: false,
useRegex: false,
});
const byPath = new Map<string, number>();
for (const match of result.matches) {
byPath.set(match.path, (byPath.get(match.path) ?? 0) + 1);
}
expect(byPath.get("src/dense.ts")).toBe(100);
expect(byPath.get("src/other.ts")).toBe(1);
}),
);
it.effect("preserves regex escapes during case-insensitive searches", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-" });
yield* writeTextFile(cwd, "src/shapes.ts", "Square\nsquare\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "\\SQUARE",
limit: 100,
caseSensitive: false,
wholeWord: false,
useRegex: true,
});
expect(result.matches.map((match) => match.lineNumber)).toEqual([1, 2]);
}),
);
it.effect("preserves invalid regex errors during case-insensitive searches", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-invalid-regex-" });
yield* writeTextFile(cwd, "src/shapes.ts", "foobar\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo)bar(",
limit: 100,
caseSensitive: false,
wholeWord: false,
useRegex: true,
});
expect(result.regexFallbackError).toBeDefined();
expect(result.matches).toEqual([]);
}),
);
it.effect("maps multi-byte lines to string-indexed ranges", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
yield* writeTextFile(cwd, "src/notes.ts", 'const label = "héllo wörld";\n');
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "wörld",
limit: 100,
caseSensitive: true,
wholeWord: false,
useRegex: false,
});
expect(result.matches).toHaveLength(1);
const match = result.matches[0]!;
const range = match.matchRanges[0]!;
expect(match.lineContent.slice(range.start, range.end)).toBe("wörld");
}),
);
});
describe("browse", () => {
it.effect("returns matching directories and excludes files", () =>
Effect.gen(function* () {
+71 -34
View File
@@ -14,11 +14,14 @@ import type {
FilesystemBrowseResult,
ProjectListEntriesInput,
ProjectListEntriesResult,
ProjectSearchContentsInput,
ProjectSearchContentsResult,
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
@@ -93,6 +96,9 @@ export class WorkspaceEntries extends Context.Service<
readonly search: (
input: ProjectSearchEntriesInput,
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
readonly searchContents: (
input: ProjectSearchContentsInput,
) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
readonly refresh: (cwd: string) => Effect.Effect<void>;
}
>()("t3/workspace/WorkspaceEntries") {}
@@ -148,33 +154,37 @@ export const make = Effect.gen(function* () {
const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
Effect.orElseSucceed(() => cwd),
);
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
return;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
continue;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
variant,
cause,
});
yield* workspaceSearchIndexes.invalidate(indexKey);
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
});
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
);
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(indexKey)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
);
}
},
);
@@ -230,28 +240,55 @@ export const make = Effect.gen(function* () {
const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
const normalizedQuery = input.query
.trim()
.toLowerCase()
.replace(/^[@./]+/, "");
const normalizedQuery = normalizeSearchQuery(input.query, {
trimLeadingPattern: /^[@./]+/,
});
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.search(normalizedQuery, input.limit);
}).pipe(Effect.provide(workspaceSearchIndexes.get(normalizedCwd)));
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind);
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
),
),
);
},
);
const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
"WorkspaceEntries.searchContents",
)(function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.searchContents(input);
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
),
),
);
});
const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.list();
}).pipe(Effect.provide(workspaceSearchIndexes.get(normalizedCwd)));
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
),
),
);
},
);
return WorkspaceEntries.of({ browse, list, refresh, search });
return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
});
export const layer = Layer.effect(WorkspaceEntries, make).pipe(
@@ -1,4 +1,4 @@
import { FileFinder } from "@ff-labs/fff-node";
import { FileFinder, type GrepCursor, type GrepOptions, type GrepResult } from "@ff-labs/fff-node";
import { afterEach, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
@@ -51,6 +51,41 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
}),
);
it.effect("waits for the full content index warmup before returning", () =>
Effect.gen(function* () {
const waitForIndexReady = vi.fn(async () => ({ ok: true as const, value: true }));
const finder = {
destroy: vi.fn(),
waitForIndexReady,
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content"));
expect(waitForIndexReady).toHaveBeenCalledWith(15_000);
}),
);
it.effect("preserves a full-index warmup timeout as a structured error", () =>
Effect.gen(function* () {
const finder = {
destroy: vi.fn(),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const error = yield* Effect.flip(
Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content")),
);
expect(error).toMatchObject({
_tag: "WorkspaceSearchIndexScanTimedOut",
cwd: "/workspace/project",
timeout: "15 seconds",
});
}),
);
it.effect("preserves FileFinder destroy failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native destroy failed");
@@ -58,7 +93,7 @@ it.effect("preserves FileFinder destroy failures as structured defects", () =>
destroy: vi.fn(() => {
throw cause;
}),
isScanning: vi.fn(() => false),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
@@ -85,12 +120,16 @@ it.effect("preserves search and refresh failures with operation context", () =>
Effect.gen(function* () {
const searchCause = new Error("native search failed");
const refreshCause = new Error("native scan failed");
const contentSearchCause = new Error("native grep failed");
const finder = {
destroy: vi.fn(),
isScanning: vi.fn(() => false),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
mixedSearch: vi.fn(() => {
throw searchCause;
}),
grep: vi.fn(() => {
throw contentSearchCause;
}),
scanFiles: vi.fn(() => {
throw refreshCause;
}),
@@ -100,6 +139,15 @@ it.effect("preserves search and refresh failures with operation context", () =>
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
const query = "authorization: Bearer secret-token";
const searchError = yield* Effect.flip(searchIndex.search(query, 3));
const contentSearchError = yield* Effect.flip(
searchIndex.searchContents({
query,
limit: 3,
caseSensitive: false,
wholeWord: false,
useRegex: false,
}),
);
const refreshError = yield* Effect.flip(searchIndex.refresh());
expect(searchError).toMatchObject({
@@ -112,6 +160,16 @@ it.effect("preserves search and refresh failures with operation context", () =>
});
expect(searchError).not.toHaveProperty("query");
expect(searchError.message).not.toMatch(/Bearer|secret-token/);
expect(contentSearchError).toMatchObject({
_tag: "WorkspaceSearchIndexSearchFailed",
cwd: "/workspace/project",
queryLength: query.length,
pageSize: 3,
reason: "FileFinder.grep threw unexpectedly.",
cause: contentSearchCause,
});
expect(contentSearchError).not.toHaveProperty("query");
expect(contentSearchError.message).not.toMatch(/Bearer|secret-token/);
expect(refreshError).toMatchObject({
_tag: "WorkspaceSearchIndexRefreshFailed",
cwd: "/workspace/project",
@@ -127,7 +185,7 @@ it.effect("keeps returned search diagnostics out of the cause chain", () =>
Effect.gen(function* () {
const finder = {
destroy: vi.fn(),
isScanning: vi.fn(() => false),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
mixedSearch: vi.fn(() => ({ ok: false, error: "native query rejected" })),
scanFiles: vi.fn(() => ({ ok: false, error: "native refresh rejected" })),
} as unknown as FileFinder;
@@ -157,3 +215,80 @@ it.effect("keeps returned search diagnostics out of the cause chain", () =>
}),
),
);
it.effect("continues whole-word searches after a filtered grep page", () =>
Effect.scoped(
Effect.gen(function* () {
const nextCursor = {
__brand: "GrepCursor",
_offset: 1,
} as GrepCursor;
const grepResult = (
lineContent: string,
matchRanges: Array<[number, number]>,
cursor: GrepCursor | null,
): GrepResult => ({
items: [
{
relativePath: "src/words.ts",
fileName: "words.ts",
gitStatus: "unmodified",
size: lineContent.length,
modified: 0,
isBinary: false,
totalFrecencyScore: 0,
accessFrecencyScore: 0,
modificationFrecencyScore: 0,
lineNumber: 1,
col: 0,
byteOffset: 0,
lineContent,
matchRanges,
},
],
totalMatched: 1,
totalFilesSearched: 1,
totalFiles: 1,
filteredFileCount: 1,
nextCursor: cursor,
});
const grep = vi.fn((_query: string, options?: GrepOptions) =>
options?.cursor
? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
: {
ok: true as const,
value: grepResult("needleSuffix", [[0, 6]], nextCursor),
},
);
const finder = {
destroy: vi.fn(),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
grep,
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
const result = yield* searchIndex.searchContents({
query: "needle",
limit: 1,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
expect(result).toEqual({
matches: [
{
path: "src/words.ts",
lineNumber: 1,
lineContent: "needle",
matchRanges: [{ start: 0, end: 6 }],
},
],
truncated: false,
});
expect(grep).toHaveBeenCalledTimes(2);
expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
}),
),
);
+275 -40
View File
@@ -1,22 +1,36 @@
import { FileFinder, type MixedItem, type MixedSearchResult } from "@ff-labs/fff-node";
import {
type DirItem,
type DirSearchResult,
type FileItem,
FileFinder,
type GrepCursor,
type MixedItem,
type MixedSearchResult,
type Result,
type SearchResult,
} from "@ff-labs/fff-node";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as LayerMap from "effect/LayerMap";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import type {
ProjectEntry,
ProjectEntryKind,
ProjectListEntriesResult,
ProjectSearchContentsInput,
ProjectSearchContentsResult,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
const WORKSPACE_INDEX_SCAN_POLL_INTERVAL = "50 millis";
const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexCreateFailed>()(
"WorkspaceSearchIndexCreateFailed",
@@ -96,7 +110,11 @@ export class WorkspaceSearchIndex extends Context.Service<
readonly search: (
query: string,
limit: number,
kind?: ProjectEntryKind,
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
readonly searchContents: (
input: Omit<ProjectSearchContentsInput, "cwd">,
) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;
readonly refresh: () => Effect.Effect<
void,
WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut
@@ -129,6 +147,43 @@ function toProjectEntry(item: MixedItem): ProjectEntry | null {
};
}
function toFileEntry(item: FileItem): ProjectEntry | null {
const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
}
function toDirectoryEntry(item: DirItem): ProjectEntry | null {
const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
}
function mapFileSearchResult(result: SearchResult, limit: number): ProjectSearchEntriesResult {
return {
entries: result.items
.flatMap((item) => {
const entry = toFileEntry(item);
return entry ? [entry] : [];
})
.slice(0, limit),
truncated: result.totalMatched > limit,
};
}
function mapDirectorySearchResult(
result: DirSearchResult,
limit: number,
): ProjectSearchEntriesResult {
const entries = result.items.flatMap((item) => {
const entry = toDirectoryEntry(item);
return entry ? [entry] : [];
});
const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
return {
entries: entries.slice(0, limit),
truncated: result.totalMatched - rootDirectoryCount > limit,
};
}
function mapMixedSearchResult(
result: MixedSearchResult,
limit: number,
@@ -155,6 +210,74 @@ function mapMixedSearchResult(
};
}
const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
function codePointAt(line: string, index: number): string | undefined {
const codePoint = line.codePointAt(index);
return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
}
function codePointBefore(line: string, index: number): string | undefined {
if (index <= 0) return undefined;
const previousCodeUnit = line.charCodeAt(index - 1);
const previousIndex =
previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
return codePointAt(line, previousIndex);
}
function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
readonly searchQuery: string;
readonly regexMode: boolean;
} {
if (input.caseSensitive) {
return { searchQuery: input.query, regexMode: input.useRegex };
}
// Plain mode relies on smart case: an all-lowercase needle matches
// case-insensitively. Regex mode needs an explicit inline flag instead.
return input.useRegex
? { searchQuery: `(?i)${input.query}`, regexMode: true }
: { searchQuery: input.query.toLowerCase(), regexMode: false };
}
function mapContentMatchRanges(
line: string,
byteRanges: ReadonlyArray<readonly [number, number]>,
): Array<{ readonly start: number; readonly end: number }> {
const lineBytes = Buffer.from(line);
const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
return byteRanges.map(([startByte, endByte]) => ({
start: toStringIndex(startByte),
end: toStringIndex(endByte),
}));
}
/**
* Whole-word filtering happens after the grep rather than by wrapping the
* pattern in boundary regex: consuming boundaries such as `(?:^|\W)` swallow
* the separator between adjacent matches and widen the reported ranges, and
* `\b` cannot match punctuation-edged queries at all. Matching VS Code, a
* match edge is a word boundary when it touches the line edge, the
* neighbouring character is not a word character, or the match's own edge
* character is not a word character.
*/
function isWholeWordRange(
line: string,
range: { readonly start: number; readonly end: number },
): boolean {
if (range.end <= range.start) return false;
const isWord = (character: string | undefined) =>
character !== undefined && WORD_CHARACTER.test(character);
const leftIsBoundary =
range.start === 0 ||
!isWord(codePointBefore(line, range.start)) ||
!isWord(codePointAt(line, range.start));
const rightIsBoundary =
range.end >= line.length ||
!isWord(codePointAt(line, range.end)) ||
!isWord(codePointBefore(line, range.end));
return leftIsBoundary && rightIsBoundary;
}
function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
for (const entry of entries) {
@@ -169,13 +292,19 @@ function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEn
return [...entryByPath.values()];
}
const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (cwd: string) {
const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
cwd: string,
variant: WorkspaceSearchIndexVariant,
) {
const result = yield* Effect.try({
try: () =>
FileFinder.create({
basePath: cwd,
disableMmapCache: true,
disableContentIndexing: true,
// Content indexing costs scan CPU and memory, so only the on-demand
// content-search index pays for it; path-only consumers (file tree,
// composer path search, file picker) keep the lightweight index.
disableContentIndexing: variant !== "content",
aiMode: false,
enableFsRootScanning: true,
enableHomeDirScanning: true,
@@ -194,53 +323,65 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (c
});
});
const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unknown) => E) =>
Effect.try({
try: () => finder.isScanning(),
catch: onFailure,
}).pipe(
Effect.repeat({
while: (scanning) => scanning,
schedule: Schedule.spaced(WORKSPACE_INDEX_SCAN_POLL_INTERVAL),
}),
Effect.timeoutOrElse({
duration: WORKSPACE_INDEX_SCAN_TIMEOUT,
orElse: () =>
new WorkspaceSearchIndexScanTimedOut({ cwd, timeout: WORKSPACE_INDEX_SCAN_TIMEOUT }),
}),
Effect.withSpan("WorkspaceSearchIndex.waitForScan"),
);
const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
cwd: string,
finder: FileFinder,
onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
const result = yield* Effect.tryPromise({
try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
catch: (cause) =>
onFailure({
reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
cause,
}),
});
if (!result.ok) {
return yield* Effect.fail(onFailure({ reason: result.error }));
}
if (!result.value) {
return yield* new WorkspaceSearchIndexScanTimedOut({
cwd,
timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
});
}
});
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
cwd: string,
variant: WorkspaceSearchIndexVariant = "paths",
) {
const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
Effect.try({
try: () => finder.destroy(),
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
}).pipe(Effect.orDie),
);
yield* waitForScan(
yield* waitForIndexReady(
cwd,
finder,
(cause) =>
({ reason, cause }) =>
new WorkspaceSearchIndexCreateFailed({
cwd,
reason: "FileFinder.isScanning threw while creating the index.",
reason,
cause,
}),
);
const runMixedSearch = Effect.fn("WorkspaceSearchIndex.runMixedSearch")(function* (
const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
query: string,
pageSize: number,
) {
operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
execute: () => Result<A>,
): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
const result = yield* Effect.try({
try: () => finder.mixedSearch(query, { pageSize }),
try: execute,
catch: (cause) =>
new WorkspaceSearchIndexSearchFailed({
cwd,
queryLength: query.length,
pageSize,
reason: "FileFinder.mixedSearch threw unexpectedly.",
reason: `FileFinder.${operation} threw unexpectedly.`,
cause,
}),
});
@@ -273,13 +414,13 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: strin
reason: result.error,
});
}
yield* waitForScan(
yield* waitForIndexReady(
cwd,
finder,
(cause) =>
({ reason, cause }) =>
new WorkspaceSearchIndexRefreshFailed({
cwd,
reason: "FileFinder.isScanning threw while refreshing the index.",
reason,
cause,
}),
);
@@ -287,7 +428,9 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: strin
const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
function* () {
const result = yield* runMixedSearch("", WORKSPACE_INDEX_PAGE_SIZE);
const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
);
const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
left.path.localeCompare(right.path),
@@ -302,20 +445,112 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: strin
const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
"WorkspaceSearchIndex.search",
)(function* (query, limit) {
const result = yield* runMixedSearch(query, Math.max(1, limit + 1));
)(function* (query, limit, kind) {
const pageSize = Math.max(1, limit + 1);
if (kind === "file") {
const result = yield* runSearch(query, pageSize, "fileSearch", () =>
finder.fileSearch(query, { pageSize }),
);
return mapFileSearchResult(result, limit);
}
if (kind === "directory") {
const result = yield* runSearch(query, pageSize, "directorySearch", () =>
finder.directorySearch(query, { pageSize }),
);
return mapDirectorySearchResult(result, limit);
}
const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
finder.mixedSearch(query, { pageSize }),
);
return mapMixedSearchResult(result, limit);
});
return WorkspaceSearchIndex.of({ list, refresh, search });
const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
"WorkspaceSearchIndex.searchContents",
)(function* (input) {
const { searchQuery, regexMode } = buildContentSearchQuery(input);
const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
// Grep cursors advance by file, so whole-word post-filtering needs enough
// raw candidates from the current file before moving to the next one.
const rawPageSize = input.wholeWord
? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
: input.limit;
const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
let nextCursor: GrepCursor | null = null;
let regexFallbackError: string | undefined;
do {
const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
const result = yield* runSearch(input.query, input.limit, "grep", () =>
finder.grep(searchQuery, {
mode: regexMode ? "regex" : "plain",
smartCase: !input.caseSensitive && !regexMode,
// A single dense file must not consume the whole result page.
maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
pageSize: rawPageSize,
cursor: nextCursor,
timeBudgetMs: remainingTimeBudgetMs,
}),
);
for (const match of result.items) {
const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
(range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
);
if (matchRanges.length === 0) continue;
matches.push({
path: toPosixPath(match.relativePath),
lineNumber: match.lineNumber,
lineContent: match.lineContent,
matchRanges,
});
}
nextCursor = result.nextCursor;
regexFallbackError ??= result.regexFallbackError;
} while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);
return {
matches: matches.slice(0, input.limit),
truncated: matches.length > input.limit || nextCursor !== null,
...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
};
});
return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
});
export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
/**
* Composite LayerMap key so the lightweight path index and the on-demand
* content-search index of the same workspace are separate resources with
* independent lifecycles. "\n" cannot appear in a filesystem path.
*/
export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
`${variant}\n${cwd}`;
function parseWorkspaceSearchIndexKey(key: string): {
readonly cwd: string;
readonly variant: WorkspaceSearchIndexVariant;
} {
const separatorIndex = key.indexOf("\n");
return {
variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
cwd: key.slice(separatorIndex + 1),
};
}
/**
* A layer factory is required because every index is scoped to a concrete
* workspace root. WorkspaceSearchIndexMap owns memoization and idle cleanup;
* using a default cwd here would mix resources from different workspaces.
* workspace root and variant. WorkspaceSearchIndexMap owns memoization and
* idle cleanup; using a default cwd here would mix resources from different
* workspaces.
*/
export const layer = (cwd: string) => Layer.effect(WorkspaceSearchIndex, make(cwd));
export const layer = (key: string) => {
const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
};
export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
"t3/workspace/WorkspaceSearchIndexMap",
+18
View File
@@ -37,6 +37,7 @@ import {
type ProjectFileOperation,
ProjectListEntriesError,
ProjectReadFileError,
ProjectSearchContentsError,
ProjectSearchEntriesError,
ProjectWriteFileError,
RelayClientInstallFailedError,
@@ -1597,6 +1598,23 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.projectsSearchContents]: (input) =>
observeRpcEffect(
WS_METHODS.projectsSearchContents,
workspaceEntries.searchContents(input).pipe(
Effect.mapError(
(cause) =>
new ProjectSearchContentsError({
cwd: input.cwd,
queryLength: input.query.length,
limit: input.limit,
...projectEntriesFailureContext(cause),
cause,
}),
),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.projectsListEntries]: (input) =>
observeRpcEffect(
WS_METHODS.projectsListEntries,