From e7baa29b29718b80caaf74f2539bec134a66b343 Mon Sep 17 00:00:00 2001 From: Josh Vera Date: Sun, 21 Jul 2024 22:30:41 -0400 Subject: [PATCH 1/3] Add a unique constraint on code_snippets_tags And log errors from minisearch --- core/core.ts | 2 +- core/indexing/CodeSnippetsIndex.ts | 16 ++ gui/package-lock.json | 8 +- gui/package.json | 2 +- gui/src/hooks/useSubmenuContextProviders.tsx | 205 ++++++++++++------- 5 files changed, 148 insertions(+), 85 deletions(-) diff --git a/core/core.ts b/core/core.ts index 25e44a849..5daaa3f9f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -257,7 +257,7 @@ export class Core { }); on("context/loadSubmenuItems", async (msg) => { const config = await this.config(); - const items = config.contextProviders + const items = await config.contextProviders ?.find((provider) => provider.description.title === msg.data.title) ?.loadSubmenuItems({ ide: this.ide, diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index a5ec68f8b..739462ece 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -43,6 +43,22 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { snippetId INTEGER NOT NULL, FOREIGN KEY (snippetId) REFERENCES code_snippets (id) )`); + + // Delete duplicate entries + await db.exec(` + DELETE FROM code_snippets_tags + WHERE id NOT IN ( + SELECT MIN(id) + FROM code_snippets_tags + GROUP BY snippetId, tag + ) + `); + + // Add unique constraint if it doesn't exist + await db.exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag + ON code_snippets_tags (snippetId, tag) + `); } async getSnippetsInFile( diff --git a/gui/package-lock.json b/gui/package-lock.json index 47df1bfbb..a2cbec237 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -29,7 +29,7 @@ "dompurify": "^3.0.6", "downshift": "^7.6.0", "lodash": "^4.17.21", - "minisearch": "^6.3.0", + "minisearch": "^7.0.2", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", @@ -5237,9 +5237,9 @@ } }, "node_modules/minisearch": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-6.3.0.tgz", - "integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ==" + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.0.2.tgz", + "integrity": "sha512-Pf0sFXaCgRpOBDr4G8wTbVAEH9o9rvJzCMwj0TMe3L/NfUuG188xabfx6Vm3vD/Dv5L500n7JeiMB9Mq3sWMfQ==" }, "node_modules/monaco-editor": { "version": "0.49.0", diff --git a/gui/package.json b/gui/package.json index f0e4611e6..457d4ada4 100644 --- a/gui/package.json +++ b/gui/package.json @@ -31,7 +31,7 @@ "dompurify": "^3.0.6", "downshift": "^7.6.0", "lodash": "^4.17.21", - "minisearch": "^6.3.0", + "minisearch": "^7.0.2", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index e2da6f961..c860da56e 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -6,7 +6,7 @@ import { groupByLastNPathParts, } from "core/util"; import MiniSearch, { SearchResult } from "minisearch"; -import { useContext, useEffect, useState } from "react"; +import { useContext, useEffect, useMemo, useState } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { selectContextProviderDescriptions } from "../redux/selectors"; @@ -107,95 +107,142 @@ function useSubmenuContextProviders() { }; }, []); + const getSubmenuSearchResults = useMemo( + () => + (providerTitle: string | undefined, query: string): SearchResult[] => { + console.log( + "Executing getSubmenuSearchResults. Provider:", + providerTitle, + "Query:", + query, + ); + console.log("Current minisearches:", Object.keys(minisearches)); + if (providerTitle === undefined) { + // Return search combined from all providers + const results = Object.keys(minisearches).map((providerTitle) => { + const results = minisearches[providerTitle].search( + query, + MINISEARCH_OPTIONS, + ); + console.log(`Search results for ${providerTitle}:`, results.length); + return results.map((result) => { + return { ...result, providerTitle }; + }); + }); + + return results.flat().sort((a, b) => b.score - a.score); + } + if (!minisearches[providerTitle]) { + console.log(`No minisearch found for provider: ${providerTitle}`); + return []; + } + + const results = minisearches[providerTitle] + .search(query, MINISEARCH_OPTIONS) + .map((result) => { + return { ...result, providerTitle }; + }); + console.log(`Search results for ${providerTitle}:`, results.length); + + return results; + }, + [minisearches], + ); + + const getSubmenuContextItems = useMemo( + () => + ( + providerTitle: string | undefined, + query: string, + limit: number = MAX_LENGTH, + ): (ContextSubmenuItem & { providerTitle: string })[] => { + console.log( + "Executing getSubmenuContextItems. Provider:", + providerTitle, + "Query:", + query, + "Limit:", + limit, + ); + + const results = getSubmenuSearchResults(providerTitle, query); + if (results.length === 0) { + const fallbackItems = (fallbackResults[providerTitle] ?? []) + .slice(0, limit) + .map((result) => { + return { + ...result, + providerTitle, + }; + }); + console.log("Using fallback results:", fallbackItems.length); + return fallbackItems; + } + const limitedResults = results.slice(0, limit).map((result) => { + return { + id: result.id, + title: result.title, + description: result.description, + providerTitle: result.providerTitle, + }; + }); + return limitedResults; + }, + [fallbackResults, getSubmenuSearchResults], + ); + useEffect(() => { if (contextProviderDescriptions.length === 0 || loaded) { return; } setLoaded(true); - contextProviderDescriptions.forEach(async (description) => { - const minisearch = new MiniSearch({ - fields: ["title", "description"], - storeFields: ["id", "title", "description"], - }); - const items = await ideMessenger.request("context/loadSubmenuItems", { - title: description.title, - }); - minisearch.addAll(items); - setMinisearches((prev) => ({ ...prev, [description.title]: minisearch })); - if (description.title === "file") { - const openFiles = await getOpenFileItems(); - setFallbackResults((prev) => ({ + const loadSubmenuItems = async () => { + for (const description of contextProviderDescriptions) { + const minisearch = new MiniSearch({ + fields: ["title", "description"], + storeFields: ["id", "title", "description"], + }); + const items = await ideMessenger.request("context/loadSubmenuItems", { + title: description.title, + }); + + try { + minisearch.addAll(items); + } catch (itemError) { + console.error( + "Error adding item to minisearch:", + itemError.message, + itemError.stack, + ); + } + + setMinisearches((prev) => ({ ...prev, - file: [ - ...openFiles, - ...items.slice(0, MAX_LENGTH - openFiles.length), - ], - })); - } else { - setFallbackResults((prev) => ({ - ...prev, - [description.title]: items.slice(0, MAX_LENGTH), + [description.title]: minisearch, })); + + if (description.title === "file") { + const openFiles = await getOpenFileItems(); + setFallbackResults((prev) => ({ + ...prev, + file: [ + ...openFiles, + ...items.slice(0, MAX_LENGTH - openFiles.length), + ], + })); + } else { + setFallbackResults((prev) => ({ + ...prev, + [description.title]: items.slice(0, MAX_LENGTH), + })); + } } - }); + }; + + loadSubmenuItems(); }, [contextProviderDescriptions, loaded]); - function getSubmenuSearchResults( - providerTitle: string | undefined, - query: string, - ): SearchResult[] { - if (providerTitle === undefined) { - // Return search combined from all providers - const results = Object.keys(minisearches).map((providerTitle) => { - const results = minisearches[providerTitle].search( - query, - MINISEARCH_OPTIONS, - ); - return results.map((result) => { - return { ...result, providerTitle }; - }); - }); - - return results.flat().sort((a, b) => b.score - a.score); - } - if (!minisearches[providerTitle]) { - return []; - } - - return minisearches[providerTitle] - .search(query, MINISEARCH_OPTIONS) - .map((result) => { - return { ...result, providerTitle }; - }); - } - - function getSubmenuContextItems( - providerTitle: string | undefined, - query: string, - limit: number = MAX_LENGTH, - ): (ContextSubmenuItem & { providerTitle: string })[] { - const results = getSubmenuSearchResults(providerTitle, query); - if (results.length === 0) { - return (fallbackResults[providerTitle] ?? []) - .slice(0, limit) - .map((result) => { - return { - ...result, - providerTitle, - }; - }); - } - return results.slice(0, limit).map((result) => { - return { - id: result.id, - title: result.title, - description: result.description, - providerTitle: result.providerTitle, - }; - }); - } - return { getSubmenuContextItems, addItem, From e74abcda35146d2837fadb30c0e16ef83c434d43 Mon Sep 17 00:00:00 2001 From: Josh Vera Date: Sun, 21 Jul 2024 22:55:17 -0400 Subject: [PATCH 2/3] Delete duplicate entries and REPLACE in compute Also moves the insert snippets explicitly to CodeSnippetsIndex instead of depending on compute --- core/indexing/CodeSnippetsIndex.ts | 65 ++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 739462ece..25022532e 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -36,6 +36,21 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); + // Delete duplicate entries in code_snippets + await db.exec(` + DELETE FROM code_snippets + WHERE id NOT IN ( + SELECT MIN(id) + FROM code_snippets + GROUP BY path, cacheKey, content, title, startLine, endLine + ) + `); + + // Add unique constraint if it doesn't exist + await db.exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique + ON code_snippets (path, cacheKey, content, title, startLine, endLine) + `); await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -44,6 +59,21 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { FOREIGN KEY (snippetId) REFERENCES code_snippets (id) )`); + // Delete code_snippets associated with duplicate code_snippets_tags entries + await db.exec(` + DELETE FROM code_snippets + WHERE id IN ( + SELECT snippetId + FROM code_snippets_tags + WHERE (snippetId, tag) IN ( + SELECT snippetId, tag + FROM code_snippets_tags + GROUP BY snippetId, tag + HAVING COUNT(*) > 1 + ) + ) + `); + // Delete duplicate entries await db.exec(` DELETE FROM code_snippets_tags @@ -109,12 +139,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ); } catch (e) { // If can't parse, assume malformatted code + console.error(`Error parsing ${compute.path}:`, e); } // Add snippets to sqlite for (const snippet of snippets) { const { lastID } = await db.run( - "INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", [ compute.path, compute.cacheKey, @@ -126,7 +157,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ); await db.run( - "INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", + "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", [lastID, tagString], ); } @@ -152,15 +183,33 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } for (let i = 0; i < results.addTag.length; i++) { - const snippetsWithPath = await db.all( - "SELECT * FROM code_snippets WHERE cacheKey = ?", - [results.addTag[i].cacheKey], - ); + const addTag = results.addTag[i]; + let snippets: (ChunkWithoutID & { title: string })[] = []; + try { + snippets = await this.getSnippetsInFile( + addTag.path, + await this.ide.readFile(addTag.path), + ); + } catch (e) { + // If can't parse, assume malformatted code + console.error(`Error parsing ${addTag.path}:`, e); + } - for (const snippet of snippetsWithPath) { + for (const snippet of snippets) { + const { lastID } = await db.run( + "INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + [ + addTag.path, + addTag.cacheKey, + snippet.content, + snippet.title, + snippet.startLine, + snippet.endLine, + ], + ); await db.run( "INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", - [snippet.id, tagString], + [lastID, tagString], ); } From 511b789c1435f5b72968b3f97fcd01b1283b2fb8 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 5 Aug 2024 19:29:21 -0400 Subject: [PATCH 3/3] use a migration for removing duplicate snippets --- core/indexing/CodeSnippetsIndex.ts | 90 ++++++++++++++++-------------- 1 file changed, 47 insertions(+), 43 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 25022532e..8fc1ccb95 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -7,6 +7,7 @@ import type { IndexingProgressUpdate, } from "../index.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; +import { migrate } from "../util/paths.js"; import { TSQueryType, getParserForFile, @@ -36,21 +37,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); - // Delete duplicate entries in code_snippets - await db.exec(` - DELETE FROM code_snippets - WHERE id NOT IN ( - SELECT MIN(id) - FROM code_snippets - GROUP BY path, cacheKey, content, title, startLine, endLine - ) - `); - - // Add unique constraint if it doesn't exist - await db.exec(` - CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique - ON code_snippets (path, cacheKey, content, title, startLine, endLine) - `); await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -59,36 +45,54 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { FOREIGN KEY (snippetId) REFERENCES code_snippets (id) )`); - // Delete code_snippets associated with duplicate code_snippets_tags entries - await db.exec(` - DELETE FROM code_snippets - WHERE id IN ( - SELECT snippetId - FROM code_snippets_tags - WHERE (snippetId, tag) IN ( - SELECT snippetId, tag - FROM code_snippets_tags - GROUP BY snippetId, tag - HAVING COUNT(*) > 1 - ) - ) - `); + migrate("delete_duplicate_code_snippets", async () => { + // Delete duplicate entries in code_snippets + await db.exec(` + DELETE FROM code_snippets + WHERE id NOT IN ( + SELECT MIN(id) + FROM code_snippets + GROUP BY path, cacheKey, content, title, startLine, endLine + ) + `); - // Delete duplicate entries - await db.exec(` - DELETE FROM code_snippets_tags - WHERE id NOT IN ( - SELECT MIN(id) - FROM code_snippets_tags - GROUP BY snippetId, tag - ) - `); + // Add unique constraint if it doesn't exist + await db.exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique + ON code_snippets (path, cacheKey, content, title, startLine, endLine) + `); - // Add unique constraint if it doesn't exist - await db.exec(` - CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag - ON code_snippets_tags (snippetId, tag) - `); + // Delete code_snippets associated with duplicate code_snippets_tags entries + await db.exec(` + DELETE FROM code_snippets + WHERE id IN ( + SELECT snippetId + FROM code_snippets_tags + WHERE (snippetId, tag) IN ( + SELECT snippetId, tag + FROM code_snippets_tags + GROUP BY snippetId, tag + HAVING COUNT(*) > 1 + ) + ) + `); + + // Delete duplicate entries + await db.exec(` + DELETE FROM code_snippets_tags + WHERE id NOT IN ( + SELECT MIN(id) + FROM code_snippets_tags + GROUP BY snippetId, tag + ) + `); + + // Add unique constraint if it doesn't exist + await db.exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag + ON code_snippets_tags (snippetId, tag) + `); + }); } async getSnippetsInFile(