Add global project content search #4007
Closedjakeleventhal(GitHub profile, opens in a new tab)wants to merge 3 commits into
main fromrefs/pull/4007/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/workspace/WorkspaceSearchIndex.ts lines 325 to 325OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -307,4 +312,14 @@307312 return mapMixedSearchResult(result, limit);308313 });309314310- return WorkspaceSearchIndex.of({ list, refresh, search });315+ const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(316+ "WorkspaceSearchIndex.searchContents",317+ )(function* (input) {318+ const escapedQuery = input.query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");319+ const wordCharacter = /[\p{Letter}\p{Mark}\p{Number}_]/u;320+ const firstCharacter = Array.from(input.query).at(0) ?? "";321+ const lastCharacter = Array.from(input.query).at(-1) ?? "";322+ const literalWholeWordQuery = `${wordCharacter.test(firstCharacter) ? "\\b" : "(?:^|\\W)"}(?:${escapedQuery})${wordCharacter.test(lastCharacter) ? "\\b" : "(?:$|\\W)"}`;323+ const query = input.wholeWord324+ ? input.useRegex325+ ? `\\b(?:${input.query})\\b`
- apps/web/src/components/ProjectContentSearchDialog.tsx line 187Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +167,21 @@167+ >168+ .*169+ </SearchOptionButton>170+ </div>171+ </div>172+173+ <div className="flex min-h-0 flex-1 flex-col">174+ <div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">175+ {search.isPending ? (176+ <span className="flex items-center gap-2">177+ <LoaderCircle className="size-3.5 animate-spin" /> Searching…178+ </span>179+ ) : search.error ? (180+ <span className="text-destructive">{search.error}</span>181+ ) : search.invalidRegex ? (182+ <span className="text-destructive">Invalid regular expression</span>183+ ) : !search.hasQuery ? (184+ `Search every file in ${props.projectName}`185+ ) : (186+ `${matches.length.toLocaleString()}${search.truncated ? "+" : ""} results in ${fileCount.toLocaleString()} files`187+ )}apps/web/src/components/files/FileBrowserPanel.tsx line 218Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -75,0 +84,21 @@84+85+ syncingSelectionRef.current = true;86+ model.closeSearch();87+ for (const path of model.getSelectedPaths()) {88+ model.getItem(path)?.deselect();89+ }90+91+ const segments = selectedPath.split("/");92+ let ancestorPath = "";93+ for (const segment of segments.slice(0, -1)) {94+ ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;95+ const item = model.getItem(ancestorPath);96+ if (item && "expand" in item) item.expand();97+ }98+99+ model.getItem(selectedPath)?.select();100+ model.scrollToPath(selectedPath, { focus: true, offset: "center" });101+ queueMicrotask(() => {102+ syncingSelectionRef.current = false;103+ });104+ }, [entryKinds, model, selectedPath, selectedPathRevealId, treePaths]);apps/server/src/workspace/WorkspaceSearchIndex.ts line 387Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -310,0 +367,21 @@367+ const end = byteOffsetToStringIndex(line, endByte);368+ if (!input.wholeWord || input.useRegex) return { start, end };369+370+ const matchedText = line.slice(start, end);371+ const queryIndex = input.caseSensitive372+ ? matchedText.indexOf(input.query)373+ : matchedText.toLocaleLowerCase().indexOf(input.query.toLocaleLowerCase());374+ return queryIndex === -1375+ ? { start, end }376+ : { start: start + queryIndex, end: start + queryIndex + input.query.length };377+ };378+ return {379+ matches: result.value.items.map((match) => ({380+ path: toPosixPath(match.relativePath),381+ lineNumber: match.lineNumber,382+ lineContent: match.lineContent,383+ matchRanges: match.matchRanges.map(([start, end]) =>384+ mapMatchRange(match.lineContent, start, end),385+ ),386+ })),387+ truncated: result.value.nextCursor !== null,apps/web/src/components/files/FilePreviewPanel.tsx line 945Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -893,3 +893,5 @@893893 environmentId={environmentId}894894 cwd={cwd}895895 projectName={projectName}896+ selectedPath={relativePath}897+ selectedPathRevealId={revealRequestId}apps/web/src/components/files/FileBrowserPanel.tsx line 197Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -73,3 +79,5 @@7379 model.resetPaths(treePaths);7480 }, [entryKinds, model, treePaths]);758182+ useEffect(() => {83+ if (!selectedPath || entryKinds.get(selectedPath) !== "file") return;
- @@ -310,0 +359,21 @@359+ reason: result.error,360+ });361+ }362+363+ const byteOffsetToStringIndex = (line: string, byteOffset: number): number =>364+ Buffer.from(line).subarray(0, byteOffset).toString().length;365+ const mapMatchRange = (line: string, startByte: number, endByte: number) => {366+ const start = byteOffsetToStringIndex(line, startByte);367+ const end = byteOffsetToStringIndex(line, endByte);368+ if (!input.wholeWord || input.useRegex) return { start, end };369+370+ const matchedText = line.slice(start, end);371+ const queryIndex = input.caseSensitive372+ ? matchedText.indexOf(input.query)373+ : matchedText.toLocaleLowerCase().indexOf(input.query.toLocaleLowerCase());374+ return queryIndex === -1375+ ? { start, end }376+ : { start: start + queryIndex, end: start + queryIndex + input.query.length };377+ };378+ return {379+ matches: result.value.items.map((match) => ({@@ -216,0 +233,21 @@233+ const result = useEnvironmentQuery(234+ target.environmentId !== null &&235+ target.cwd !== null &&236+ query.length > 0 &&237+ debouncedQuery.length > 0238+ ? projectEnvironment.searchContents({239+ environmentId: target.environmentId,240+ input: {241+ cwd: target.cwd,242+ query: debouncedQuery,243+ limit: PROJECT_CONTENT_SEARCH_LIMIT,244+ caseSensitive: target.caseSensitive,245+ wholeWord: target.wholeWord,246+ useRegex: target.useRegex,247+ },248+ })249+ : null,250+ );251+252+ return {253+ matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES,@@ -73,3 +79,17 @@7379 model.resetPaths(treePaths);7480 }, [entryKinds, model, treePaths]);758182+ useEffect(() => {83+ if (!selectedPath || entryKinds.get(selectedPath) !== "file") return;84+85+ syncingSelectionRef.current = true;86+ model.closeSearch();87+ for (const path of model.getSelectedPaths()) {88+ model.getItem(path)?.deselect();89+ }90+91+ const segments = selectedPath.split("/");92+ let ancestorPath = "";93+ for (const segment of segments.slice(0, -1)) {94+ ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;95+ const item = model.getItem(ancestorPath);
- apps/server/src/workspace/WorkspaceSearchIndex.ts line 368Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -310,0 +348,21 @@348+ queryLength: input.query.length,349+ pageSize: input.limit,350+ reason: "FileFinder.grep threw unexpectedly.",351+ cause,352+ }),353+ });354+ if (!result.ok) {355+ return yield* new WorkspaceSearchIndexSearchFailed({356+ cwd,357+ queryLength: input.query.length,358+ pageSize: input.limit,359+ reason: result.error,360+ });361+ }362+363+ const byteOffsetToStringIndex = (line: string, byteOffset: number): number =>364+ Buffer.from(line).subarray(0, byteOffset).toString().length;365+ const mapMatchRange = (line: string, startByte: number, endByte: number) => {366+ const start = byteOffsetToStringIndex(line, startByte);367+ const end = byteOffsetToStringIndex(line, endByte);368+ if (!input.wholeWord || input.useRegex) return { start, end };@@ -170,2 +176,21 @@170176 }, [entryKinds, model, treePaths]);171177178+ useEffect(() => {179+ if (!selectedPath || entryKinds.get(selectedPath) !== "file") return;180+181+ syncingSelectionRef.current = true;182+ model.closeSearch();183+ for (const path of model.getSelectedPaths()) {184+ model.getItem(path)?.deselect();185+ }186+187+ const segments = selectedPath.split("/");188+ let ancestorPath = "";189+ for (const segment of segments.slice(0, -1)) {190+ ancestorPath = ancestorPath ? `${ancestorPath}/${segment}` : segment;191+ const item = model.getItem(ancestorPath);192+ if (item && "expand" in item) item.expand();193+ }194+195+ model.getItem(selectedPath)?.select();196+ model.scrollToPath(selectedPath, { focus: true, offset: "center" });
- @@ -307,4 +312,15 @@307312 return mapMixedSearchResult(result, limit);308313 });309314310- return WorkspaceSearchIndex.of({ list, refresh, search });315+ const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(316+ "WorkspaceSearchIndex.searchContents",317+ )(function* (input) {318+ const escapedQuery = input.query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");319+ const wordCharacter = /[\p{Letter}\p{Mark}\p{Number}_]/u;320+ const firstCharacter = Array.from(input.query).at(0) ?? "";321+ const lastCharacter = Array.from(input.query).at(-1) ?? "";322+ // Use \b only when the pattern edge is a word character; otherwise \b cannot323+ // match (e.g. query "foo-" → \b(?:foo-)\b never matches "foo- "). Fall back to324+ // (?:^|\W)/(?:$|\W) for non-word edges, same as the literal whole-word path.325+ const wrapWholeWord = (pattern: string) =>326+ `${wordCharacter.test(firstCharacter) ? "\\b" : "(?:^|\\W)"}(?:${pattern})${wordCharacter.test(lastCharacter) ? "\\b" : "(?:$|\\W)"}`;@@ -26,3 +27,6 @@2627 });2728 export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;282930+export const ProjectSearchContentsInput = Schema.Struct({31+ cwd: TrimmedNonEmptyString,32+ query: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
- apps/web/src/components/ProjectContentSearchDialog.tsx line 141Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+ <div className="flex shrink-0 items-center gap-2 border-b p-2">122+ <Search className="ml-1 size-4 shrink-0 text-muted-foreground" />123+ <Input124+ autoFocus125+ nativeInput126+ unstyled127+ value={query}128+ onChange={(event) => setQuery(event.currentTarget.value)}129+ onKeyDown={(event) => {130+ if (event.key === "ArrowDown" && matches.length > 0) {131+ event.preventDefault();132+ setSelectedIndex((current) => (current + 1) % matches.length);133+ } else if (event.key === "ArrowUp" && matches.length > 0) {134+ event.preventDefault();135+ setSelectedIndex((current) => (current - 1 + matches.length) % matches.length);136+ } else if (event.key === "Enter") {137+ const match = matches[selectedIndex];138+ if (match) {139+ event.preventDefault();140+ openMatch(match);141+ }
- @@ -310,0 +322,21 @@322+ // Use \b only when the pattern edge is a word character; otherwise \b cannot323+ // match (e.g. query "foo-" → \b(?:foo-)\b never matches "foo- "). Fall back to324+ // (?:^|\W)/(?:$|\W) for non-word edges, same as the literal whole-word path.325+ const wrapWholeWord = (pattern: string) =>326+ `${wordCharacter.test(firstCharacter) ? "\\b" : "(?:^|\\W)"}(?:${pattern})${wordCharacter.test(lastCharacter) ? "\\b" : "(?:$|\\W)"}`;327+ const query = input.wholeWord328+ ? wrapWholeWord(input.useRegex ? input.query : escapedQuery)329+ : input.query;330+ const regexMode = input.useRegex || input.wholeWord;331+ const searchQuery = input.caseSensitive332+ ? query333+ : regexMode334+ ? `(?i:${query})`335+ : query.toLowerCase();336+ const result = yield* Effect.try({337+ try: () =>338+ finder.grep(searchQuery, {339+ mode: regexMode ? "regex" : "plain",340+ smartCase: !input.caseSensitive && !regexMode,341+ maxMatchesPerFile: input.limit,342+ pageSize: input.limit,@@ -310,0 +321,21 @@321+ const lastCharacter = Array.from(input.query).at(-1) ?? "";322+ // Use \b only when the pattern edge is a word character; otherwise \b cannot323+ // match (e.g. query "foo-" → \b(?:foo-)\b never matches "foo- "). Fall back to324+ // (?:^|\W)/(?:$|\W) for non-word edges, same as the literal whole-word path.325+ const wrapWholeWord = (pattern: string) =>326+ `${wordCharacter.test(firstCharacter) ? "\\b" : "(?:^|\\W)"}(?:${pattern})${wordCharacter.test(lastCharacter) ? "\\b" : "(?:$|\\W)"}`;327+ const query = input.wholeWord328+ ? wrapWholeWord(input.useRegex ? input.query : escapedQuery)329+ : input.query;330+ const regexMode = input.useRegex || input.wholeWord;331+ const searchQuery = input.caseSensitive332+ ? query333+ : regexMode334+ ? `(?i:${query})`335+ : query.toLowerCase();336+ const result = yield* Effect.try({337+ try: () =>338+ finder.grep(searchQuery, {339+ mode: regexMode ? "regex" : "plain",340+ smartCase: !input.caseSensitive && !regexMode,341+ maxMatchesPerFile: input.limit,
- @@ -0,0 +78,21 @@78+ const [useRegex, setUseRegex] = useState(false);79+ const [selectedIndex, setSelectedIndex] = useState(0);80+81+ const search = useProjectContentSearch({82+ environmentId: props.open ? props.environmentId : null,83+ cwd: props.open ? props.cwd : null,84+ query,85+ caseSensitive,86+ wholeWord,87+ useRegex,88+ });89+ const matches = search.matches;90+ const groups = useMemo(() => groupMatches(matches), [matches]);91+92+ useEffect(() => {93+ if (!props.open) setQuery("");94+ }, [props.open]);95+96+ useEffect(() => {97+ setSelectedIndex(0);98+ }, [matches]);
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
15e03ea3-4aaa-4df8-8801-4b8d5350cffcYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share