Elffuss BraidHub

kikocis/continue public

7a512fed920f · 17.9 KiBRawPermalink
1import {
2 ContextProviderDescription,
3 ContextProviderName,
4 ContextSubmenuItemWithProvider,
5} from "core";
6import { deduplicateArray, splitCamelCaseAndNonAlphaNumeric } from "core/util";
7import {
8 getShortestUniqueRelativeUriPaths,
9 getUriPathBasename,
10} from "core/util/uri";
11import MiniSearch, { SearchResult } from "minisearch";
12import {
13 createContext,
14 useCallback,
15 useContext,
16 useEffect,
17 useRef,
18 useState,
19} from "react";
20import { useWebviewListener } from "../hooks/useWebviewListener";
21import { useAppSelector } from "../redux/hooks";
22import { selectSubmenuContextProviders } from "../redux/selectors";
23import { IdeMessengerContext } from "./IdeMessenger";
24
25const MINISEARCH_OPTIONS = {
26 prefix: true,
27 fuzzy: 2,
28};
29
30const MAX_LENGTH = 70;
31
32// Enhanced search result interface for intelligent sorting
33interface EnhancedSearchResult
34 extends SearchResult,
35 Omit<ContextSubmenuItemWithProvider, "id"> {
36 sortPriority: number;
37 matchQuality: number;
38}
39
40interface SubtextContextProvidersContextType {
41 getSubmenuContextItems: (
42 providerTitle: string | undefined,
43 query: string,
44 ) => ContextSubmenuItemWithProvider[];
45}
46
47const initialContextProviders: SubtextContextProvidersContextType = {
48 getSubmenuContextItems: () => [],
49};
50
51const SubmenuContextProvidersContext =
52 createContext<SubtextContextProvidersContextType>(initialContextProviders);
53
54// Helper functions for intelligent file sorting
55function hasExactWordMatch(text: string, query: string): boolean {
56 const words = text.split(/[^a-zA-Z0-9]+/);
57 return words.some((word) => word === query);
58}
59
60function isCommonDevFile(fileName: string): boolean {
61 const commonExtensions = [
62 ".ts",
63 ".tsx",
64 ".js",
65 ".jsx",
66 ".py",
67 ".java",
68 ".cpp",
69 ".c",
70 ".h",
71 ".vue",
72 ".svelte",
73 ];
74 const commonNames = [
75 "index",
76 "main",
77 "app",
78 "component",
79 "service",
80 "util",
81 "helper",
82 "config",
83 "types",
84 ];
85
86 const extension = fileName.substring(fileName.lastIndexOf("."));
87 const baseName = fileName
88 .substring(0, fileName.lastIndexOf("."))
89 .toLowerCase();
90
91 return commonExtensions.includes(extension) || commonNames.includes(baseName);
92}
93
94function isInCommonDirectory(filePath: string): boolean {
95 const commonDirs = [
96 "src/",
97 "lib/",
98 "components/",
99 "utils/",
100 "helpers/",
101 "services/",
102 "pages/",
103 "views/",
104 "hooks/",
105 "store/",
106 "types/",
107 "interfaces/",
108 "models/",
109 "api/",
110 ];
111 return commonDirs.some((dir) => filePath.includes(dir));
112}
113
114function matchesCamelCaseOrAbbreviation(
115 fileName: string,
116 query: string,
117): boolean {
118 // Extract capital letters for camel case matching
119 const capitals = fileName.match(/[A-Z]/g)?.join("").toLowerCase() || "";
120
121 // Check if query matches the capital letters pattern
122 if (capitals.length > 0 && capitals.includes(query)) {
123 return true;
124 }
125
126 // Check for abbreviation matches (first letters of words)
127 const words = fileName.split(/[^a-zA-Z0-9]+/).filter((w) => w.length > 0);
128 if (words.length > 1) {
129 const abbreviation = words
130 .map((word) => word[0])
131 .join("")
132 .toLowerCase();
133 return abbreviation.includes(query);
134 }
135
136 return false;
137}
138
139export const SubmenuContextProvidersProvider = ({
140 children,
141}: {
142 children: React.ReactNode;
143}) => {
144 const ideMessenger = useContext(IdeMessengerContext);
145 const submenuContextProviders = useAppSelector(selectSubmenuContextProviders);
146 const lastProviders = useRef(submenuContextProviders);
147 const disableIndexing = useAppSelector(
148 (store) => store.config.config.disableIndexing,
149 );
150
151 const [minisearches, setMinisearches] = useState<{
152 [id: string]: MiniSearch<ContextSubmenuItemWithProvider>;
153 }>({});
154 const [fallbackResults, setFallbackResults] = useState<{
155 [id: string]: ContextSubmenuItemWithProvider[];
156 }>({});
157
158 // Update open files for file provider on an interval
159 const lastOpenFilesRef = useRef<ContextSubmenuItemWithProvider[]>([]);
160 useEffect(() => {
161 function hasOpenFilesChanged(
162 newFiles: ContextSubmenuItemWithProvider[],
163 oldFiles: ContextSubmenuItemWithProvider[],
164 ) {
165 const newIds = new Set(newFiles.map((f) => f.id));
166 const oldIds = new Set(oldFiles.map((f) => f.id));
167
168 if (newIds.size !== oldIds.size) return true;
169
170 for (const id of newIds) {
171 if (!oldIds.has(id)) return true;
172 }
173
174 for (const id of oldIds) {
175 if (!newIds.has(id)) return true;
176 }
177 return false;
178 }
179
180 let isMounted = true;
181 const refreshOpenFiles = async () => {
182 if (!isMounted) return;
183
184 const openFiles = await ideMessenger.ide.getOpenFiles();
185 const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
186 const withUniquePaths = getShortestUniqueRelativeUriPaths(
187 openFiles,
188 workspaceDirs,
189 );
190 const openFileItems = withUniquePaths.map((file) => ({
191 id: file.uri,
192 title: getUriPathBasename(file.uri),
193 description: file.uniquePath,
194 providerTitle: "file",
195 }));
196
197 if (hasOpenFilesChanged(openFileItems, lastOpenFilesRef.current)) {
198 setFallbackResults((prev) => ({
199 ...prev,
200 file: deduplicateArray(
201 [...openFileItems, ...(prev.file ?? [])],
202 (a, b) => a.id === b.id,
203 ),
204 }));
205 }
206 lastOpenFilesRef.current = openFileItems;
207 };
208
209 const interval = setInterval(refreshOpenFiles, 2000);
210
211 refreshOpenFiles(); // Initial call
212
213 return () => {
214 isMounted = false;
215 clearInterval(interval);
216 };
217 }, [ideMessenger]);
218
219 const providersLoading = useRef(new Set<ContextProviderName>()).current;
220 const abortControllers = useRef(
221 new Map<ContextProviderName, AbortController>(),
222 ).current;
223
224 const calculateFileSortPriority = useCallback(
225 (
226 result: SearchResult & ContextSubmenuItemWithProvider,
227 query: string,
228 openFiles: ContextSubmenuItemWithProvider[],
229 ): number => {
230 const fileName = result.title.toLowerCase();
231 const filePath = result.description.toLowerCase();
232 const queryLower = query.toLowerCase();
233
234 // Priority 1: Exact filename match
235 if (fileName === queryLower) {
236 return 1;
237 }
238
239 // Priority 2: Recently opened files
240 if (openFiles.some((f) => f.id === result.id)) {
241 return 2;
242 }
243
244 // Priority 3: Filename starts with query
245 if (fileName.startsWith(queryLower)) {
246 return 3;
247 }
248
249 // Priority 4: Exact word match in filename
250 if (hasExactWordMatch(fileName, queryLower)) {
251 return 4;
252 }
253
254 // Priority 5: Common development files
255 if (isCommonDevFile(fileName)) {
256 return 5;
257 }
258
259 // Priority 6: Files in common directories
260 if (isInCommonDirectory(filePath)) {
261 return 6;
262 }
263
264 // Priority 7: CamelCase/abbreviation matches
265 if (matchesCamelCaseOrAbbreviation(fileName, queryLower)) {
266 return 7;
267 }
268
269 // Priority 8: Path starts with query
270 if (filePath.startsWith(queryLower)) {
271 return 8;
272 }
273
274 // Priority 9: Default
275 return 9;
276 },
277 [],
278 );
279
280 const calculateMatchQuality = useCallback(
281 (
282 result: SearchResult & ContextSubmenuItemWithProvider,
283 query: string,
284 ): number => {
285 const fileName = result.title.toLowerCase();
286 const queryLower = query.toLowerCase();
287 let quality = 0;
288
289 // Exact match bonus
290 if (fileName === queryLower) quality += 100;
291
292 // Prefix match bonus
293 if (fileName.startsWith(queryLower)) quality += 50;
294
295 // Contains match bonus
296 if (fileName.includes(queryLower)) quality += 25;
297
298 // Shorter filename bonus (prefer concise names)
299 quality += Math.max(0, 50 - fileName.length);
300
301 // Extension preference (common dev files)
302 if (
303 fileName.endsWith(".ts") ||
304 fileName.endsWith(".tsx") ||
305 fileName.endsWith(".js") ||
306 fileName.endsWith(".jsx")
307 ) {
308 quality += 10;
309 }
310
311 return quality;
312 },
313 [],
314 );
315
316 const getSubmenuContextItems = useCallback(
317 (
318 providerTitle: string | undefined,
319 query: string,
320 limit: number = MAX_LENGTH,
321 ): ContextSubmenuItemWithProvider[] => {
322 try {
323 // 1. Search using minisearch
324 let searchResults: (SearchResult & ContextSubmenuItemWithProvider)[] =
325 [];
326
327 if (providerTitle === undefined) {
328 // Include results from all providers
329 searchResults = Object.keys(minisearches).flatMap((providerTitle) =>
330 minisearches[providerTitle]
331 .search(query, MINISEARCH_OPTIONS)
332 .map((result) => {
333 return {
334 ...result,
335 providerTitle,
336 title: result.title,
337 description: result.description,
338 };
339 }),
340 );
341 } else {
342 // Only include results from the specified provider
343 if (minisearches[providerTitle]) {
344 searchResults = minisearches[providerTitle]
345 .search(query, MINISEARCH_OPTIONS)
346 .map((result) => {
347 return {
348 ...result,
349 providerTitle,
350 title: result.title,
351 description: result.description,
352 };
353 });
354 }
355 }
356
357 // 2. Enhanced sorting for file provider
358 if (
359 providerTitle === "file" ||
360 (!providerTitle &&
361 searchResults.some((r) => r.providerTitle === "file"))
362 ) {
363 const enhancedResults: EnhancedSearchResult[] = searchResults.map(
364 (result): EnhancedSearchResult => ({
365 ...result,
366 id: result.id,
367 title: result.title,
368 description: result.description,
369 providerTitle: result.providerTitle,
370 sortPriority: calculateFileSortPriority(
371 result,
372 query,
373 lastOpenFilesRef.current,
374 ),
375 matchQuality: calculateMatchQuality(result, query),
376 }),
377 );
378
379 // Sort by multiple criteria
380 enhancedResults.sort((a, b) => {
381 // Primary: Sort priority (lower = better)
382 if (a.sortPriority !== b.sortPriority) {
383 return a.sortPriority - b.sortPriority;
384 }
385
386 // Secondary: Match quality (higher = better)
387 if (a.matchQuality !== b.matchQuality) {
388 return b.matchQuality - a.matchQuality;
389 }
390
391 // Tertiary: MiniSearch relevance score (higher = better)
392 if (a.score !== b.score) {
393 return b.score - a.score;
394 }
395
396 // Quaternary: Path length (shorter = better)
397 return a.description.length - b.description.length;
398 });
399
400 searchResults = enhancedResults;
401 } else {
402 // Default sorting for non-file providers
403 searchResults.sort((a, b) => b.score - a.score);
404 }
405
406 // 3. Add fallback results if no search results
407 if (searchResults.length === 0) {
408 const fallbackItems = (
409 providerTitle ? (fallbackResults[providerTitle] ?? []) : []
410 )
411 .slice(0, limit)
412 .map((result) => {
413 return {
414 ...result,
415 providerTitle: providerTitle || "unknown",
416 };
417 });
418
419 if (fallbackItems.length === 0) {
420 const loadingFiller = [
421 {
422 id: "loading",
423 title: "Loading...",
424 description: "Please wait while items are being loaded",
425 providerTitle: providerTitle || "unknown",
426 },
427 ];
428
429 // If getting for all providers
430 if (!providerTitle) {
431 // then show loading if ANY loading
432 if (providersLoading.size > 0) {
433 return loadingFiller;
434 }
435 } else {
436 // Otherwise just check if the provider is loading
437 if (providersLoading.has(providerTitle)) {
438 return loadingFiller;
439 }
440 }
441 }
442
443 return fallbackItems;
444 }
445 const limitedResults = searchResults.slice(0, limit).map((result) => {
446 return {
447 id: result.id,
448 title: result.title,
449 description: result.description,
450 providerTitle: result.providerTitle,
451 };
452 });
453 return limitedResults;
454 } catch (error) {
455 console.error("Error in getSubmenuContextItems:", error);
456 return [];
457 }
458 },
459 [
460 fallbackResults,
461 minisearches,
462 calculateFileSortPriority,
463 calculateMatchQuality,
464 ],
465 );
466
467 const loadSubmenuItems = useCallback(
468 async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => {
469 await Promise.allSettled(
470 submenuContextProviders.map(
471 async (description: ContextProviderDescription) => {
472 const controller = new AbortController();
473 try {
474 const refreshProvider =
475 providers === "all"
476 ? true
477 : providers === "dependsOnIndexing"
478 ? description.dependsOnIndexing
479 : providers.includes(description.title);
480
481 if (!refreshProvider) {
482 if (providers === "dependsOnIndexing") {
483 console.debug(
484 `Skipping ${description.title} provider due to disabled indexing`,
485 );
486 }
487 return;
488 }
489
490 // Submenu loading requests cancel existing requests
491 abortControllers.get(description.title)?.abort();
492 abortControllers.set(description.title, controller);
493 providersLoading.add(description.title);
494
495 const result = await ideMessenger.request(
496 "context/loadSubmenuItems",
497 {
498 title: description.title,
499 },
500 );
501
502 // IMPORTANT - the controller only prevents invalid loading state
503 // But does not cancel using data from the request
504 // Could uncomment this to truly cancel the request
505 // if (controller.signal.aborted) {
506 // return console.debug(
507 // `${description.title} provider loading aborted`,
508 // );
509 // }
510
511 if (result.status === "error") {
512 throw new Error(result.error);
513 }
514 const submenuItems = result.content;
515 const providerTitle = description.title;
516 const renderInlineAs = description.renderInlineAs;
517
518 const itemsWithProvider = submenuItems.map((item) => ({
519 ...item,
520 providerTitle,
521 renderInlineAs,
522 }));
523
524 const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>(
525 {
526 fields: ["title", "description"],
527 storeFields: ["id", "title", "description", "providerTitle"],
528 tokenize: (text) =>
529 deduplicateArray(
530 MiniSearch.getDefault("tokenize")(text).concat(
531 splitCamelCaseAndNonAlphaNumeric(text),
532 ),
533 (a, b) => a === b,
534 ),
535 },
536 );
537
538 const deduplicatedItems = deduplicateArray(
539 submenuItems.map((item) => ({ ...item, providerTitle })),
540 (a, b) => a.id === b.id,
541 );
542 minisearch.addAll(deduplicatedItems);
543
544 setMinisearches((prev) => ({
545 ...prev,
546 [providerTitle]: minisearch,
547 }));
548
549 if (providerTitle === "file") {
550 setFallbackResults((prev) => ({
551 ...prev,
552 file: deduplicateArray(
553 [...lastOpenFilesRef.current, ...itemsWithProvider],
554 (a, b) => a.id === b.id,
555 ),
556 }));
557 } else {
558 setFallbackResults((prev) => ({
559 ...prev,
560 [providerTitle]: itemsWithProvider,
561 }));
562 }
563 } catch (error) {
564 console.error(
565 `Error loading items for ${description.title}:`,
566 error,
567 );
568 console.error(
569 "Error details:",
570 JSON.stringify(error, Object.getOwnPropertyNames(error)),
571 );
572 } finally {
573 if (!controller.signal.aborted) {
574 providersLoading.delete(description.title);
575 }
576 }
577 },
578 ),
579 );
580 },
581 [
582 submenuContextProviders,
583 disableIndexing,
584 providersLoading,
585 abortControllers,
586 ],
587 );
588
589 useWebviewListener(
590 "refreshSubmenuItems",
591 async (data) => {
592 loadSubmenuItems(data.providers);
593 },
594 [loadSubmenuItems],
595 );
596
597 // Reload all submenu items on the initial config load
598 useEffect(() => {
599 if (!submenuContextProviders.length) {
600 return;
601 }
602 // Refresh submenu items when new titles detected
603 const newTitles = submenuContextProviders
604 .filter(
605 (provider) =>
606 !lastProviders.current.find((p) => p.title === provider.title),
607 )
608 .map((provider) => provider.title);
609 if (newTitles.length > 0) {
610 loadSubmenuItems(newTitles);
611 }
612 lastProviders.current = submenuContextProviders;
613 }, [loadSubmenuItems, submenuContextProviders]);
614
615 return (
616 <SubmenuContextProvidersContext.Provider
617 value={{
618 getSubmenuContextItems,
619 }}
620 >
621 {children}
622 </SubmenuContextProvidersContext.Provider>
623 );
624};
625
626export const useSubmenuContextProviders = () =>
627 useContext(SubmenuContextProvidersContext);