From 9d2fad9ad0ce5d43a6b69c7da9aea0d54c79ad81 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 16:30:40 -0800 Subject: [PATCH 01/21] docs UI start with indexing per file --- core/core.ts | 80 +++++++++--- core/indexing/CodebaseIndexer.ts | 77 ++++++++--- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 3 +- .../ContinuePluginStartupActivity.kt | 4 +- .../toolWindow/ContinueBrowser.kt | 1 + extensions/vscode/package-lock.json | 4 +- .../vscode/src/extension/VsCodeExtension.ts | 10 +- gui/src/pages/More/IndexingProgress/index.ts | 1 - gui/src/pages/More/More.tsx | 2 +- .../IndexingProgressBar.tsx | 2 +- .../IndexingProgressIndicator.tsx | 2 +- .../IndexingProgressSubtext.tsx | 0 .../IndexingProgressTitleText.tsx | 10 +- .../codebase}/IndexingProgressErrorText.tsx | 4 +- .../codebase/index.tsx} | 34 ++--- gui/src/pages/More/progress/docs/index.tsx | 121 ++++++++++++++++++ gui/src/pages/More/progress/index.ts | 17 +++ 18 files changed, 290 insertions(+), 83 deletions(-) delete mode 100644 gui/src/pages/More/IndexingProgress/index.ts rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressBar.tsx (91%) rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressIndicator.tsx (95%) rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressSubtext.tsx (100%) rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressTitleText.tsx (65%) rename gui/src/pages/More/{IndexingProgress => progress/codebase}/IndexingProgressErrorText.tsx (94%) rename gui/src/pages/More/{IndexingProgress/IndexingProgress.tsx => progress/codebase/index.tsx} (75%) create mode 100644 gui/src/pages/More/progress/docs/index.tsx create mode 100644 gui/src/pages/More/progress/index.ts diff --git a/core/core.ts b/core/core.ts index 6df1482ef..a5514490a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -83,7 +83,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -174,7 +174,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -684,9 +684,14 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); + on("index/forceReIndexFiles", async ({ data }) => { + if (data?.files?.length) { + await this.refreshCodebaseIndexFiles(data.files); + } + }); on("index/setPaused", (msg) => { new GlobalContext().update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; @@ -722,14 +727,29 @@ export class Core { } private indexingCancellationController: AbortController | undefined; + private async sendIndexingTelemetry(update: IndexingProgressUpdate) { + console.debug( + "Indexing failed with error: ", + update.desc, + update.debugInfo, + ); + void Telemetry.capture( + "indexing_error", + { + error: update.desc, + stack: update.debugInfo, + }, + false, + ); + } - private async refreshCodebaseIndex(dirs: string[]) { + private async refreshCodebaseIndex(paths: string[]) { if (this.indexingCancellationController) { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refresh( - dirs, + for await (const update of (await this.codebaseIndexerPromise).refreshDirs( + paths, this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; @@ -743,19 +763,41 @@ export class Core { this.indexingState = updateToSend; if (update.status === "failed") { - console.debug( - "Indexing failed with error: ", - update.desc, - update.debugInfo, - ); - void Telemetry.capture( - "indexing_error", - { - error: update.desc, - stack: update.debugInfo, - }, - false, - ); + void this.sendIndexingTelemetry(update); + } + } + + this.messenger.send("refreshSubmenuItems", undefined); + } + + private async refreshCodebaseIndexFiles(files: string[]) { + // Can be cancelled by codebase index but not vice versa + if ( + this.indexingCancellationController && + !this.indexingCancellationController.signal.aborted + ) { + return console.debug( + "Codebase indexing already in progress, skipping indexing of files\n" + + files.join("\n"), + ); + } + this.indexingCancellationController = new AbortController(); + for await (const update of (await this.codebaseIndexerPromise).refreshFiles( + files, + this.indexingCancellationController.signal, + )) { + let updateToSend = { ...update }; + if (update.status === "failed") { + updateToSend.status = "done"; + updateToSend.desc = "Indexing complete"; + updateToSend.progress = 1.0; + } + + void this.messenger.request("indexProgress", updateToSend); + this.indexingState = updateToSend; + + if (update.status === "failed") { + void this.sendIndexingTelemetry(update); } } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b4962d182..175e1a062 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -17,6 +17,7 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; +import { getBasename } from "../util/index.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -144,13 +145,61 @@ export class CodebaseIndexer { } } - async *refresh( - workspaceDirs: string[], + async *refreshFiles( + files: string[], + abortSignal: AbortSignal, + ): AsyncGenerator { + let progress = 0; + if (files.length === 0) { + yield { + progress: 1, + desc: "Indexing Complete", + status: "done", + }; + } + + const progressPer = 1 / files.length; + try { + for (const file of files) { + yield { + progress, + desc: `Indexing file ${file}...`, + status: "indexing", + }; + await this.refreshFile(file); + + progress += progressPer; + + if (this.pauseToken.paused) { + yield* this.yieldUpdateAndPause(); + } + if (abortSignal.aborted) { + yield { + progress: 1, + desc: "Indexing cancelled", + status: "disabled", + }; + return; + } + } + + yield { + progress: 1, + desc: "Indexing Complete", + status: "done", + }; + } catch (err) { + yield this.handleErrorAndGetProgressUpdate(err); + } + } + + async *refreshDirs( + dirs: string[], abortSignal: AbortSignal, ): AsyncGenerator { let progress = 0; - if (workspaceDirs.length === 0) { + if (dirs.length === 0) { yield { progress, desc: "Nothing to index", @@ -175,11 +224,9 @@ export class CodebaseIndexer { }; } - let completedDirs = 0; - // Wait until Git Extension has loaded to report progress // so we don't appear stuck at 0% while waiting - await this.ide.getRepoName(workspaceDirs[0]); + await this.ide.getRepoName(dirs[0]); yield { progress, @@ -188,16 +235,16 @@ export class CodebaseIndexer { }; const beginTime = Date.now(); - for (const directory of workspaceDirs) { + for (const directory of dirs) { const dirBasename = await this.basename(directory); yield { progress, desc: `Discovering files in ${dirBasename}...`, status: "indexing", }; - const workspaceFiles = []; + const directoryFiles = []; for await (const p of walkDirAsync(directory, this.ide)) { - workspaceFiles.push(p); + directoryFiles.push(p); if (abortSignal.aborted) { yield { progress: 1, @@ -218,7 +265,7 @@ export class CodebaseIndexer { try { for await (const updateDesc of this.indexFiles( directory, - workspaceFiles, + directoryFiles, branch, repoName, )) { @@ -240,7 +287,7 @@ export class CodebaseIndexer { nextLogThreshold += 0.025; this.logProgress( beginTime, - Math.floor(workspaceFiles.length * updateDesc.progress), + Math.floor(directoryFiles.length * updateDesc.progress), updateDesc.progress, ); } @@ -347,18 +394,18 @@ export class CodebaseIndexer { } private async *indexFiles( - workspaceDir: string, - workspaceFiles: string[], + directory: string, + files: string[], branch: string, repoName: string | undefined, ): AsyncGenerator { - const stats = await this.ide.getLastModified(workspaceFiles); + const stats = await this.ide.getLastModified(files); const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { - directory: workspaceDir, + directory, branch, artifactId: codebaseIndex.artifactId, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..e30de4673 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -147,6 +147,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, void, ]; + "index/forceReIndexFiles": [undefined | { files?: string[] }, void]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..21ac52c8d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,6 +41,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", + "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", @@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index fa39729fa..451baae68 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -169,8 +169,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // Create a data map if there are any paths to re-index if (allPaths.isNotEmpty()) { - val data = mapOf("dirs" to allPaths) - continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + val data = mapOf("files" to allPaths) + continuePluginService.coreMessenger?.request("index/forceReIndexFiles", data, null) { _ -> } } } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 26896906b..147f153e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -58,6 +58,7 @@ class ContinueBrowser(val project: Project, url: String) { "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", + "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 24930d980..29ac4731f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 06263e356..bb46e7466 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -297,17 +297,15 @@ export class VsCodeExtension { this.core.invoke("index/forceReIndex", undefined); } else { // Reindex the file - this.core.invoke("index/forceReIndex", { - dirs: [filepath], + this.core.invoke("index/forceReIndexFiles", { + files: [filepath], }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { - this.core.invoke("index/forceReIndex", { - dirs: event.files.map((file) => - file.fsPath.split("/").slice(0, -1).join("/"), - ), + this.core.invoke("index/forceReIndexFiles", { + files: event.files.map((file) => file.fsPath), }); }); diff --git a/gui/src/pages/More/IndexingProgress/index.ts b/gui/src/pages/More/IndexingProgress/index.ts deleted file mode 100644 index 7f51ae6ad..000000000 --- a/gui/src/pages/More/IndexingProgress/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./IndexingProgress"; diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 4824c9535..14d0eadee 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -14,7 +14,7 @@ import { useDispatch } from "react-redux"; import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; -import IndexingProgress from "./IndexingProgress"; +import IndexingProgress from "./progress/codebase"; function MorePage() { useNavigationListener(); diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx b/gui/src/pages/More/progress/IndexingProgressBar.tsx similarity index 91% rename from gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx rename to gui/src/pages/More/progress/IndexingProgressBar.tsx index 5de74fb3f..6d0f7f104 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx +++ b/gui/src/pages/More/progress/IndexingProgressBar.tsx @@ -1,5 +1,5 @@ import { IndexingProgressUpdate } from "core"; -import { getProgressPercentage } from "./IndexingProgress"; +import { getProgressPercentage } from "."; export interface IndexingProgressBarProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/progress/IndexingProgressIndicator.tsx similarity index 95% rename from gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx rename to gui/src/pages/More/progress/IndexingProgressIndicator.tsx index 944fdc917..f337a1d0a 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/progress/IndexingProgressIndicator.tsx @@ -1,10 +1,10 @@ import { IndexingProgressUpdate } from "core"; -import { getProgressPercentage } from "./IndexingProgress"; import { ArrowPathIcon, PauseCircleIcon, CheckCircleIcon, } from "@heroicons/react/24/outline"; +import { getProgressPercentage } from "."; export interface IndexingProgressIndicatorProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx b/gui/src/pages/More/progress/IndexingProgressSubtext.tsx similarity index 100% rename from gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx rename to gui/src/pages/More/progress/IndexingProgressSubtext.tsx diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx b/gui/src/pages/More/progress/IndexingProgressTitleText.tsx similarity index 65% rename from gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx rename to gui/src/pages/More/progress/IndexingProgressTitleText.tsx index 61d4bbba6..9cf014e10 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx +++ b/gui/src/pages/More/progress/IndexingProgressTitleText.tsx @@ -1,19 +1,11 @@ import { IndexingProgressUpdate } from "core"; import { AnimatedEllipsis } from "../../../components"; +import { STATUS_TO_TEXT } from "."; export interface IndexingProgressTitleTextProps { update: IndexingProgressUpdate; } -const STATUS_TO_TEXT: Record = { - done: "Indexing complete", - loading: "Initializing", - indexing: "Indexing in-progress", - paused: "Indexing paused", - failed: "Indexing failed", - disabled: "Indexing disabled", -}; - function IndexingProgressTitleText({ update }: IndexingProgressTitleTextProps) { const showEllipsis = update.status === "loading"; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx similarity index 94% rename from gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx rename to gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx index fff7ab9a8..c8ec68937 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx @@ -1,8 +1,8 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { useSelector } from "react-redux"; -import { RootState } from "../../../redux/store"; -import { isJetBrains } from "../../../util"; +import { RootState } from "../../../../redux/store"; +import { isJetBrains } from "../../../../util"; import { XCircleIcon } from "@heroicons/react/24/outline"; export interface IndexingProgressErrorTextProps { diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx b/gui/src/pages/More/progress/codebase/index.tsx similarity index 75% rename from gui/src/pages/More/IndexingProgress/IndexingProgress.tsx rename to gui/src/pages/More/progress/codebase/index.tsx index f3d4fea55..a0388b785 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx +++ b/gui/src/pages/More/progress/codebase/index.tsx @@ -1,26 +1,20 @@ import { IndexingProgressUpdate } from "core"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { isJetBrains } from "../../../util"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import IndexingProgressBar from "./IndexingProgressBar"; -import IndexingProgressIndicator from "./IndexingProgressIndicator"; -import IndexingProgressTitleText from "./IndexingProgressTitleText"; -import IndexingProgressSubtext from "./IndexingProgressSubtext"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { isJetBrains } from "../../../../util"; +import { useWebviewListener } from "../../../../hooks/useWebviewListener"; +import IndexingProgressBar from "../IndexingProgressBar"; +import IndexingProgressIndicator from "../IndexingProgressIndicator"; +import IndexingProgressSubtext from "../IndexingProgressSubtext"; import { usePostHog } from "posthog-js/react"; -import ConfirmationDialog from "../../../components/dialogs/ConfirmationDialog"; +import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; import { setShowDialog, setDialogMessage, -} from "../../../redux/slices/uiStateSlice"; +} from "../../../../redux/slices/uiStateSlice"; import IndexingProgressErrorText from "./IndexingProgressErrorText"; - -export function getProgressPercentage( - progress: IndexingProgressUpdate["progress"], -) { - return Math.min(100, Math.max(0, progress * 100)); -} +import IndexingProgressTitleText from "../IndexingProgressTitleText"; function IndexingProgress() { const ideMessenger = useContext(IdeMessengerContext); @@ -33,19 +27,13 @@ function IndexingProgress() { status: "loading", }); - // If sidebar is opened after extension initializes, retrieve saved states. - let initialized = false; - useWebviewListener("indexProgress", async (data) => { setUpdate(data); }); useEffect(() => { - if (!initialized) { - // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization - ideMessenger.post("index/indexingProgressBarInitialized", undefined); - initialized = true; - } + // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization + ideMessenger.post("index/indexingProgressBarInitialized", undefined); }, []); useEffect(() => { diff --git a/gui/src/pages/More/progress/docs/index.tsx b/gui/src/pages/More/progress/docs/index.tsx new file mode 100644 index 000000000..b2590adbe --- /dev/null +++ b/gui/src/pages/More/progress/docs/index.tsx @@ -0,0 +1,121 @@ +import { IndexingProgressUpdate } from "core"; +import { useContext, useEffect, useState } from "react"; +import { useDispatch } from "react-redux"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { isJetBrains } from "../../../../util"; +import { useWebviewListener } from "../../../../hooks/useWebviewListener"; +import IndexingProgressBar from "../IndexingProgressBar"; +import IndexingProgressIndicator from "../IndexingProgressIndicator"; +import IndexingProgressSubtext from "../IndexingProgressSubtext"; +import { usePostHog } from "posthog-js/react"; +import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; +import { + setShowDialog, + setDialogMessage, +} from "../../../../redux/slices/uiStateSlice"; +import IndexingProgressTitleText from "../IndexingProgressTitleText"; +import IndexingProgressErrorText from "../codebase/IndexingProgressErrorText"; + +function DocsIndexingProgressItem() { + const ideMessenger = useContext(IdeMessengerContext); + const posthog = usePostHog(); + const dispatch = useDispatch(); + const [paused, setPaused] = useState(undefined); + const [update, setUpdate] = useState({ + desc: "Loading indexing config", + progress: 0.0, + status: "loading", + }); + + useWebviewListener("indexProgress", async (data) => { + setUpdate(data); + }); + + useEffect(() => { + // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization + ideMessenger.post("index/indexingProgressBarInitialized", undefined); + }, []); + + useEffect(() => { + if (paused === undefined) return; + ideMessenger.post("index/setPaused", paused); + }, [paused]); + + function onClickRetry() { + // For now, we don't show in JetBrains since the re-index command + // is not yet implemented + if (update.shouldClearIndexes && !isJetBrains()) { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( + { + posthog.capture("rebuild_index_clicked"); + ideMessenger.post("index/forceReIndex", { + shouldClearIndexes: true, + }); + }} + />, + ), + ); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + } + + function onClick() { + switch (update.status) { + case "failed": + onClickRetry(); + break; + case "indexing": + case "loading": + case "paused": + if (update.progress < 1 && update.progress >= 0) { + setPaused((prev) => !prev); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + break; + case "disabled": + ideMessenger.post("openConfigJson", undefined); + break; + case "done": + ideMessenger.post("index/forceReIndex", undefined); + default: + break; + } + } + + return ( +
+
+ + {update.status !== "loading" && ( + + )} +
+ + + + + + {update.status === "failed" && ( +
+ +
+ )} +
+ ); +} + +function AllDocsIndexingProgress() {} +export default AllDocsIndexingProgress; diff --git a/gui/src/pages/More/progress/index.ts b/gui/src/pages/More/progress/index.ts new file mode 100644 index 000000000..44c3d50e3 --- /dev/null +++ b/gui/src/pages/More/progress/index.ts @@ -0,0 +1,17 @@ +import { IndexingProgressUpdate } from "core"; + +export function getProgressPercentage( + progress: IndexingProgressUpdate["progress"], +) { + return Math.min(100, Math.max(0, progress * 100)); +} + +export const STATUS_TO_TEXT: Record = + { + done: "Indexing complete", + loading: "Initializing", + indexing: "Indexing in-progress", + paused: "Indexing paused", + failed: "Indexing failed", + disabled: "Indexing disabled", + }; From 44c7b7fff39fdb947e9015aaf361356bc47f389c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 16:35:08 -0800 Subject: [PATCH 02/21] revert files per index changes - moved to different branch --- core/core.ts | 80 +++++-------------- core/indexing/CodebaseIndexer.ts | 77 ++++-------------- core/protocol/core.ts | 1 - core/protocol/passThrough.ts | 3 +- .../ContinuePluginStartupActivity.kt | 4 +- .../toolWindow/ContinueBrowser.kt | 1 - extensions/vscode/package-lock.json | 4 +- .../vscode/src/extension/VsCodeExtension.ts | 10 ++- 8 files changed, 45 insertions(+), 135 deletions(-) diff --git a/core/core.ts b/core/core.ts index a5514490a..6df1482ef 100644 --- a/core/core.ts +++ b/core/core.ts @@ -83,7 +83,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => {}, + private readonly onWrite: (text: string) => Promise = async () => { }, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -174,7 +174,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => {}, + (e) => { }, (..._) => Promise.resolve([]), ); @@ -684,14 +684,9 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); + const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); await this.refreshCodebaseIndex(dirs); }); - on("index/forceReIndexFiles", async ({ data }) => { - if (data?.files?.length) { - await this.refreshCodebaseIndexFiles(data.files); - } - }); on("index/setPaused", (msg) => { new GlobalContext().update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; @@ -727,29 +722,14 @@ export class Core { } private indexingCancellationController: AbortController | undefined; - private async sendIndexingTelemetry(update: IndexingProgressUpdate) { - console.debug( - "Indexing failed with error: ", - update.desc, - update.debugInfo, - ); - void Telemetry.capture( - "indexing_error", - { - error: update.desc, - stack: update.debugInfo, - }, - false, - ); - } - private async refreshCodebaseIndex(paths: string[]) { + private async refreshCodebaseIndex(dirs: string[]) { if (this.indexingCancellationController) { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshDirs( - paths, + for await (const update of (await this.codebaseIndexerPromise).refresh( + dirs, this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; @@ -763,41 +743,19 @@ export class Core { this.indexingState = updateToSend; if (update.status === "failed") { - void this.sendIndexingTelemetry(update); - } - } - - this.messenger.send("refreshSubmenuItems", undefined); - } - - private async refreshCodebaseIndexFiles(files: string[]) { - // Can be cancelled by codebase index but not vice versa - if ( - this.indexingCancellationController && - !this.indexingCancellationController.signal.aborted - ) { - return console.debug( - "Codebase indexing already in progress, skipping indexing of files\n" + - files.join("\n"), - ); - } - this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshFiles( - files, - this.indexingCancellationController.signal, - )) { - let updateToSend = { ...update }; - if (update.status === "failed") { - updateToSend.status = "done"; - updateToSend.desc = "Indexing complete"; - updateToSend.progress = 1.0; - } - - void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; - - if (update.status === "failed") { - void this.sendIndexingTelemetry(update); + console.debug( + "Indexing failed with error: ", + update.desc, + update.debugInfo, + ); + void Telemetry.capture( + "indexing_error", + { + error: update.desc, + stack: update.debugInfo, + }, + false, + ); } } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 175e1a062..b4962d182 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -17,7 +17,6 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; -import { getBasename } from "../util/index.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -145,61 +144,13 @@ export class CodebaseIndexer { } } - async *refreshFiles( - files: string[], - abortSignal: AbortSignal, - ): AsyncGenerator { - let progress = 0; - if (files.length === 0) { - yield { - progress: 1, - desc: "Indexing Complete", - status: "done", - }; - } - - const progressPer = 1 / files.length; - try { - for (const file of files) { - yield { - progress, - desc: `Indexing file ${file}...`, - status: "indexing", - }; - await this.refreshFile(file); - - progress += progressPer; - - if (this.pauseToken.paused) { - yield* this.yieldUpdateAndPause(); - } - if (abortSignal.aborted) { - yield { - progress: 1, - desc: "Indexing cancelled", - status: "disabled", - }; - return; - } - } - - yield { - progress: 1, - desc: "Indexing Complete", - status: "done", - }; - } catch (err) { - yield this.handleErrorAndGetProgressUpdate(err); - } - } - - async *refreshDirs( - dirs: string[], + async *refresh( + workspaceDirs: string[], abortSignal: AbortSignal, ): AsyncGenerator { let progress = 0; - if (dirs.length === 0) { + if (workspaceDirs.length === 0) { yield { progress, desc: "Nothing to index", @@ -224,9 +175,11 @@ export class CodebaseIndexer { }; } + let completedDirs = 0; + // Wait until Git Extension has loaded to report progress // so we don't appear stuck at 0% while waiting - await this.ide.getRepoName(dirs[0]); + await this.ide.getRepoName(workspaceDirs[0]); yield { progress, @@ -235,16 +188,16 @@ export class CodebaseIndexer { }; const beginTime = Date.now(); - for (const directory of dirs) { + for (const directory of workspaceDirs) { const dirBasename = await this.basename(directory); yield { progress, desc: `Discovering files in ${dirBasename}...`, status: "indexing", }; - const directoryFiles = []; + const workspaceFiles = []; for await (const p of walkDirAsync(directory, this.ide)) { - directoryFiles.push(p); + workspaceFiles.push(p); if (abortSignal.aborted) { yield { progress: 1, @@ -265,7 +218,7 @@ export class CodebaseIndexer { try { for await (const updateDesc of this.indexFiles( directory, - directoryFiles, + workspaceFiles, branch, repoName, )) { @@ -287,7 +240,7 @@ export class CodebaseIndexer { nextLogThreshold += 0.025; this.logProgress( beginTime, - Math.floor(directoryFiles.length * updateDesc.progress), + Math.floor(workspaceFiles.length * updateDesc.progress), updateDesc.progress, ); } @@ -394,18 +347,18 @@ export class CodebaseIndexer { } private async *indexFiles( - directory: string, - files: string[], + workspaceDir: string, + workspaceFiles: string[], branch: string, repoName: string | undefined, ): AsyncGenerator { - const stats = await this.ide.getLastModified(files); + const stats = await this.ide.getLastModified(workspaceFiles); const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { - directory, + directory: workspaceDir, branch, artifactId: codebaseIndex.artifactId, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e30de4673..2c9af1433 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -147,7 +147,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, void, ]; - "index/forceReIndexFiles": [undefined | { files?: string[] }, void]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 21ac52c8d..1c0f5e962 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,7 +41,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", - "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", @@ -61,5 +60,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength", + "getWebviewHistoryLength" ]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 451baae68..fa39729fa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -169,8 +169,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // Create a data map if there are any paths to re-index if (allPaths.isNotEmpty()) { - val data = mapOf("files" to allPaths) - continuePluginService.coreMessenger?.request("index/forceReIndexFiles", data, null) { _ -> } + val data = mapOf("dirs" to allPaths) + continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } } } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 147f153e3..26896906b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -58,7 +58,6 @@ class ContinueBrowser(val project: Project, url: String) { "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", - "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 29ac4731f..24930d980 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.230", + "version": "0.9.229", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.230", + "version": "0.9.229", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index bb46e7466..06263e356 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -297,15 +297,17 @@ export class VsCodeExtension { this.core.invoke("index/forceReIndex", undefined); } else { // Reindex the file - this.core.invoke("index/forceReIndexFiles", { - files: [filepath], + this.core.invoke("index/forceReIndex", { + dirs: [filepath], }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { - this.core.invoke("index/forceReIndexFiles", { - files: event.files.map((file) => file.fsPath), + this.core.invoke("index/forceReIndex", { + dirs: event.files.map((file) => + file.fsPath.split("/").slice(0, -1).join("/"), + ), }); }); From d2decdb80e7ca2e3876b9541f91ee48c94c0586b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 14:34:03 -0800 Subject: [PATCH 03/21] docs servie updates --- core/core.ts | 2 +- core/indexing/docs/DocsCrawler.ts | 2 +- core/indexing/docs/DocsService.ts | 93 +++++++++++--------- gui/src/hooks/useSetup.ts | 16 +--- gui/src/hooks/useSubmenuContextProviders.tsx | 7 +- 5 files changed, 56 insertions(+), 64 deletions(-) diff --git a/core/core.ts b/core/core.ts index 6df1482ef..dc140cf3d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -688,7 +688,7 @@ export class Core { await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { - new GlobalContext().update("indexingPaused", msg.data); + this.globalContext.update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; }); on("index/indexingProgressBarInitialized", async (msg) => { diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index cb9146ab5..01f0efab1 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -95,6 +95,6 @@ export default DocsCrawler; export { CheerioCrawler, ChromiumCrawler, - ChromiumInstaller as ChromiumInstaller, + ChromiumInstaller, GitHubCrawler, }; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index d97b92974..2c9a01e1e 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -103,26 +103,6 @@ export default class DocsService { return docsService; } - async isJetBrainsAndPreIndexedDocsProvider(): Promise { - const isJetBrains = await this.isJetBrains(); - - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; - - return isJetBrains && isPreIndexedDocsProvider; - } - - /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers. - * However, we don't ship transformers with the JetBrains extension. - * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. - */ - async canUsePreindexedDocs() { - const isJetBrains = await this.isJetBrains(); - return !isJetBrains; - } - async delete(startUrl: string) { await this.deleteFromLance(startUrl); await this.deleteFromSqlite(startUrl); @@ -426,36 +406,41 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); - this.docsCrawler = new DocsCrawler(this.ide, this.config); + await this.handleConfigUpdate({config: this.config}); + configHandler.onConfigUpdate(this.handleConfigUpdate); + } - const embeddingsProvider = await this.getEmbeddingsProvider(); + private async handleConfigUpdate({config: newConfig}: {config: ContinueConfig | undefined}) { + if(newConfig){ + this.config = newConfig; + this.docsCrawler = new DocsCrawler(this.ide, this.config); - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + const embeddingsProvider = await this.getEmbeddingsProvider(); + + this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - configHandler.onConfigUpdate(async ({ config: newConfig }) => { - if (newConfig) { - const oldConfig = this.config; + const oldConfig = this.config; - // Need to update class property for config at the beginning of this callback - // to ensure downstream methods have access to the latest config. - this.config = newConfig; + // Need to update class property for config at the beginning of this callback + // to ensure downstream methods have access to the latest config. + this.config = newConfig; - if (oldConfig.docs !== newConfig.docs) { - await this.syncConfigAndSqlite(); - } - - const shouldReindex = - await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); - - if (shouldReindex) { - await this.reindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider, - ); - } + if (oldConfig.docs !== newConfig.docs) { + await this.syncConfigAndSqlite(); } - }); + + const shouldReindex = + await this.shouldReindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider.id, + ); + + if (shouldReindex) { + await this.reindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider, + ); + } + } + } private async syncConfigAndSqlite() { @@ -609,6 +594,26 @@ export default class DocsService { return ideInfo.ideType === "jetbrains"; } + async isJetBrainsAndPreIndexedDocsProvider(): Promise { + const isJetBrains = await this.isJetBrains(); + + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + + return isJetBrains && isPreIndexedDocsProvider; + } + + /* + * Currently, we generate and host embeddings for pre-indexed docs using transformers. + * However, we don't ship transformers with the JetBrains extension. + * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. + */ + async canUsePreindexedDocs() { + const isJetBrains = await this.isJetBrains(); + return !isJetBrains; + } + private async hasIndexedDoc(startUrl: string) { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2fed805da..8ece44bec 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -37,7 +37,6 @@ function useSetup(dispatch: Dispatch) { dispatch(setConfig(config)); dispatch(setSelectedProfileId(profileId)); setConfigLoaded(true); - setLocalStorage("disableIndexing", config.disableIndexing || false); // Perform any actions needed with the config if (config.ui?.fontSize) { @@ -46,20 +45,7 @@ function useSetup(dispatch: Dispatch) { } }; - // Load config from the IDE - useEffect(() => { - loadConfig(); - const interval = setInterval(() => { - if (configLoaded) { - clearInterval(interval); - return; - } - loadConfig(); - }, 2_000); - - return () => clearInterval(interval); - }, [configLoaded]); - + // ON LOAD useEffect(() => { // Override persisted state dispatch(setInactive()); diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index fc0b0c71a..7f9e65f73 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -13,6 +13,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger"; import { selectContextProviderDescriptions } from "../redux/selectors"; import { getLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; +import { RootState } from "../redux/store"; const MINISEARCH_OPTIONS = { prefix: true, @@ -38,6 +39,8 @@ function useSubmenuContextProviders() { const [isLoading, setIsLoading] = useState(false); const [autoLoadTriggered, setAutoLoadTriggered] = useState(false); + const config = useSelector((store: RootState) => store.state.config); + const ideMessenger = useContext(IdeMessengerContext); const memoizedGetOpenFileItems = useMemo(() => { @@ -213,12 +216,10 @@ function useSubmenuContextProviders() { const loadSubmenuItems = async () => { try { - const disableIndexing = getLocalStorage("disableIndexing") ?? false; - await Promise.all( contextProviderDescriptions.map(async (description) => { const shouldSkipProvider = - description.dependsOnIndexing && disableIndexing; + description.dependsOnIndexing && config.disableIndexing; if (shouldSkipProvider) { console.debug( From dfe11d357a41c43bfe08d9a456b0bcfc6343c15b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 15:39:49 -0800 Subject: [PATCH 04/21] indexing progress status type --- core/index.d.ts | 12 ++++++++++++ core/indexing/docs/DocsService.ts | 13 ++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..6b275d7e2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -45,6 +45,18 @@ export interface IndexingProgressUpdate { debugInfo?: string; } +// This is more or less a V2 of IndexingProgressUpdate +export interface IndexingStatusUpdate { + type: "docs"; + id: string; // Unique identifier, e.g. docs start url + progress: number; + description: string; + status: "initializing" | "indexing" | "complete" | "paused" | "failed" | "disabled"; + embeddingsModel: string; + isReindexing: boolean; + debugInfo: string; +} + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 2c9a01e1e..1bf358e8f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -407,6 +407,11 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); await this.handleConfigUpdate({config: this.config}); + + // only update on init because should only update on reindexDocsOnNewEmbeddingsProvider + const embeddingsProvider = await this.getEmbeddingsProvider(); + this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + configHandler.onConfigUpdate(this.handleConfigUpdate); } @@ -415,10 +420,6 @@ export default class DocsService { this.config = newConfig; this.docsCrawler = new DocsCrawler(this.ide, this.config); - const embeddingsProvider = await this.getEmbeddingsProvider(); - - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - const oldConfig = this.config; // Need to update class property for config at the beginning of this callback @@ -817,6 +818,4 @@ export default class DocsService { console.log("Completed reindexing of all docs"); } -} - -export const docsServiceSingleton = DocsService.getSingleton(); +} \ No newline at end of file From 23bde0305495d9ce0ac8da99d3d2cde63f5a2210 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 15:42:05 -0800 Subject: [PATCH 05/21] revert to old indexing progress folder structure --- .../IndexingProgress.tsx} | 34 +++-- .../IndexingProgressBar.tsx | 2 +- .../IndexingProgressErrorText.tsx | 4 +- .../IndexingProgressIndicator.tsx | 2 +- .../IndexingProgressSubtext.tsx | 0 .../IndexingProgressTitleText.tsx | 10 +- gui/src/pages/More/IndexingProgress/index.ts | 1 + gui/src/pages/More/More.tsx | 2 +- gui/src/pages/More/progress/docs/index.tsx | 121 ------------------ gui/src/pages/More/progress/index.ts | 17 --- 10 files changed, 38 insertions(+), 155 deletions(-) rename gui/src/pages/More/{progress/codebase/index.tsx => IndexingProgress/IndexingProgress.tsx} (75%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressBar.tsx (91%) rename gui/src/pages/More/{progress/codebase => IndexingProgress}/IndexingProgressErrorText.tsx (94%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressIndicator.tsx (95%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressSubtext.tsx (100%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressTitleText.tsx (65%) create mode 100644 gui/src/pages/More/IndexingProgress/index.ts delete mode 100644 gui/src/pages/More/progress/docs/index.tsx delete mode 100644 gui/src/pages/More/progress/index.ts diff --git a/gui/src/pages/More/progress/codebase/index.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx similarity index 75% rename from gui/src/pages/More/progress/codebase/index.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgress.tsx index a0388b785..f3d4fea55 100644 --- a/gui/src/pages/More/progress/codebase/index.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx @@ -1,20 +1,26 @@ import { IndexingProgressUpdate } from "core"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { isJetBrains } from "../../../../util"; -import { useWebviewListener } from "../../../../hooks/useWebviewListener"; -import IndexingProgressBar from "../IndexingProgressBar"; -import IndexingProgressIndicator from "../IndexingProgressIndicator"; -import IndexingProgressSubtext from "../IndexingProgressSubtext"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { isJetBrains } from "../../../util"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import IndexingProgressBar from "./IndexingProgressBar"; +import IndexingProgressIndicator from "./IndexingProgressIndicator"; +import IndexingProgressTitleText from "./IndexingProgressTitleText"; +import IndexingProgressSubtext from "./IndexingProgressSubtext"; import { usePostHog } from "posthog-js/react"; -import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; +import ConfirmationDialog from "../../../components/dialogs/ConfirmationDialog"; import { setShowDialog, setDialogMessage, -} from "../../../../redux/slices/uiStateSlice"; +} from "../../../redux/slices/uiStateSlice"; import IndexingProgressErrorText from "./IndexingProgressErrorText"; -import IndexingProgressTitleText from "../IndexingProgressTitleText"; + +export function getProgressPercentage( + progress: IndexingProgressUpdate["progress"], +) { + return Math.min(100, Math.max(0, progress * 100)); +} function IndexingProgress() { const ideMessenger = useContext(IdeMessengerContext); @@ -27,13 +33,19 @@ function IndexingProgress() { status: "loading", }); + // If sidebar is opened after extension initializes, retrieve saved states. + let initialized = false; + useWebviewListener("indexProgress", async (data) => { setUpdate(data); }); useEffect(() => { - // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization - ideMessenger.post("index/indexingProgressBarInitialized", undefined); + if (!initialized) { + // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization + ideMessenger.post("index/indexingProgressBarInitialized", undefined); + initialized = true; + } }, []); useEffect(() => { diff --git a/gui/src/pages/More/progress/IndexingProgressBar.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx similarity index 91% rename from gui/src/pages/More/progress/IndexingProgressBar.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx index 6d0f7f104..5de74fb3f 100644 --- a/gui/src/pages/More/progress/IndexingProgressBar.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx @@ -1,5 +1,5 @@ import { IndexingProgressUpdate } from "core"; -import { getProgressPercentage } from "."; +import { getProgressPercentage } from "./IndexingProgress"; export interface IndexingProgressBarProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx similarity index 94% rename from gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx index c8ec68937..fff7ab9a8 100644 --- a/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx @@ -1,8 +1,8 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { useSelector } from "react-redux"; -import { RootState } from "../../../../redux/store"; -import { isJetBrains } from "../../../../util"; +import { RootState } from "../../../redux/store"; +import { isJetBrains } from "../../../util"; import { XCircleIcon } from "@heroicons/react/24/outline"; export interface IndexingProgressErrorTextProps { diff --git a/gui/src/pages/More/progress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx similarity index 95% rename from gui/src/pages/More/progress/IndexingProgressIndicator.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index f337a1d0a..944fdc917 100644 --- a/gui/src/pages/More/progress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -1,10 +1,10 @@ import { IndexingProgressUpdate } from "core"; +import { getProgressPercentage } from "./IndexingProgress"; import { ArrowPathIcon, PauseCircleIcon, CheckCircleIcon, } from "@heroicons/react/24/outline"; -import { getProgressPercentage } from "."; export interface IndexingProgressIndicatorProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/progress/IndexingProgressSubtext.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx similarity index 100% rename from gui/src/pages/More/progress/IndexingProgressSubtext.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx diff --git a/gui/src/pages/More/progress/IndexingProgressTitleText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx similarity index 65% rename from gui/src/pages/More/progress/IndexingProgressTitleText.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx index 9cf014e10..61d4bbba6 100644 --- a/gui/src/pages/More/progress/IndexingProgressTitleText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx @@ -1,11 +1,19 @@ import { IndexingProgressUpdate } from "core"; import { AnimatedEllipsis } from "../../../components"; -import { STATUS_TO_TEXT } from "."; export interface IndexingProgressTitleTextProps { update: IndexingProgressUpdate; } +const STATUS_TO_TEXT: Record = { + done: "Indexing complete", + loading: "Initializing", + indexing: "Indexing in-progress", + paused: "Indexing paused", + failed: "Indexing failed", + disabled: "Indexing disabled", +}; + function IndexingProgressTitleText({ update }: IndexingProgressTitleTextProps) { const showEllipsis = update.status === "loading"; diff --git a/gui/src/pages/More/IndexingProgress/index.ts b/gui/src/pages/More/IndexingProgress/index.ts new file mode 100644 index 000000000..7f51ae6ad --- /dev/null +++ b/gui/src/pages/More/IndexingProgress/index.ts @@ -0,0 +1 @@ +export { default } from "./IndexingProgress"; diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 14d0eadee..4824c9535 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -14,7 +14,7 @@ import { useDispatch } from "react-redux"; import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; -import IndexingProgress from "./progress/codebase"; +import IndexingProgress from "./IndexingProgress"; function MorePage() { useNavigationListener(); diff --git a/gui/src/pages/More/progress/docs/index.tsx b/gui/src/pages/More/progress/docs/index.tsx deleted file mode 100644 index b2590adbe..000000000 --- a/gui/src/pages/More/progress/docs/index.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { IndexingProgressUpdate } from "core"; -import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { isJetBrains } from "../../../../util"; -import { useWebviewListener } from "../../../../hooks/useWebviewListener"; -import IndexingProgressBar from "../IndexingProgressBar"; -import IndexingProgressIndicator from "../IndexingProgressIndicator"; -import IndexingProgressSubtext from "../IndexingProgressSubtext"; -import { usePostHog } from "posthog-js/react"; -import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; -import { - setShowDialog, - setDialogMessage, -} from "../../../../redux/slices/uiStateSlice"; -import IndexingProgressTitleText from "../IndexingProgressTitleText"; -import IndexingProgressErrorText from "../codebase/IndexingProgressErrorText"; - -function DocsIndexingProgressItem() { - const ideMessenger = useContext(IdeMessengerContext); - const posthog = usePostHog(); - const dispatch = useDispatch(); - const [paused, setPaused] = useState(undefined); - const [update, setUpdate] = useState({ - desc: "Loading indexing config", - progress: 0.0, - status: "loading", - }); - - useWebviewListener("indexProgress", async (data) => { - setUpdate(data); - }); - - useEffect(() => { - // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization - ideMessenger.post("index/indexingProgressBarInitialized", undefined); - }, []); - - useEffect(() => { - if (paused === undefined) return; - ideMessenger.post("index/setPaused", paused); - }, [paused]); - - function onClickRetry() { - // For now, we don't show in JetBrains since the re-index command - // is not yet implemented - if (update.shouldClearIndexes && !isJetBrains()) { - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - { - posthog.capture("rebuild_index_clicked"); - ideMessenger.post("index/forceReIndex", { - shouldClearIndexes: true, - }); - }} - />, - ), - ); - } else { - ideMessenger.post("index/forceReIndex", undefined); - } - } - - function onClick() { - switch (update.status) { - case "failed": - onClickRetry(); - break; - case "indexing": - case "loading": - case "paused": - if (update.progress < 1 && update.progress >= 0) { - setPaused((prev) => !prev); - } else { - ideMessenger.post("index/forceReIndex", undefined); - } - break; - case "disabled": - ideMessenger.post("openConfigJson", undefined); - break; - case "done": - ideMessenger.post("index/forceReIndex", undefined); - default: - break; - } - } - - return ( -
-
- - {update.status !== "loading" && ( - - )} -
- - - - - - {update.status === "failed" && ( -
- -
- )} -
- ); -} - -function AllDocsIndexingProgress() {} -export default AllDocsIndexingProgress; diff --git a/gui/src/pages/More/progress/index.ts b/gui/src/pages/More/progress/index.ts deleted file mode 100644 index 44c3d50e3..000000000 --- a/gui/src/pages/More/progress/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IndexingProgressUpdate } from "core"; - -export function getProgressPercentage( - progress: IndexingProgressUpdate["progress"], -) { - return Math.min(100, Math.max(0, progress * 100)); -} - -export const STATUS_TO_TEXT: Record = - { - done: "Indexing complete", - loading: "Initializing", - indexing: "Indexing in-progress", - paused: "Indexing paused", - failed: "Indexing failed", - disabled: "Indexing disabled", - }; From a9169c373875ffc1d01869509246bad7ab7aae20 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 16:39:42 -0800 Subject: [PATCH 06/21] indexing progress start --- core/core.ts | 25 +++++++++++++------- core/indexing/docs/DocsService.ts | 38 +++++++++++++++++++------------ gui/src/hooks/useSetup.ts | 17 ++++++++++++-- 3 files changed, 56 insertions(+), 24 deletions(-) diff --git a/core/core.ts b/core/core.ts index dc140cf3d..dd7b2c3e6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -42,7 +42,8 @@ export class Core { codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; continueServerClientPromise: Promise; - indexingState: IndexingProgressUpdate; + codebaseIndexingState: IndexingProgressUpdate; + docsIndexingStates: Map = new Map(); controlPlaneClient: ControlPlaneClient; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -83,12 +84,16 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); - this.indexingState = { status: "loading", desc: "loading", progress: 0 }; + this.codebaseIndexingState = { + status: "loading", + desc: "loading", + progress: 0, + }; const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { @@ -148,6 +153,7 @@ export class Core { // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings + this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { await this.messenger.request("indexProgress", { progress: 1, @@ -174,7 +180,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -684,7 +690,7 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { @@ -694,8 +700,11 @@ export class Core { on("index/indexingProgressBarInitialized", async (msg) => { // Triggered when progress bar is initialized. // If a non-default state has been stored, update the indexing display to that state - if (this.indexingState.status !== "loading") { - void this.messenger.request("indexProgress", this.indexingState); + if (this.codebaseIndexingState.status !== "loading") { + void this.messenger.request( + "indexProgress", + this.codebaseIndexingState, + ); } }); @@ -740,7 +749,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { console.debug( diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 1bf358e8f..f75412917 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,7 +7,7 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingProgressUpdate, + IndexingStatusUpdate, SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; @@ -178,7 +178,7 @@ export default class DocsService { async *indexAndAdd( siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, - ): AsyncGenerator { + ): AsyncGenerator { const { startUrl } = siteIndexingConfig; const embeddingsProvider = await this.getEmbeddingsProvider(); @@ -406,17 +406,29 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); - await this.handleConfigUpdate({config: this.config}); + await this.handleConfigUpdate({ config: this.config }); // only update on init because should only update on reindexDocsOnNewEmbeddingsProvider - const embeddingsProvider = await this.getEmbeddingsProvider(); - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + const currentEmbeddingsProvider = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if (!currentEmbeddingsProvider) { + const embeddingsProvider = await this.getEmbeddingsProvider(); + this.globalContext.update( + "curEmbeddingsProviderId", + embeddingsProvider.id, + ); + } configHandler.onConfigUpdate(this.handleConfigUpdate); } - private async handleConfigUpdate({config: newConfig}: {config: ContinueConfig | undefined}) { - if(newConfig){ + private async handleConfigUpdate({ + config: newConfig, + }: { + config: ContinueConfig | undefined; + }) { + if (newConfig) { this.config = newConfig; this.docsCrawler = new DocsCrawler(this.ide, this.config); @@ -430,10 +442,9 @@ export default class DocsService { await this.syncConfigAndSqlite(); } - const shouldReindex = - await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); + const shouldReindex = await this.shouldReindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider.id, + ); if (shouldReindex) { await this.reindexDocsOnNewEmbeddingsProvider( @@ -441,7 +452,6 @@ export default class DocsService { ); } } - } private async syncConfigAndSqlite() { @@ -595,7 +605,7 @@ export default class DocsService { return ideInfo.ideType === "jetbrains"; } - async isJetBrainsAndPreIndexedDocsProvider(): Promise { + async isJetBrainsAndPreIndexedDocsProvider(): Promise { const isJetBrains = await this.isJetBrains(); const isPreIndexedDocsProvider = @@ -818,4 +828,4 @@ export default class DocsService { console.log("Completed reindexing of all docs"); } -} \ No newline at end of file +} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 8ece44bec..58feba2a5 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -45,7 +45,20 @@ function useSetup(dispatch: Dispatch) { } }; - // ON LOAD + // Load config from the IDE + useEffect(() => { + loadConfig(); + const interval = setInterval(() => { + if (configLoaded) { + clearInterval(interval); + return; + } + loadConfig(); + }, 2_000); + + return () => clearInterval(interval); + }, [configLoaded]); + useEffect(() => { // Override persisted state dispatch(setInactive()); @@ -104,7 +117,7 @@ function useSetup(dispatch: Dispatch) { useWebviewListener("configUpdate", async () => { await loadConfig(); - if (!isJetBrains && !getLocalStorage("disableIndexing")) { + if (!isJetBrains) { debouncedIndexDocs(); } }); From ecb97f23f636b761d9565100318d07eddd3429b3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 16 Nov 2024 22:24:10 -0800 Subject: [PATCH 07/21] docs service p23232 --- core/context/providers/DocsContextProvider.ts | 36 +- core/core.ts | 34 +- core/index.d.ts | 10 +- core/indexing/docs/DocsService.test.ts | 8 +- core/indexing/docs/DocsService.ts | 539 ++++++++++-------- core/protocol/passThrough.ts | 7 +- 6 files changed, 331 insertions(+), 303 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index a290589e4..f3a1e5d77 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -88,38 +88,10 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const isJetBrainsAndPreIndexedDocsProvider = - await docsService.isJetBrainsAndPreIndexedDocsProvider(); - - if (isJetBrainsAndPreIndexedDocsProvider) { - await extras.ide.showToast( - "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + - "the embeddings provider, but it cannot be used with JetBrains. " + - "Please select a different embeddings provider to use the '@docs' " + - "context provider.", - ); - - return []; - } - - const preIndexedDoc = preIndexedDocs[query]; - - if (!!preIndexedDoc) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDoc["title"], - }); - } - - const embeddingsProvider = await docsService.getEmbeddingsProvider( - !!preIndexedDoc, - ); - - const [vector] = await embeddingsProvider.embed([extras.fullInput]); - - let chunks = await docsService.retrieveChunks( + await docsService.isInitialized; + let chunks = await docsService.retrieveChunksFromQuery( + extras.fullInput, query, - vector, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); @@ -175,7 +147,7 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const docs = (await docsService.list()) ?? []; + const docs = (await docsService.listMetadata()) ?? []; const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); const submenuItemsMap = new Map(); diff --git a/core/core.ts b/core/core.ts index dd7b2c3e6..c1075dfd6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -278,24 +278,22 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - let hasFailed = false; - - for await (const result of this.docsService.indexAndAdd(msg.data)) { - if (result.status === "failed") { - hasFailed = true; - break; - } - } - - if (hasFailed) { - void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); - } else { - void this.ide.showToast( - "info", - `Successfully indexed ${msg.data.startUrl}`, - ); - this.messenger.send("refreshSubmenuItems", undefined); - } + // let hasFailed = false; + // for await (const result of this.docsService.indexAndAdd(msg.data)) { + // if (result.status === "failed") { + // hasFailed = true; + // break; + // } + // } + // if (hasFailed) { + // void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); + // } else { + // void this.ide.showToast( + // "info", + // `Successfully indexed ${msg.data.startUrl}`, + // ); + // this.messenger.send("refreshSubmenuItems", undefined); + // } }); on("context/removeDocs", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 6b275d7e2..b6b4c7f0c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -51,10 +51,16 @@ export interface IndexingStatusUpdate { id: string; // Unique identifier, e.g. docs start url progress: number; description: string; - status: "initializing" | "indexing" | "complete" | "paused" | "failed" | "disabled"; + status: + | "initializing" + | "indexing" + | "complete" + | "paused" + | "failed" + | "disabled"; embeddingsModel: string; isReindexing: boolean; - debugInfo: string; + debugInfo?: string; } export type PromptTemplateFunction = ( diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 9bac503c9..11fed29e5 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -72,7 +72,7 @@ describe.skip("DocsService Integration Tests", () => { let latestConfig = await getReloadedConfig(); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); // config.json check expect(latestConfig.docs).toContainEqual(mockSiteConfig); @@ -91,7 +91,7 @@ describe.skip("DocsService Integration Tests", () => { await docsService.delete(mockSiteConfig.startUrl); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); // config.json check latestConfig = await getReloadedConfig(); @@ -143,7 +143,7 @@ describe.skip("DocsService Integration Tests", () => { await getReloadedConfig(); - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); editConfigJson((config) => { const { docs, ...restConfig } = config; @@ -164,6 +164,6 @@ describe.skip("DocsService Integration Tests", () => { await new Promise((resolve) => setTimeout(resolve, 100)); } - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); }); }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index f75412917..79dea28e6 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -62,13 +62,25 @@ export type AddParams = { favicon?: string; }; +/* + General process: + - On config update: + - Reindex ALL docs if embeddings provider has changed + - Otherwise, reindex docs with CHANGED URL/DEPTH + - And update docs with CHANGED TITLE/FAVICON + - Also, messages to core can trigger: + - delete + - reindex all + - add/index one + - Currently a full reindex deletes all docs rather than storing PER embeddings provider + - The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful +*/ export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); - private static instance?: DocsService; public isInitialized: Promise; public isSyncing: boolean = false; @@ -89,10 +101,8 @@ export default class DocsService { this.isInitialized = this.init(configHandler); } - static getSingleton() { - return DocsService.instance; - } - + // Singleton pattern: only one service globally + private static instance?: DocsService; static createSingleton( configHandler: ConfigHandler, ide: IDE, @@ -103,17 +113,102 @@ export default class DocsService { return docsService; } - async delete(startUrl: string) { - await this.deleteFromLance(startUrl); - await this.deleteFromSqlite(startUrl); - this.deleteFromConfig(startUrl); + static getSingleton() { + return DocsService.instance; + } - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + // Initialization - load config and attach config listener + private async init(configHandler: ConfigHandler) { + this.config = await configHandler.loadConfig(); + await this.handleConfigUpdate({ config: this.config }); + + configHandler.onConfigUpdate(this.handleConfigUpdate); + } + + // Config + + /* + * Currently, we generate and host embeddings for pre-indexed docs using transformers. + * However, we don't ship transformers with the JetBrains extension. + * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. + */ + async canUsePreindexedDocs() { + const ideInfo = await this.ide.getIdeInfo(); + if (ideInfo.ideType === "jetbrains") { + return false; + } + return true; + } + + async isUsingUnsupportedPreIndexedEmbeddingsProvider() { + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + return isPreIndexedDocsProvider && !canUsePreindexedDocs; + } + + async getEmbeddingsProvider( + isPreIndexedDoc: boolean = false, + ): Promise { + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + + if (canUsePreindexedDocs && isPreIndexedDoc) { + return DocsService.preIndexedDocsEmbeddingsProvider; + } + + return this.config.embeddingsProvider; + } + + // Expose this so that docs provider can check it + + private async handleConfigUpdate({ + config: newConfig, + }: { + config: ContinueConfig | undefined; + }) { + if (newConfig) { + const oldConfig = this.config; + this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in + + this.docsCrawler = new DocsCrawler(this.ide, newConfig); + + // Skip docs indexing if not supported + const unsupported = + await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); + if (unsupported) { + return; + } + + const newConfigDocs = newConfig.docs || []; + const oldConfigDocs = oldConfig.docs || []; + + const newPreindexed = newConfigDocs.filter( + (doc) => !!preIndexedDocs[doc.startUrl], + ); + + // On embeddings provider change, reindex all docs + // change = doesn't match last successful embeddings provider + const curEmbeddingsProviderId = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if ( + curEmbeddingsProviderId && + curEmbeddingsProviderId !== curEmbeddingsProviderId + ) { + // If not set, we're initializing + const currentDocs = await this.listMetadata(); + if (currentDocs.length > 0) { + await this.reindexDocsOnNewEmbeddingsProvider(); + return; + } + } + + await this.syncConfigAndSqlite(); } } - async has(startUrl: string): Promise> { + async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -123,6 +218,16 @@ export default class DocsService { return !!title; } + // private async hasIndexedDoc(startUrl: string) { + // const db = await this.getOrCreateSqliteDb(); + // const docs = await db.all( + // `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + // startUrl, + // ); + + // return docs.length > 0; + // } + async showAddDocsContextProviderToast() { const actionMsg = "Add 'docs' context provider"; const res = await this.ide.showToast( @@ -156,17 +261,17 @@ export default class DocsService { } } - const docs = await this.list(); + const docs = await this.listMetadata(); for (const doc of docs) { const generator = this.indexAndAdd(doc, reIndex); while (!(await generator.next()).done) {} } - await this.ide.showToast("info", "Docs indexing completed"); + void this.ide.showToast("info", "Docs indexing completed"); } - async list() { + async listMetadata() { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, @@ -180,18 +285,36 @@ export default class DocsService { reIndex: boolean = false, ): AsyncGenerator { const { startUrl } = siteIndexingConfig; - const embeddingsProvider = await this.getEmbeddingsProvider(); if (this.docsIndexingQueue.has(startUrl)) { - console.log("Already in queue"); + console.debug("Already in queue"); return; } + const embeddingsProvider = await this.getEmbeddingsProvider(); - if (!reIndex && (await this.has(startUrl))) { + const indexExists = await this.hasMetadata(startUrl); + + const fixedStatus: Pick< + IndexingStatusUpdate, + "type" | "id" | "embeddingsModel" | "isReindexing" + > = { + type: "docs", + id: siteIndexingConfig.startUrl, + embeddingsModel: embeddingsProvider.id, + isReindexing: reIndex && indexExists, + }; + + const completeStatus: IndexingStatusUpdate = { + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + }; + + if (indexExists && !reIndex) { yield { - progress: 1, - desc: "Already indexed", - status: "done", + ...completeStatus, + debugInfo: "Already indexed", }; return; } @@ -200,9 +323,10 @@ export default class DocsService { this.docsIndexingQueue.add(startUrl); yield { - progress: 0, - desc: "Finding subpages", + ...fixedStatus, status: "indexing", + description: "Finding subpages", + progress: 0, }; const articles: Article[] = []; @@ -225,9 +349,10 @@ export default class DocsService { const progress = Math.min(processedPages / maxKnownPages, 1); yield { - progress, // Yield the heuristic progress - desc: `Finding subpages (${page.path})`, + ...fixedStatus, + description: `Finding subpages (${page.path})`, status: "indexing", + progress, // Yield the heuristic progress }; // Increase maxKnownPages to delay progress reaching 100% too soon @@ -246,14 +371,15 @@ export default class DocsService { const embeddings: number[][] = []; // Create embeddings of retrieved articles - console.log(`Creating embeddings for ${articles.length} articles`); + console.debug(`Creating embeddings for ${articles.length} articles`); for (let i = 0; i < articles.length; i++) { const article = articles[i]; yield { - progress: i / articles.length, - desc: `Creating Embeddings: ${article.subpath}`, + ...fixedStatus, status: "indexing", + description: `Creating Embeddings: ${article.subpath}`, + progress: i / articles.length, }; try { @@ -284,9 +410,10 @@ export default class DocsService { ); yield { - progress: 1, - desc: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", + progress: 1, }; this.docsIndexingQueue.delete(startUrl); @@ -298,13 +425,14 @@ export default class DocsService { console.log(`Adding ${embeddings.length} embeddings to db`); yield { - progress: 0.5, - desc: `Adding ${embeddings.length} embeddings to db`, + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", + progress: 0.5, }; // Delete indexed docs if re-indexing - if (reIndex && (await this.has(startUrl.toString()))) { + if (reIndex && (await this.hasMetadata(startUrl.toString()))) { console.log("Deleting old embeddings"); await this.delete(startUrl); } @@ -321,9 +449,10 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); yield { + ...fixedStatus, + description: "Complete", + status: "complete", progress: 1, - desc: "Done", - status: "done", }; console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); @@ -333,15 +462,50 @@ export default class DocsService { } } + // Retrieve docs embeds based on user input + async retrieveChunksFromQuery( + query: string, + startUrl: string, + nRetrieve: number, + ) { + if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { + await this.ide.showToast( + "error", + `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + + "the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE" + "Please select a different embeddings provider to use the '@docs' " + + "context provider.", + ); + + return []; + } + + const preIndexedDoc = preIndexedDocs[query]; + + if (!!preIndexedDoc) { + void Telemetry.capture("docs_pre_indexed_doc_used", { + doc: preIndexedDoc["title"], + }); + } + + const embeddingsProvider = + await this.getEmbeddingsProvider(!!preIndexedDoc); + + const [vector] = await embeddingsProvider.embed([query]); + + return await this.retrieveChunks(query, vector, nRetrieve); + } + async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, isRetry: boolean = false, ): Promise { + const embeddingsProvider = await this.getEmbeddingsProvider(); const table = await this.getOrCreateLanceTable({ initializationVector: vector, - isPreIndexedDoc: !!preIndexedDocs[startUrl], + embeddingsProvider, }); let docs: LanceDbDocsRow[] = []; @@ -355,7 +519,7 @@ export default class DocsService { console.error("Error retrieving chunks from LanceDB", e); } - const hasIndexedDoc = await this.hasIndexedDoc(startUrl); + const hasIndexedDoc = await this.hasMetadata(startUrl); if (!hasIndexedDoc && docs.length === 0) { const preIndexedDoc = preIndexedDocs[startUrl]; @@ -381,121 +545,7 @@ export default class DocsService { })); } - async getEmbeddingsProvider(isPreIndexedDoc: boolean = false) { - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - - if (isPreIndexedDoc && canUsePreindexedDocs) { - return DocsService.preIndexedDocsEmbeddingsProvider; - } - - return this.config.embeddingsProvider; - } - - async getFavicon(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const result = await db.get( - `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - if (!result) { - return; - } - return result.favicon; - } - - private async init(configHandler: ConfigHandler) { - this.config = await configHandler.loadConfig(); - await this.handleConfigUpdate({ config: this.config }); - - // only update on init because should only update on reindexDocsOnNewEmbeddingsProvider - const currentEmbeddingsProvider = this.globalContext.get( - "curEmbeddingsProviderId", - ); - if (!currentEmbeddingsProvider) { - const embeddingsProvider = await this.getEmbeddingsProvider(); - this.globalContext.update( - "curEmbeddingsProviderId", - embeddingsProvider.id, - ); - } - - configHandler.onConfigUpdate(this.handleConfigUpdate); - } - - private async handleConfigUpdate({ - config: newConfig, - }: { - config: ContinueConfig | undefined; - }) { - if (newConfig) { - this.config = newConfig; - this.docsCrawler = new DocsCrawler(this.ide, this.config); - - const oldConfig = this.config; - - // Need to update class property for config at the beginning of this callback - // to ensure downstream methods have access to the latest config. - this.config = newConfig; - - if (oldConfig.docs !== newConfig.docs) { - await this.syncConfigAndSqlite(); - } - - const shouldReindex = await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); - - if (shouldReindex) { - await this.reindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider, - ); - } - } - } - - private async syncConfigAndSqlite() { - this.isSyncing = true; - - const sqliteDocs = await this.list(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; - - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; - - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( - (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], - ); - - for (const doc of newDocs) { - console.log(`Indexing new doc: ${doc.startUrl}`); - void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} - } - - for (const doc of deletedDocs) { - // console.debug(`Deleting doc: ${doc.startUrl}`); - await this.delete(doc.startUrl); - } - - this.isSyncing = false; - } - - private hasDocsContextProvider() { - return !!this.config.contextProviders?.some( - (provider) => - provider.description.title === DocsContextProvider.description.title, - ); - } - + // SQLITE DB private async getOrCreateSqliteDb() { if (!this.sqliteDb) { const db = await open({ @@ -520,6 +570,65 @@ export default class DocsService { return this.sqliteDb; } + async getFavicon(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + const result = await db.get( + `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + if (!result) { + return; + } + return result.favicon; + } + + private async syncConfigAndSqlite() { + try { + this.isSyncing = true; + + const sqliteDocs = await this.listMetadata(); + const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; + + const configDocs = this.config.docs || []; + const configDocStartUrls = + this.config.docs?.map((doc) => doc.startUrl) || []; + + const newDocs = configDocs.filter( + (doc) => !sqliteDocStartUrls.includes(doc.startUrl), + ); + const deletedDocs = sqliteDocs.filter( + (doc) => + !configDocStartUrls.includes(doc.startUrl) && + !preIndexedDocs[doc.startUrl], + ); + + for (const doc of newDocs) { + console.log(`Indexing new doc: ${doc.startUrl}`); + void Telemetry.capture("add_docs_config", { url: doc.startUrl }); + + const generator = this.indexAndAdd(doc); + while (!(await generator.next()).done) {} + } + + for (const doc of deletedDocs) { + await this.delete(doc.startUrl); + } + } catch (e) { + console.error("Error syncing config and sqlite", e); + } finally { + this.isSyncing = false; + } + } + + private hasDocsContextProvider() { + return !!this.config.contextProviders?.some( + (provider) => + provider.description.title === DocsContextProvider.description.title, + ); + } + + // Lance DB Initialization private async createLanceDocsTable( connection: Connection, initializationVector: number[], @@ -554,11 +663,8 @@ export default class DocsService { } private async getLanceTableNameFromEmbeddingsProvider( - isPreIndexedDoc: boolean, + embeddingsProvider: EmbeddingsProvider, ) { - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); - const tableName = this.sanitizeLanceTableName( `${DocsService.lanceTableName}${embeddingsProvider.id}`, ); @@ -568,15 +674,15 @@ export default class DocsService { private async getOrCreateLanceTable({ initializationVector, - isPreIndexedDoc, + embeddingsProvider, }: { initializationVector: number[]; - isPreIndexedDoc?: boolean; + embeddingsProvider: EmbeddingsProvider; }) { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const tableNameFromEmbeddingsProvider = - await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); + await this.getLanceTableNameFromEmbeddingsProvider(embeddingsProvider); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -600,40 +706,7 @@ export default class DocsService { return table; } - private async isJetBrains() { - const ideInfo = await this.ide.getIdeInfo(); - return ideInfo.ideType === "jetbrains"; - } - - async isJetBrainsAndPreIndexedDocsProvider(): Promise { - const isJetBrains = await this.isJetBrains(); - - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; - - return isJetBrains && isPreIndexedDocsProvider; - } - - /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers. - * However, we don't ship transformers with the JetBrains extension. - * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. - */ - async canUsePreindexedDocs() { - const isJetBrains = await this.isJetBrains(); - return !isJetBrains; - } - - private async hasIndexedDoc(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const docs = await db.all( - `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - return docs.length > 0; - } + // Add methods for Individual docs private async addToLance({ chunks, @@ -642,8 +715,11 @@ export default class DocsService { }: AddParams) { const sampleVector = embeddings[0]; const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + const embeddingsProvider = + await this.getEmbeddingsProvider(isPreIndexedDoc); + const table = await this.getOrCreateLanceTable({ - isPreIndexedDoc, + embeddingsProvider, initializationVector: sampleVector, }); @@ -660,7 +736,7 @@ export default class DocsService { await table.add(rows); } - private async addToSqlite({ + private async addMetadataToSqlite({ siteIndexingConfig: { title, startUrl }, favicon, }: AddParams) { @@ -690,7 +766,7 @@ export default class DocsService { private async add(params: AddParams) { await this.addToLance(params); - await this.addToSqlite(params); + await this.addMetadataToSqlite(params); const isPreIndexedDoc = !!preIndexedDocs[params.siteIndexingConfig.startUrl]; @@ -700,7 +776,8 @@ export default class DocsService { } } - private async deleteFromLance(startUrl: string) { + // Delete methods for individual docs + private async deleteEmbeddingsFromLance(startUrl: string) { for (const tableName of this.lanceTableNamesSet) { const conn = await lancedb.connect(getLanceDbPath()); const table = await conn.openTable(tableName); @@ -708,7 +785,7 @@ export default class DocsService { } } - private async deleteFromSqlite(startUrl: string) { + private async deleteMetadataFromSqlite(startUrl: string) { const db = await this.getOrCreateSqliteDb(); await db.run( `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -716,13 +793,26 @@ export default class DocsService { ); } - deleteFromConfig(startUrl: string) { + private deleteFromConfig(startUrl: string) { editConfigJson((config) => ({ ...config, docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], })); } + async delete(startUrl: string) { + await this.deleteEmbeddingsFromLance(startUrl); + await this.deleteMetadataFromSqlite(startUrl); + this.deleteFromConfig(startUrl); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } + + // When user requests a pre-indexed doc for the first time + // And pre-indexed embeddings are supported + // Fetch pre-indexed embeddings from S3, add to Lance, and then search those private async fetchAndAddPreIndexedDocEmbeddings(title: string) { const embeddingsProvider = await this.getEmbeddingsProvider(true); @@ -751,59 +841,17 @@ export default class DocsService { }); } - private async shouldReindexDocsOnNewEmbeddingsProvider( - curEmbeddingsProviderId: EmbeddingsProvider["id"], - ): Promise { - const isJetBrainsAndPreIndexedDocsProvider = - await this.isJetBrainsAndPreIndexedDocsProvider(); - - if (isJetBrainsAndPreIndexedDocsProvider) { - // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider - // this.ide.showToast( - // "error", - // "The 'transformers.js' embeddings provider currently cannot be used to index " + - // "documentation in JetBrains. To enable documentation indexing, you can use " + - // "any of the other providers described in the docs: " + - // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - // ); - - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - const lastEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - - if (!lastEmbeddingsProviderId) { - // If it's the first time we're setting the `curEmbeddingsProviderId` - // global state, we don't need to reindex docs - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - return lastEmbeddingsProviderId !== curEmbeddingsProviderId; - } + // METHODS FOR MASS REINDEXING /** * Currently this deletes re-crawls + re-indexes all docs. * A more optimal solution in the future will be to create * a per-embeddings-provider table for docs. */ - private async reindexDocsOnNewEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, - ) { + private async reindexDocsOnNewEmbeddingsProvider() { // We use config as our source of truth here since it contains additional information // needed for re-crawling such as `faviconUrl` and `maxDepth`. - const { docs } = this.config; + const { docs, embeddingsProvider } = this.config; if (!docs || docs.length === 0) { return; @@ -815,9 +863,10 @@ export default class DocsService { for (const doc of docs) { await this.delete(doc.startUrl); + } + for (const doc of docs) { const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..077fa4315 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,7 +41,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", - "index/indexingProgressBarInitialized", + "index/indexingProgressBarInitialized", // Deprecated + "index/getStatuses", + "completeOnboarding", "addAutocompleteModel", "config/listProfiles", @@ -55,10 +57,11 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "configUpdate", "getDefaultModelTitle", "indexProgress", + "index/statusUpdate", // "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; From af4e5ee4400f65843319ce4f50e487e80344605d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 01:22:57 -0800 Subject: [PATCH 08/21] indexing manager --- core/context/providers/DocsContextProvider.ts | 1 - core/core.ts | 41 +++-- core/index.d.ts | 19 +- core/indexing/IndexingStatusManager.ts | 104 +++++++++++ core/indexing/docs/DocsService.test.ts | 9 +- core/indexing/docs/DocsService.ts | 171 +++++++++++------- core/protocol/core.ts | 12 ++ core/protocol/passThrough.ts | 15 +- core/protocol/webview.ts | 7 +- gui/src/hooks/useSetup.ts | 8 - 10 files changed, 274 insertions(+), 113 deletions(-) create mode 100644 core/indexing/IndexingStatusManager.ts diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f3a1e5d77..2f2ca9002 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -9,7 +9,6 @@ import { } from "../.."; import DocsService from "../../indexing/docs/DocsService"; import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; -import { Telemetry } from "../../util/posthog"; import { INSTRUCTIONS_BASE_ITEM } from "./utils"; diff --git a/core/core.ts b/core/core.ts index c1075dfd6..fe07ecbce 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,6 +35,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; +import { IndexingStatusManager } from "./indexing/IndexingStatusManager"; export class Core { // implements IMessenger @@ -43,8 +44,8 @@ export class Core { completionProvider: CompletionProvider; continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; - docsIndexingStates: Map = new Map(); controlPlaneClient: ControlPlaneClient; + private indexingManager: IndexingStatusManager; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -109,6 +110,8 @@ export class Core { this.controlPlaneClient, ); + this.indexingManager = new IndexingStatusManager(this.messenger); + this.docsService = DocsService.createSingleton( this.configHandler, this.ide, @@ -278,32 +281,15 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - // let hasFailed = false; - // for await (const result of this.docsService.indexAndAdd(msg.data)) { - // if (result.status === "failed") { - // hasFailed = true; - // break; - // } - // } - // if (hasFailed) { - // void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); - // } else { - // void this.ide.showToast( - // "info", - // `Successfully indexed ${msg.data.startUrl}`, - // ); - // this.messenger.send("refreshSubmenuItems", undefined); - // } + void this.docsService.indexAndAdd(msg.data); }); on("context/removeDocs", async (msg) => { await this.docsService.delete(msg.data.startUrl); - this.messenger.send("refreshSubmenuItems", undefined); }); on("context/indexDocs", async (msg) => { - await this.docsService.indexAllDocs(msg.data.reIndex); - this.messenger.send("refreshSubmenuItems", undefined); + await this.docsService.indexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -726,6 +712,19 @@ export class Core { recentlyEditedFilesCache.set(filepath, filepath); } }); + + on("indexing/reindex", async (msg) => { + this.indexingManager.reindex(msg.data.id); + }); + on("indexing/abort", async (msg) => { + this.indexingManager.abort(msg.data.id); + }); + on("indexing/setPaused", async (msg) => { + this.indexingManager.setPaused(msg.data.id, msg.data.pause); + }); + on("indexing/getStatuses", async (msg) => { + return this.indexingManager.statuses; + }); } private indexingCancellationController: AbortController | undefined; @@ -768,4 +767,6 @@ export class Core { this.messenger.send("refreshSubmenuItems", undefined); } + + // private } diff --git a/core/index.d.ts b/core/index.d.ts index b6b4c7f0c..f1c7263eb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -47,22 +47,21 @@ export interface IndexingProgressUpdate { // This is more or less a V2 of IndexingProgressUpdate export interface IndexingStatusUpdate { + id: string; type: "docs"; - id: string; // Unique identifier, e.g. docs start url progress: number; description: string; - status: - | "initializing" - | "indexing" - | "complete" - | "paused" - | "failed" - | "disabled"; - embeddingsModel: string; - isReindexing: boolean; + status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "deleted"; + embeddingsProviderId: string; + isReindexing?: boolean; debugInfo?: string; } +export type IndexingStatusMap = Map< + string, + Map +>; + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts new file mode 100644 index 000000000..1ba177493 --- /dev/null +++ b/core/indexing/IndexingStatusManager.ts @@ -0,0 +1,104 @@ +import { IndexingStatusMap, IndexingStatusUpdate } from ".."; +import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; +import { IMessenger } from "../util/messenger"; + +/* + Any service that sends indexing updates can use an instance of this class + 1. Pass indexingManager to the service + 2. Register the service with the manager using `registerService` + E.g. docs uses startUrl as id + 3. +*/ +export class IndexingStatusManager { + private readonly messenger: IMessenger; + readonly statuses: IndexingStatusMap = new Map(); + private readonly reindexTypeFunctions: Map< + string, + (id: string) => Promise + > = new Map(); + + constructor(messenger: IMessenger) { + this.messenger = messenger; + } + + // Services that use an instance of this class should add their reindex functions here + registerService(type: string, fn: (id: string) => Promise) { + this.reindexTypeFunctions.set(type, fn); + this.statuses.set(type, new Map()); + } + + reindex(type: string, id: string) { + const byType = this.statuses.get(type); + const reindexFn = this.reindexTypeFunctions.get(type); + + if (byType && reindexFn) { + const status = byType.get(id); + if (status) { + if (status.status === "deleted") { + throw new Error( + "Cannot reindex a deleted item, shouldn't ever happen", + ); + } + void reindexFn(id); + } + } + } + + handleUpdate(status: IndexingStatusUpdate) { + const byType = this.statuses.get(status.type); + if (byType) { + byType.set(status.id, status); + this.messenger.send("indexing/statusUpdate", status); + } + } + + delete(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: "deleted" }); + } + } + } + + abort(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: "aborted" }); + } + } + } + + isAborted(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + return status.status === "aborted"; + } + } + } + + setPaused(type: string, id: string, pause: boolean) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); + } + } + } + + isPaused(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + return status.status === "paused"; + } + } + } +} diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 11fed29e5..4a911b38a 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -66,8 +66,7 @@ describe.skip("DocsService Integration Tests", () => { }); test("Indexing, retrieval, and deletion of a new documentation site", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); let latestConfig = await getReloadedConfig(); @@ -133,13 +132,11 @@ describe.skip("DocsService Integration Tests", () => { test("Handles pulling down and adding pre-indexed docs", async () => { const preIndexedDoc = Object.values(preIndexedDocs)[0]; - const generator = docsService.indexAndAdd(preIndexedDoc); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(preIndexedDoc); }); test("Config synchronization with SQLite", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); await getReloadedConfig(); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 79dea28e6..9450cca6b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -24,6 +24,7 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; +import { IndexingStatusManager } from "../IndexingStatusManager"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; @@ -78,6 +79,8 @@ export type AddParams = { export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; + static indexingType = "docs"; + static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); @@ -97,6 +100,7 @@ export default class DocsService { configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, + private readonly indexingManager?: IndexingStatusManager, ) { this.isInitialized = this.init(configHandler); } @@ -119,9 +123,12 @@ export default class DocsService { // Initialization - load config and attach config listener private async init(configHandler: ConfigHandler) { + this.indexingManager?.registerService( + DocsService.indexingType, + this.reindexDoc, + ); this.config = await configHandler.loadConfig(); await this.handleConfigUpdate({ config: this.config }); - configHandler.onConfigUpdate(this.handleConfigUpdate); } @@ -180,14 +187,7 @@ export default class DocsService { return; } - const newConfigDocs = newConfig.docs || []; - const oldConfigDocs = oldConfig.docs || []; - - const newPreindexed = newConfigDocs.filter( - (doc) => !!preIndexedDocs[doc.startUrl], - ); - - // On embeddings provider change, reindex all docs + // On embeddings provider change, reindex all non-preindexed docs // change = doesn't match last successful embeddings provider const curEmbeddingsProviderId = this.globalContext.get( "curEmbeddingsProviderId", @@ -204,7 +204,7 @@ export default class DocsService { } } - await this.syncConfigAndSqlite(); + await this.syncDocsOnConfigUpdate(oldConfig, newConfig); } } @@ -251,7 +251,7 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocs(reIndex: boolean = false) { + async indexAllDocsWithPrompt(reIndex: boolean = false) { if (!this.hasDocsContextProvider()) { const didAddDocsContextProvider = await this.showAddDocsContextProviderToast(); @@ -264,8 +264,7 @@ export default class DocsService { const docs = await this.listMetadata(); for (const doc of docs) { - const generator = this.indexAndAdd(doc, reIndex); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc, reIndex); } void this.ide.showToast("info", "Docs indexing completed"); @@ -280,10 +279,23 @@ export default class DocsService { return docs; } - async *indexAndAdd( + updateIndexingStatus(update: IndexingStatusUpdate) { + this.indexingManager?.handleUpdate(update); + } + + async reindexDoc(startUrl: string) { + const docConfig = this.config.docs?.find( + (doc) => doc.startUrl === startUrl, + ); + if (docConfig) { + await this.indexAndAdd(docConfig, true); + } + } + + async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, - ): AsyncGenerator { + ): Promise { const { startUrl } = siteIndexingConfig; if (this.docsIndexingQueue.has(startUrl)) { @@ -296,38 +308,34 @@ export default class DocsService { const fixedStatus: Pick< IndexingStatusUpdate, - "type" | "id" | "embeddingsModel" | "isReindexing" + "type" | "id" | "embeddingsProviderId" | "isReindexing" > = { type: "docs", id: siteIndexingConfig.startUrl, - embeddingsModel: embeddingsProvider.id, + embeddingsProviderId: embeddingsProvider.id, isReindexing: reIndex && indexExists, }; - const completeStatus: IndexingStatusUpdate = { - ...fixedStatus, - progress: 1, - description: "Complete", - status: "complete", - }; - if (indexExists && !reIndex) { - yield { - ...completeStatus, + this.updateIndexingStatus({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", debugInfo: "Already indexed", - }; + }); return; } // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - yield { + this.updateIndexingStatus({ ...fixedStatus, status: "indexing", description: "Finding subpages", progress: 0, - }; + }); const articles: Article[] = []; let processedPages = 0; @@ -348,12 +356,12 @@ export default class DocsService { // Use a heuristic approach for progress calculation const progress = Math.min(processedPages / maxKnownPages, 1); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", progress, // Yield the heuristic progress - }; + }); // Increase maxKnownPages to delay progress reaching 100% too soon if (processedPages === maxKnownPages) { @@ -375,12 +383,12 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - yield { + this.updateIndexingStatus({ ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, progress: i / articles.length, - }; + }); try { const chunkedArticle = chunkArticle( @@ -409,12 +417,14 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", progress: 1, - }; + }); + + void this.ide.showToast("info", `Failed to index ${startUrl}`); this.docsIndexingQueue.delete(startUrl); @@ -424,12 +434,12 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", progress: 0.5, - }; + }); // Delete indexed docs if re-indexing if (reIndex && (await this.hasMetadata(startUrl.toString()))) { @@ -448,14 +458,14 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: "Complete", status: "complete", progress: 1, - }; + }); - console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); if (this.messenger) { this.messenger.send("refreshSubmenuItems", undefined); @@ -480,8 +490,7 @@ export default class DocsService { return []; } - const preIndexedDoc = preIndexedDocs[query]; - + const preIndexedDoc = preIndexedDocs[startUrl]; if (!!preIndexedDoc) { void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDoc["title"], @@ -583,32 +592,72 @@ export default class DocsService { return result.favicon; } - private async syncConfigAndSqlite() { + /* + Sync with no embeddings provider change + Ignores pre-indexed docs + */ + private async syncDocsOnConfigUpdate( + oldConfig: ContinueConfig, + newConfig: ContinueConfig, + ) { try { this.isSyncing = true; - const sqliteDocs = await this.listMetadata(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; + // Otherwise sync the index based on config changes + const oldConfigDocs = oldConfig.docs || []; + const newConfigDocs = newConfig.docs || []; + const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; + const currentlyIndexedDocs = await this.listMetadata(); + const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( + // const newDocs = newConfigDocs.filter( + // (doc) => !currentStartUrls.includes(doc.startUrl), + // ); + + // Anything found in sqlite but not in new config should be deleted + const deletedDocs = currentlyIndexedDocs.filter( (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], + !preIndexedDocs[doc.startUrl] && + !newConfigStartUrls.includes(doc.startUrl), ); + // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed + // TODO if only favicon and title change, only update, don't embed + // Otherwise anything found in new config that isn't in sqlite should be added/indexed + const newDocs: SiteIndexingConfig[] = []; + const changedDocs: SiteIndexingConfig[] = []; + for (const doc of newConfigDocs) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); + const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); + + if (currentIndexedDoc) { + if ( + oldConfigDoc && + (oldConfigDoc.maxDepth !== doc.maxDepth || + oldConfigDoc.title !== doc.title || + oldConfigDoc.faviconUrl !== doc.faviconUrl) + ) { + changedDocs.push(doc); + } + // if get's here, not changed, no update needed + } else { + newDocs.push(doc); + } + } + + for (const doc of changedDocs) { + console.log(`Updating indexed doc: ${doc.startUrl}`); + await this.indexAndAdd(doc, true); + } + for (const doc of newDocs) { console.log(`Indexing new doc: ${doc.startUrl}`); void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc); } for (const doc of deletedDocs) { @@ -706,8 +755,7 @@ export default class DocsService { return table; } - // Add methods for Individual docs - + // Methods for adding individual docs private async addToLance({ chunks, siteIndexingConfig, @@ -858,7 +906,7 @@ export default class DocsService { } console.log( - `Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`, + `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); for (const doc of docs) { @@ -866,8 +914,7 @@ export default class DocsService { } for (const doc of docs) { - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc); } // Important that this only is invoked after we have successfully @@ -875,6 +922,6 @@ export default class DocsService { // invalid state. this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - console.log("Completed reindexing of all docs"); + console.log("Completed reindexing of all non-preindexed docs"); } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..fec158eac 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,6 +8,7 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, + IndexingStatusMap, LLMFullCompletionOptions, MessageContent, ModelDescription, @@ -142,6 +143,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { { model: string; promptTokens: number; generatedTokens: number }[], ]; "tts/kill": [undefined, void]; + + // Codebase indexing "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, @@ -154,6 +157,15 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + + // Docs Indexing. TODO move codebase to this + "indexing/reindex": [ + { id: string; shouldClearAllOfIndexType?: boolean }, + void, + ]; + "indexing/abort": [{ id: string }, void]; + "indexing/setPaused": [{ id: string; pause: boolean }, void]; + "indexing/getStatuses": [undefined, IndexingStatusMap]; addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 077fa4315..b2d18c533 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -39,11 +39,16 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "chatDescriber/describe", "stats/getTokensPerDay", "stats/getTokensPerModel", + // Codebase "index/setPaused", "index/forceReIndex", - "index/indexingProgressBarInitialized", // Deprecated - "index/getStatuses", - + "index/indexingProgressBarInitialized", + // Docs, etc. + "indexing/getStatuses", + "indexing/reindex", + "indexing/abort", + "indexing/setPaused", + // "completeOnboarding", "addAutocompleteModel", "config/listProfiles", @@ -56,8 +61,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", "getDefaultModelTitle", - "indexProgress", - "index/statusUpdate", // + "indexProgress", // Codebase + "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index d974c1516..4fd2f7094 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,12 +1,17 @@ import { ConfigValidationError } from "../config/validation.js"; -import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js"; +import type { + ContextItemWithId, + IndexingProgressUpdate, + IndexingStatusUpdate, +} from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; + "indexing/statusUpdate": [IndexingStatusUpdate, void]; refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 58feba2a5..5329abdda 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -110,16 +110,8 @@ function useSetup(dispatch: Dispatch) { }); }); - const debouncedIndexDocs = debounce(() => { - ideMessenger.request("context/indexDocs", { reIndex: false }); - }, 1000); - useWebviewListener("configUpdate", async () => { await loadConfig(); - - if (!isJetBrains) { - debouncedIndexDocs(); - } }); useWebviewListener("configError", async (error) => { From 34627a94d473a16ffdc6c185ac695bd1ebfc7043 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 02:25:32 -0800 Subject: [PATCH 09/21] indexing manager p2 --- core/core.ts | 11 ++-- core/index.d.ts | 5 ++ core/indexing/IndexingStatusManager.ts | 89 +++++++++++--------------- core/indexing/docs/DocsService.ts | 24 ++++--- core/protocol/core.ts | 11 ++-- core/protocol/webview.ts | 4 +- extensions/vscode/package-lock.json | 4 +- gui/src/hooks/useSetup.ts | 10 +++ 8 files changed, 85 insertions(+), 73 deletions(-) diff --git a/core/core.ts b/core/core.ts index fe07ecbce..8a27fedc3 100644 --- a/core/core.ts +++ b/core/core.ts @@ -110,12 +110,15 @@ export class Core { this.controlPlaneClient, ); - this.indexingManager = new IndexingStatusManager(this.messenger); + this.indexingManager = IndexingStatusManager.createSingleton( + this.messenger, + ); this.docsService = DocsService.createSingleton( this.configHandler, this.ide, this.messenger, + this.indexingManager, ); this.configHandler.onConfigUpdate( @@ -714,13 +717,13 @@ export class Core { }); on("indexing/reindex", async (msg) => { - this.indexingManager.reindex(msg.data.id); + this.indexingManager.reindex(msg.data.identifier); }); on("indexing/abort", async (msg) => { - this.indexingManager.abort(msg.data.id); + this.indexingManager.abort(msg.data.identifier); }); on("indexing/setPaused", async (msg) => { - this.indexingManager.setPaused(msg.data.id, msg.data.pause); + this.indexingManager.setPaused(msg.data.identifier, msg.data.pause); }); on("indexing/getStatuses", async (msg) => { return this.indexingManager.statuses; diff --git a/core/index.d.ts b/core/index.d.ts index f1c7263eb..53ca6ae42 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -57,6 +57,11 @@ export interface IndexingStatusUpdate { debugInfo?: string; } +interface IndexIdentifier { + type: string; + id: string; +} + export type IndexingStatusMap = Map< string, Map diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts index 1ba177493..785f14b95 100644 --- a/core/indexing/IndexingStatusManager.ts +++ b/core/indexing/IndexingStatusManager.ts @@ -1,4 +1,4 @@ -import { IndexingStatusMap, IndexingStatusUpdate } from ".."; +import { IndexIdentifier, IndexingStatusMap, IndexingStatusUpdate } from ".."; import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import { IMessenger } from "../util/messenger"; @@ -7,7 +7,8 @@ import { IMessenger } from "../util/messenger"; 1. Pass indexingManager to the service 2. Register the service with the manager using `registerService` E.g. docs uses startUrl as id - 3. + 3. Rules of engagement: + - service is responsible for checking corrupted indexes - don't check paused or deleted */ export class IndexingStatusManager { private readonly messenger: IMessenger; @@ -21,26 +22,29 @@ export class IndexingStatusManager { this.messenger = messenger; } + private static instance?: IndexingStatusManager; + static createSingleton( + messenger: IMessenger, + ) { + const instance = new IndexingStatusManager(messenger); + IndexingStatusManager.instance = instance; + return instance; + } + + static getSingleton() { + return IndexingStatusManager.instance; + } + // Services that use an instance of this class should add their reindex functions here registerService(type: string, fn: (id: string) => Promise) { this.reindexTypeFunctions.set(type, fn); this.statuses.set(type, new Map()); } - reindex(type: string, id: string) { - const byType = this.statuses.get(type); + reindex({ type, id }: IndexIdentifier) { const reindexFn = this.reindexTypeFunctions.get(type); - - if (byType && reindexFn) { - const status = byType.get(id); - if (status) { - if (status.status === "deleted") { - throw new Error( - "Cannot reindex a deleted item, shouldn't ever happen", - ); - } - void reindexFn(id); - } + if (reindexFn) { + void reindexFn(id); } } @@ -52,53 +56,38 @@ export class IndexingStatusManager { } } - delete(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - this.handleUpdate({ ...status, status: "deleted" }); - } + delete({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + this.handleUpdate({ ...status, status: "deleted" }); } } - abort(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - this.handleUpdate({ ...status, status: "aborted" }); - } + abort({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + this.handleUpdate({ ...status, status: "aborted" }); } } - isAborted(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - return status.status === "aborted"; - } + isAborted({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + return status.status === "aborted"; } } - setPaused(type: string, id: string, pause: boolean) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); - } + setPaused({ type, id }: IndexIdentifier, pause: boolean) { + const status = this.statuses.get(type)?.get(id); + if (status) { + this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); } } - isPaused(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - return status.status === "paused"; - } + isPaused({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + return status.status === "paused"; } } } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 9450cca6b..cb6e12bee 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -111,8 +111,14 @@ export default class DocsService { configHandler: ConfigHandler, ide: IDE, messenger?: IMessenger, + indexingManager?: IndexingStatusManager, ) { - const docsService = new DocsService(configHandler, ide, messenger); + const docsService = new DocsService( + configHandler, + ide, + messenger, + indexingManager, + ); DocsService.instance = docsService; return docsService; } @@ -127,9 +133,9 @@ export default class DocsService { DocsService.indexingType, this.reindexDoc, ); - this.config = await configHandler.loadConfig(); - await this.handleConfigUpdate({ config: this.config }); - configHandler.onConfigUpdate(this.handleConfigUpdate); + const config = await configHandler.loadConfig(); + await this.handleConfigUpdate({ config }); + configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } // Config @@ -502,7 +508,7 @@ export default class DocsService { const [vector] = await embeddingsProvider.embed([query]); - return await this.retrieveChunks(query, vector, nRetrieve); + return await this.retrieveChunks(startUrl, vector, nRetrieve); } async retrieveChunks( @@ -525,7 +531,7 @@ export default class DocsService { .where(`starturl = '${startUrl}'`) .execute(); } catch (e: any) { - console.error("Error retrieving chunks from LanceDB", e); + console.warn("Error retrieving chunks from LanceDB", e); } const hasIndexedDoc = await this.hasMetadata(startUrl); @@ -597,14 +603,14 @@ export default class DocsService { Ignores pre-indexed docs */ private async syncDocsOnConfigUpdate( - oldConfig: ContinueConfig, + oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, ) { try { this.isSyncing = true; // Otherwise sync the index based on config changes - const oldConfigDocs = oldConfig.docs || []; + const oldConfigDocs = oldConfig?.docs || []; const newConfigDocs = newConfig.docs || []; const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); @@ -664,7 +670,7 @@ export default class DocsService { await this.delete(doc.startUrl); } } catch (e) { - console.error("Error syncing config and sqlite", e); + console.error("Error syncing docs index on config update", e); } finally { this.isSyncing = false; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index fec158eac..2e5a660d4 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,6 +8,7 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, + IndexIdentifier, IndexingStatusMap, LLMFullCompletionOptions, MessageContent, @@ -159,13 +160,11 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; // Docs Indexing. TODO move codebase to this - "indexing/reindex": [ - { id: string; shouldClearAllOfIndexType?: boolean }, - void, - ]; - "indexing/abort": [{ id: string }, void]; - "indexing/setPaused": [{ id: string; pause: boolean }, void]; + "indexing/reindex": [{ identifier: IndexIdentifier }, void]; + "indexing/abort": [{ identifier: IndexIdentifier }, void]; + "indexing/setPaused": [{ identifier: IndexIdentifier; pause: boolean }, void]; "indexing/getStatuses": [undefined, IndexingStatusMap]; + addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 4fd2f7094..e5330d81f 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -10,8 +10,8 @@ export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; - indexProgress: [IndexingProgressUpdate, void]; - "indexing/statusUpdate": [IndexingStatusUpdate, void]; + indexProgress: [IndexingProgressUpdate, void]; // Codebase + "indexing/statusUpdate": [IndexingStatusUpdate, void]; // Docs, etc. refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 24930d980..29ac4731f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 5329abdda..07bcec0eb 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -135,6 +135,16 @@ function useSetup(dispatch: Dispatch) { ); }); + useWebviewListener("indexing/statusUpdate", async (data) => { + console.log("Indexing status update", data); + // dispatch( + // addContextItemsAtIndex({ + // index: data.historyIndex, + // contextItems: [data.item], + // }), + // ); + }); + useWebviewListener( "getDefaultModelTitle", async () => { From b14aca3b996afd6bdfbe3b89544de84a01516545 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 02:47:13 -0800 Subject: [PATCH 10/21] docs service debugging --- core/context/providers/DocsContextProvider.ts | 2 +- core/indexing/docs/DocsService.test.ts | 10 ++++------ core/indexing/docs/DocsService.ts | 9 ++++----- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 2f2ca9002..6eab55fa4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -89,7 +89,7 @@ class DocsContextProvider extends BaseContextProvider { await docsService.isInitialized; let chunks = await docsService.retrieveChunksFromQuery( - extras.fullInput, + extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 4a911b38a..67d33020d 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -77,11 +77,9 @@ describe.skip("DocsService Integration Tests", () => { expect(latestConfig.docs).toContainEqual(mockSiteConfig); // Lance DB check - const embeddingsProvider = await docsService.getEmbeddingsProvider(); - const [mockVector] = await embeddingsProvider.embed(["test"]); - let retrievedChunks = await docsService.retrieveChunks( + let retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); @@ -99,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => { ); // LanceDB check - retrievedChunks = await docsService.retrieveChunks( + retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); expect(retrievedChunks.length).toBe(0); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index cb6e12bee..c37b68553 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -199,8 +199,8 @@ export default class DocsService { "curEmbeddingsProviderId", ); if ( - curEmbeddingsProviderId && - curEmbeddingsProviderId !== curEmbeddingsProviderId + !curEmbeddingsProviderId || + curEmbeddingsProviderId !== newConfig.embeddingsProvider.id ) { // If not set, we're initializing const currentDocs = await this.listMetadata(); @@ -517,7 +517,8 @@ export default class DocsService { nRetrieve: number, isRetry: boolean = false, ): Promise { - const embeddingsProvider = await this.getEmbeddingsProvider(); + const isPreindexed = !!preIndexedDocs[startUrl]; + const embeddingsProvider = await this.getEmbeddingsProvider(isPreindexed); const table = await this.getOrCreateLanceTable({ initializationVector: vector, embeddingsProvider, @@ -895,8 +896,6 @@ export default class DocsService { }); } - // METHODS FOR MASS REINDEXING - /** * Currently this deletes re-crawls + re-indexes all docs. * A more optimal solution in the future will be to create From 08d8f3781be54f191bd426cc9a4058f2960890c4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 02:55:31 -0800 Subject: [PATCH 11/21] docs working --- core/indexing/docs/DocsService.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index c37b68553..ee7520eb5 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -517,11 +517,10 @@ export default class DocsService { nRetrieve: number, isRetry: boolean = false, ): Promise { - const isPreindexed = !!preIndexedDocs[startUrl]; - const embeddingsProvider = await this.getEmbeddingsProvider(isPreindexed); + const isPreIndexedDoc = !!preIndexedDocs[startUrl]; const table = await this.getOrCreateLanceTable({ initializationVector: vector, - embeddingsProvider, + isPreIndexedDoc, }); let docs: LanceDbDocsRow[] = []; @@ -719,8 +718,11 @@ export default class DocsService { } private async getLanceTableNameFromEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, + isPreIndexedDoc: boolean, ) { + const embeddingsProvider = + await this.getEmbeddingsProvider(isPreIndexedDoc); + const tableName = this.sanitizeLanceTableName( `${DocsService.lanceTableName}${embeddingsProvider.id}`, ); @@ -730,15 +732,15 @@ export default class DocsService { private async getOrCreateLanceTable({ initializationVector, - embeddingsProvider, + isPreIndexedDoc, }: { initializationVector: number[]; - embeddingsProvider: EmbeddingsProvider; + isPreIndexedDoc?: boolean; }) { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const tableNameFromEmbeddingsProvider = - await this.getLanceTableNameFromEmbeddingsProvider(embeddingsProvider); + await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -770,11 +772,9 @@ export default class DocsService { }: AddParams) { const sampleVector = embeddings[0]; const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); const table = await this.getOrCreateLanceTable({ - embeddingsProvider, + isPreIndexedDoc, initializationVector: sampleVector, }); From 441b489fcbcee0c5d81db0393d7ebb242f413e7f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 03:11:16 -0800 Subject: [PATCH 12/21] init with status updates --- core/indexing/docs/DocsService.ts | 263 ++++++++++++++++-------------- 1 file changed, 142 insertions(+), 121 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index ee7520eb5..801796363 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -134,6 +134,16 @@ export default class DocsService { this.reindexDoc, ); const config = await configHandler.loadConfig(); + this.config = config; + + // On first go we want to have an indexing status for all docs + // Since config handler will only trigger indexing status updates on changes + if (config.docs?.length) { + for (const doc of config.docs) { + await this.indexAndAdd(doc); + } + } + await this.handleConfigUpdate({ config }); configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } @@ -335,146 +345,157 @@ export default class DocsService { // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - - this.updateIndexingStatus({ - ...fixedStatus, - status: "indexing", - description: "Finding subpages", - progress: 0, - }); - - const articles: Article[] = []; - let processedPages = 0; - let maxKnownPages = 1; - - // Crawl pages and retrieve info as articles - for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - processedPages++; - - const article = pageToArticle(page); - - if (!article) { - continue; - } - - articles.push(article); - - // Use a heuristic approach for progress calculation - const progress = Math.min(processedPages / maxKnownPages, 1); - - this.updateIndexingStatus({ - ...fixedStatus, - description: `Finding subpages (${page.path})`, - status: "indexing", - progress, // Yield the heuristic progress - }); - - // Increase maxKnownPages to delay progress reaching 100% too soon - if (processedPages === maxKnownPages) { - maxKnownPages *= 2; - } - - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - void Telemetry.capture("docs_pages_crawled", { - count: processedPages, - }); - - const chunks: Chunk[] = []; - const embeddings: number[][] = []; - - // Create embeddings of retrieved articles - console.debug(`Creating embeddings for ${articles.length} articles`); - - for (let i = 0; i < articles.length; i++) { - const article = articles[i]; + try { this.updateIndexingStatus({ ...fixedStatus, status: "indexing", - description: `Creating Embeddings: ${article.subpath}`, - progress: i / articles.length, + description: "Finding subpages", + progress: 0, }); - try { - const chunkedArticle = chunkArticle( - article, - embeddingsProvider.maxChunkSize, - ); + const articles: Article[] = []; + let processedPages = 0; + let maxKnownPages = 1; - const chunkedArticleContents = chunkedArticle.map( - (chunk) => chunk.content, - ); + // Crawl pages and retrieve info as articles + for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { + processedPages++; - chunks.push(...chunkedArticle); + const article = pageToArticle(page); - const subpathEmbeddings = await embeddingsProvider.embed( - chunkedArticleContents, - ); + if (!article) { + continue; + } - embeddings.push(...subpathEmbeddings); - } catch (e) { - console.warn("Error chunking article: ", e); + articles.push(article); + + // Use a heuristic approach for progress calculation + const progress = Math.min(processedPages / maxKnownPages, 1); + + this.updateIndexingStatus({ + ...fixedStatus, + description: `Finding subpages (${page.path})`, + status: "indexing", + progress, // Yield the heuristic progress + }); + + // Increase maxKnownPages to delay progress reaching 100% too soon + if (processedPages === maxKnownPages) { + maxKnownPages *= 2; + } + + await new Promise((resolve) => setTimeout(resolve, 50)); } - } - if (embeddings.length === 0) { - console.error( - `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, - ); + void Telemetry.capture("docs_pages_crawled", { + count: processedPages, + }); + const chunks: Chunk[] = []; + const embeddings: number[][] = []; + + // Create embeddings of retrieved articles + console.debug(`Creating embeddings for ${articles.length} articles`); + + for (let i = 0; i < articles.length; i++) { + const article = articles[i]; + this.updateIndexingStatus({ + ...fixedStatus, + status: "indexing", + description: `Creating Embeddings: ${article.subpath}`, + progress: i / articles.length, + }); + + try { + const chunkedArticle = chunkArticle( + article, + embeddingsProvider.maxChunkSize, + ); + + const chunkedArticleContents = chunkedArticle.map( + (chunk) => chunk.content, + ); + + chunks.push(...chunkedArticle); + + const subpathEmbeddings = await embeddingsProvider.embed( + chunkedArticleContents, + ); + + embeddings.push(...subpathEmbeddings); + } catch (e) { + console.warn("Error chunking article: ", e); + } + } + + if (embeddings.length === 0) { + console.error( + `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, + ); + + this.updateIndexingStatus({ + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + status: "failed", + progress: 1, + }); + + void this.ide.showToast("info", `Failed to index ${startUrl}`); + + this.docsIndexingQueue.delete(startUrl); + + return; + } + + // Add docs to databases + console.log(`Adding ${embeddings.length} embeddings to db`); + + this.updateIndexingStatus({ + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + progress: 0.5, + }); + + // Delete indexed docs if re-indexing + if (reIndex && (await this.hasMetadata(startUrl.toString()))) { + console.log("Deleting old embeddings"); + await this.delete(startUrl); + } + + const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + + await this.add({ + siteIndexingConfig, + chunks, + embeddings, + favicon, + }); + + this.docsIndexingQueue.delete(startUrl); + + this.updateIndexingStatus({ + ...fixedStatus, + description: "Complete", + status: "complete", + progress: 1, + }); + + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } catch (e) { + console.error("Error indexing docs", e); this.updateIndexingStatus({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", progress: 1, }); - - void this.ide.showToast("info", `Failed to index ${startUrl}`); - + } finally { this.docsIndexingQueue.delete(startUrl); - - return; - } - - // Add docs to databases - console.log(`Adding ${embeddings.length} embeddings to db`); - - this.updateIndexingStatus({ - ...fixedStatus, - description: `Adding ${embeddings.length} embeddings to db`, - status: "indexing", - progress: 0.5, - }); - - // Delete indexed docs if re-indexing - if (reIndex && (await this.hasMetadata(startUrl.toString()))) { - console.log("Deleting old embeddings"); - await this.delete(startUrl); - } - - const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); - - await this.add({ - siteIndexingConfig, - chunks, - embeddings, - favicon, - }); - - this.docsIndexingQueue.delete(startUrl); - - this.updateIndexingStatus({ - ...fixedStatus, - description: "Complete", - status: "complete", - progress: 1, - }); - - void this.ide.showToast("info", `Successfully indexed ${startUrl}`); - - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); } } From f52fbca1d5e09982db1a5040ebd928af7730a92c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 20:29:19 -0800 Subject: [PATCH 13/21] docs indexing on more --- core/core.ts | 47 +-- core/index.d.ts | 24 +- core/indexing/IndexingStatusManager.ts | 93 ----- core/indexing/docs/DocsService.ts | 328 +++++++++++------- core/protocol/core.ts | 11 +- core/protocol/passThrough.ts | 2 +- core/protocol/webview.ts | 4 +- extensions/vscode/config_schema.json | 2 +- gui/src/components/Footer.tsx | 71 ++-- .../indexing/FooterIndexingPeeks.tsx | 80 +++++ .../components/indexing/IndexingStatus.tsx | 135 +++++++ .../components/indexing/IndexingStatuses.tsx | 50 +++ gui/src/components/indexing/utils.ts | 17 + gui/src/hooks/useSetup.ts | 21 +- gui/src/index.css | 19 + gui/src/pages/More/More.tsx | 4 + gui/src/redux/slices/stateSlice.ts | 16 +- 17 files changed, 620 insertions(+), 304 deletions(-) delete mode 100644 core/indexing/IndexingStatusManager.ts create mode 100644 gui/src/components/indexing/FooterIndexingPeeks.tsx create mode 100644 gui/src/components/indexing/IndexingStatus.tsx create mode 100644 gui/src/components/indexing/IndexingStatuses.tsx create mode 100644 gui/src/components/indexing/utils.ts diff --git a/core/core.ts b/core/core.ts index ab71ab4d7..823607814 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,7 +35,6 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; -import { IndexingStatusManager } from "./indexing/IndexingStatusManager"; export class Core { // implements IMessenger @@ -45,7 +44,6 @@ export class Core { continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; controlPlaneClient: ControlPlaneClient; - private indexingManager: IndexingStatusManager; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -110,15 +108,10 @@ export class Core { this.controlPlaneClient, ); - this.indexingManager = IndexingStatusManager.createSingleton( - this.messenger, - ); - this.docsService = DocsService.createSingleton( this.configHandler, this.ide, this.messenger, - this.indexingManager, ); this.configHandler.onConfigUpdate( @@ -292,7 +285,7 @@ export class Core { }); on("context/indexDocs", async (msg) => { - await this.docsService.indexAllDocsWithPrompt(msg.data.reIndex); + await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -671,6 +664,8 @@ export class Core { const rows = await DevDataSqliteDb.getTokensPerModel(); return rows; }); + + // Codebase indexing on("index/forceReIndex", async ({ data }) => { if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; @@ -700,6 +695,27 @@ export class Core { } }); + // Docs, etc. indexing + on("indexing/reindex", async (msg) => { + if (msg.data.type === "docs") { + void this.docsService.reindexDoc(msg.data.id); + } + }); + on("indexing/abort", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.abort(msg.data.id); + } + }); + on("indexing/setPaused", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.setPaused(msg.data.id, msg.data.paused); + } + }); + on("indexing/initStatuses", async (msg) => { + return this.docsService.initStatuses(); + }); + // + on("didChangeSelectedProfile", (msg) => { void this.configHandler.setSelectedProfile(msg.data.id); void this.configHandler.reloadConfig(); @@ -720,19 +736,6 @@ export class Core { recentlyEditedFilesCache.set(filepath, filepath); } }); - - on("indexing/reindex", async (msg) => { - this.indexingManager.reindex(msg.data.identifier); - }); - on("indexing/abort", async (msg) => { - this.indexingManager.abort(msg.data.identifier); - }); - on("indexing/setPaused", async (msg) => { - this.indexingManager.setPaused(msg.data.identifier, msg.data.pause); - }); - on("indexing/getStatuses", async (msg) => { - return this.indexingManager.statuses; - }); } private indexingCancellationController: AbortController | undefined; @@ -803,7 +806,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { void this.sendIndexingErrorTelemetry(update); diff --git a/core/index.d.ts b/core/index.d.ts index 53ca6ae42..32685b79a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -46,26 +46,28 @@ export interface IndexingProgressUpdate { } // This is more or less a V2 of IndexingProgressUpdate -export interface IndexingStatusUpdate { +export interface IndexingStatus { id: string; type: "docs"; progress: number; description: string; - status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "deleted"; + status: + | "indexing" + | "complete" + | "paused" + | "failed" + | "aborted" + | "deleted" + | "pending"; embeddingsProviderId: string; isReindexing?: boolean; debugInfo?: string; + title: string; + icon?: string; + url?: string; } -interface IndexIdentifier { - type: string; - id: string; -} - -export type IndexingStatusMap = Map< - string, - Map ->; +export type IndexingStatusMap = Map; export type PromptTemplateFunction = ( history: ChatMessage[], diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts deleted file mode 100644 index 785f14b95..000000000 --- a/core/indexing/IndexingStatusManager.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { IndexIdentifier, IndexingStatusMap, IndexingStatusUpdate } from ".."; -import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; -import { IMessenger } from "../util/messenger"; - -/* - Any service that sends indexing updates can use an instance of this class - 1. Pass indexingManager to the service - 2. Register the service with the manager using `registerService` - E.g. docs uses startUrl as id - 3. Rules of engagement: - - service is responsible for checking corrupted indexes - don't check paused or deleted -*/ -export class IndexingStatusManager { - private readonly messenger: IMessenger; - readonly statuses: IndexingStatusMap = new Map(); - private readonly reindexTypeFunctions: Map< - string, - (id: string) => Promise - > = new Map(); - - constructor(messenger: IMessenger) { - this.messenger = messenger; - } - - private static instance?: IndexingStatusManager; - static createSingleton( - messenger: IMessenger, - ) { - const instance = new IndexingStatusManager(messenger); - IndexingStatusManager.instance = instance; - return instance; - } - - static getSingleton() { - return IndexingStatusManager.instance; - } - - // Services that use an instance of this class should add their reindex functions here - registerService(type: string, fn: (id: string) => Promise) { - this.reindexTypeFunctions.set(type, fn); - this.statuses.set(type, new Map()); - } - - reindex({ type, id }: IndexIdentifier) { - const reindexFn = this.reindexTypeFunctions.get(type); - if (reindexFn) { - void reindexFn(id); - } - } - - handleUpdate(status: IndexingStatusUpdate) { - const byType = this.statuses.get(status.type); - if (byType) { - byType.set(status.id, status); - this.messenger.send("indexing/statusUpdate", status); - } - } - - delete({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - this.handleUpdate({ ...status, status: "deleted" }); - } - } - - abort({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - this.handleUpdate({ ...status, status: "aborted" }); - } - } - - isAborted({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - return status.status === "aborted"; - } - } - - setPaused({ type, id }: IndexIdentifier, pause: boolean) { - const status = this.statuses.get(type)?.get(id); - if (status) { - this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); - } - } - - isPaused({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - return status.status === "paused"; - } - } -} diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 25f465be4..7c163667b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,7 +7,8 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingStatusUpdate, + IndexingStatusMap, + IndexingStatus, SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; @@ -24,7 +25,6 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; -import { IndexingStatusManager } from "../IndexingStatusManager"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; @@ -100,7 +100,6 @@ export default class DocsService { configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, - private readonly indexingManager?: IndexingStatusManager, ) { this.isInitialized = this.init(configHandler); } @@ -111,14 +110,8 @@ export default class DocsService { configHandler: ConfigHandler, ide: IDE, messenger?: IMessenger, - indexingManager?: IndexingStatusManager, ) { - const docsService = new DocsService( - configHandler, - ide, - messenger, - indexingManager, - ); + const docsService = new DocsService(configHandler, ide, messenger); DocsService.instance = docsService; return docsService; } @@ -129,26 +122,46 @@ export default class DocsService { // Initialization - load config and attach config listener private async init(configHandler: ConfigHandler) { - this.indexingManager?.registerService( - DocsService.indexingType, - this.reindexDoc, - ); const config = await configHandler.loadConfig(); - this.config = config; - - // On first go we want to have an indexing status for all docs - // Since config handler will only trigger indexing status updates on changes - if (config.docs?.length) { - for (const doc of config.docs) { - await this.indexAndAdd(doc); - } - } - await this.handleConfigUpdate({ config }); configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } - // Config + readonly statuses: IndexingStatusMap = new Map(); + + handleStatusUpdate(update: IndexingStatus) { + this.statuses.set(update.id, update); + this.messenger?.send("indexing/statusUpdate", update); + } + + abort(startUrl: string) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: "aborted", + }); + } + } + + isAborted(startUrl: string) { + return this.statuses.get(startUrl)?.status === "aborted"; + } + + // Pausing not supported for docs yet + // setPaused(startUrl: string, pause: boolean) { + // const status = this.statuses.get(startUrl); + // if (status) { + // this.handleStatusUpdate({ + // ...status, + // status: pause ? "paused" : "indexing", + // }); + // } + // } + + // isPaused(startUrl: string) { + // return this.statuses.get(startUrl)?.status === "paused"; + // } /* * Currently, we generate and host embeddings for pre-indexed docs using transformers. @@ -183,8 +196,6 @@ export default class DocsService { return this.config.embeddingsProvider; } - // Expose this so that docs provider can check it - private async handleConfigUpdate({ config: newConfig, }: { @@ -203,27 +214,49 @@ export default class DocsService { return; } - // On embeddings provider change, reindex all non-preindexed docs - // change = doesn't match last successful embeddings provider - const curEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - if ( - !curEmbeddingsProviderId || - curEmbeddingsProviderId !== newConfig.embeddingsProvider.id - ) { - // If not set, we're initializing - const currentDocs = await this.listMetadata(); - if (currentDocs.length > 0) { - await this.reindexDocsOnNewEmbeddingsProvider(); - return; - } - } - - await this.syncDocsOnConfigUpdate(oldConfig, newConfig); + await this.syncOrReindexAllDocs(newConfig, oldConfig); } } + private async syncOrReindexAllDocs( + newConfig: ContinueConfig, + oldConfig?: ContinueConfig, + ) { + // On embeddings provider change, reindex all non-preindexed docs + // change = doesn't match last successful embeddings provider + const curEmbeddingsProviderId = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if ( + !curEmbeddingsProviderId || + curEmbeddingsProviderId !== newConfig.embeddingsProvider.id + ) { + // If not set, we're initializing + const currentDocs = await this.listMetadata(); + if (currentDocs.length > 0) { + await this.reindexDocsOnNewEmbeddingsProvider(); + return; + } + } + + await this.syncDocsOnConfigUpdate(oldConfig, newConfig); + } + + async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) { + if (!this.hasDocsContextProvider()) { + const didAddDocsContextProvider = + await this.showAddDocsContextProviderToast(); + + if (!didAddDocsContextProvider) { + return; + } + } + + await this.syncOrReindexAllDocs(this.config); + + void this.ide.showToast("info", "Docs indexing completed"); + } + async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( @@ -234,16 +267,6 @@ export default class DocsService { return !!title; } - // private async hasIndexedDoc(startUrl: string) { - // const db = await this.getOrCreateSqliteDb(); - // const docs = await db.all( - // `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - // startUrl, - // ); - - // return docs.length > 0; - // } - async showAddDocsContextProviderToast() { const actionMsg = "Add 'docs' context provider"; const res = await this.ide.showToast( @@ -267,25 +290,6 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocsWithPrompt(reIndex: boolean = false) { - if (!this.hasDocsContextProvider()) { - const didAddDocsContextProvider = - await this.showAddDocsContextProviderToast(); - - if (!didAddDocsContextProvider) { - return; - } - } - - const docs = await this.listMetadata(); - - for (const doc of docs) { - await this.indexAndAdd(doc, reIndex); - } - - void this.ide.showToast("info", "Docs indexing completed"); - } - async listMetadata() { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( @@ -295,10 +299,6 @@ export default class DocsService { return docs; } - updateIndexingStatus(update: IndexingStatusUpdate) { - this.indexingManager?.handleUpdate(update); - } - async reindexDoc(startUrl: string) { const docConfig = this.config.docs?.find( (doc) => doc.startUrl === startUrl, @@ -323,36 +323,53 @@ export default class DocsService { const indexExists = await this.hasMetadata(startUrl); const fixedStatus: Pick< - IndexingStatusUpdate, - "type" | "id" | "embeddingsProviderId" | "isReindexing" + IndexingStatus, + | "type" + | "id" + | "embeddingsProviderId" + | "isReindexing" + | "debugInfo" + | "icon" + | "url" + | "title" > = { type: "docs", id: siteIndexingConfig.startUrl, embeddingsProviderId: embeddingsProvider.id, isReindexing: reIndex && indexExists, + title: siteIndexingConfig.title, + debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, + icon: siteIndexingConfig.faviconUrl, + url: siteIndexingConfig.startUrl, }; - if (indexExists && !reIndex) { - this.updateIndexingStatus({ - ...fixedStatus, - progress: 1, - description: "Complete", - status: "complete", - debugInfo: "Already indexed", - }); - return; + if (indexExists) { + if (reIndex) { + await this.deleteIndexes(startUrl); + } else { + this.handleStatusUpdate({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + debugInfo: "Already indexed", + }); + return; + } } // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); try { - this.updateIndexingStatus({ + this.handleStatusUpdate({ ...fixedStatus, status: "indexing", description: "Finding subpages", progress: 0, }); + // NOTE - during "indexing" phase, check if aborted before each status update + const articles: Article[] = []; let processedPages = 0; let maxKnownPages = 1; @@ -372,7 +389,10 @@ export default class DocsService { // Use a heuristic approach for progress calculation const progress = Math.min(processedPages / maxKnownPages, 1); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", @@ -399,7 +419,11 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - this.updateIndexingStatus({ + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, @@ -433,7 +457,10 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", @@ -450,21 +477,34 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, - description: `Adding ${embeddings.length} embeddings to db`, + description: "Deleting old embeddings from the db", status: "indexing", progress: 0.5, }); // Delete indexed docs if re-indexing - if (reIndex && (await this.hasMetadata(startUrl.toString()))) { + if (reIndex && indexExists) { console.log("Deleting old embeddings"); - await this.delete(startUrl); + await this.deleteIndexes(startUrl); } const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + progress: 0.5, + }); + await this.add({ siteIndexingConfig, chunks, @@ -474,7 +514,10 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, description: "Complete", status: "complete", @@ -488,7 +531,7 @@ export default class DocsService { } } catch (e) { console.error("Error indexing docs", e); - this.updateIndexingStatus({ + this.handleStatusUpdate({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", @@ -499,6 +542,31 @@ export default class DocsService { } } + // Function for GUI to retrieve initial pending statuses + // And kickoff indexing where needed + async initStatuses() { + this.config?.docs?.forEach(async (doc) => { + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + this.handleStatusUpdate(currentStatus); + } else { + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + progress: 0, + description: "Pending", + status: "pending", + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }); + } + }); + } + // Retrieve docs embeds based on user input async retrieveChunksFromQuery( query: string, @@ -638,10 +706,6 @@ export default class DocsService { const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // const newDocs = newConfigDocs.filter( - // (doc) => !currentStartUrls.includes(doc.startUrl), - // ); - // Anything found in sqlite but not in new config should be deleted const deletedDocs = currentlyIndexedDocs.filter( (doc) => @@ -668,13 +732,30 @@ export default class DocsService { oldConfigDoc.faviconUrl !== doc.faviconUrl) ) { changedDocs.push(doc); + } else { + // if get's here, not changed, no update needed, mark as complete + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + title: doc.title, + debugInfo: "Config sync: not changed", + icon: doc.faviconUrl, + url: doc.startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); } - // if get's here, not changed, no update needed } else { newDocs.push(doc); } } + // Sends "Pending" or current status for each + await this.initStatuses(); + for (const doc of changedDocs) { console.log(`Updating indexed doc: ${doc.startUrl}`); await this.indexAndAdd(doc, true); @@ -688,7 +769,7 @@ export default class DocsService { } for (const doc of deletedDocs) { - await this.delete(doc.startUrl); + await this.deleteIndexes(doc.startUrl); } } catch (e) { console.error("Error syncing docs index on config update", e); @@ -852,7 +933,7 @@ export default class DocsService { } } - // Delete methods for individual docs + // Delete methods private async deleteEmbeddingsFromLance(startUrl: string) { for (const tableName of this.lanceTableNamesSet) { const conn = await lancedb.connect(getLanceDbPath()); @@ -870,20 +951,31 @@ export default class DocsService { } private deleteFromConfig(startUrl: string) { - editConfigJson((config) => ({ - ...config, - docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], - })); + const doesDocExist = this.config.docs?.some( + (doc) => doc.startUrl === startUrl, + ); + if (doesDocExist) { + editConfigJson((config) => ({ + ...config, + docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], + })); + } + } + + async deleteIndexes(startUrl: string) { + await this.deleteEmbeddingsFromLance(startUrl); + await this.deleteMetadataFromSqlite(startUrl); } async delete(startUrl: string) { - await this.deleteEmbeddingsFromLance(startUrl); - await this.deleteMetadataFromSqlite(startUrl); + await this.deleteIndexes(startUrl); this.deleteFromConfig(startUrl); - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ ...status, status: "deleted" }); } + this.messenger?.send("refreshSubmenuItems", undefined); } // When user requests a pre-indexed doc for the first time @@ -934,13 +1026,9 @@ export default class DocsService { console.log( `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); - + await this.initStatuses(); for (const doc of docs) { - await this.delete(doc.startUrl); - } - - for (const doc of docs) { - await this.indexAndAdd(doc); + await this.indexAndAdd(doc, true); } // Important that this only is invoked after we have successfully diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 65a798c55..f6c849963 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,7 +8,6 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, - IndexIdentifier, IndexingStatusMap, LLMFullCompletionOptions, MessageContent, @@ -160,11 +159,11 @@ export type ToCoreFromIdeOrWebviewProtocol = { void, ]; - // Docs Indexing. TODO move codebase to this - "indexing/reindex": [{ identifier: IndexIdentifier }, void]; - "indexing/abort": [{ identifier: IndexIdentifier }, void]; - "indexing/setPaused": [{ identifier: IndexIdentifier; pause: boolean }, void]; - "indexing/getStatuses": [undefined, IndexingStatusMap]; + // Docs etc. Indexing. TODO move codebase to this + "indexing/reindex": [{ type: string; id: string }, void]; + "indexing/abort": [{ type: string; id: string }, void]; + "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; + "indexing/initStatuses": [undefined, void]; addAutocompleteModel: [{ model: ModelDescription }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1997b8700..71e35fe65 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -45,7 +45,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "index/forceReIndexFiles", "index/indexingProgressBarInitialized", // Docs, etc. - "indexing/getStatuses", + "indexing/initStatuses", "indexing/reindex", "indexing/abort", "indexing/setPaused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index e5330d81f..d259fde9e 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -3,7 +3,7 @@ import { ConfigValidationError } from "../config/validation.js"; import type { ContextItemWithId, IndexingProgressUpdate, - IndexingStatusUpdate, + IndexingStatus, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -11,7 +11,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; // Codebase - "indexing/statusUpdate": [IndexingStatusUpdate, void]; // Docs, etc. + "indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc. refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index eb75d1f90..76d27bec2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2325,7 +2325,7 @@ "type": "integer", "description": "The maximum depth to crawl the documentation site" }, - "favicon": { + "faviconUrl": { "type": "string", "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index 0c094155c..bf51abc0f 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -14,6 +14,7 @@ import { ROUTES } from "../util/navigation"; import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; import ProfileSwitcher from "./ProfileSwitcher"; +import FooterIndexingPeeks from "./indexing/FooterIndexingPeeks"; function Footer() { const navigate = useNavigate(); @@ -47,45 +48,49 @@ function Footer() { } return ( -
-
- - {defaultModel?.provider === "free-trial" && ( - - )} -
+ <> + + +
+
+ + {defaultModel?.provider === "free-trial" && ( + + )} +
+ +
+ {configError && ( + + + + )} -
- {configError && ( - + - )} - - - - - - - -
-
+ + + + +
+ ); } diff --git a/gui/src/components/indexing/FooterIndexingPeeks.tsx b/gui/src/components/indexing/FooterIndexingPeeks.tsx new file mode 100644 index 000000000..c95e8db7d --- /dev/null +++ b/gui/src/components/indexing/FooterIndexingPeeks.tsx @@ -0,0 +1,80 @@ +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; + +import { IndexingStatus } from "core"; +import { useContext, useMemo } from "react"; +import { STATUS_TO_ICON } from "./utils"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +interface IndexingStatusViewerProps { + status: IndexingStatus; +} + +function FooterIndexingPeek({ status }: IndexingStatusViewerProps) { + const ideMessenger = useContext(IdeMessengerContext); + + const progressPercentage = useMemo(() => { + return Math.min(100, Math.max(0, status.progress * 100)); + }, [status.progress]); + + const Icon = STATUS_TO_ICON[status.status]; + + return ( +
+
{ + if (status.url) { + ideMessenger.post("openUrl", status.url); + } + }} + > + {status.icon ? ( + doc icon + ) : null} +

+ {status.title ?? status.id} +

+
+
+
+
+
+ {progressPercentage.toFixed(0)}% + {Icon ? ( + + ) : null} +
+
+ ); +} + +function FooterIndexingPeeks() { + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexingStatuses, + ); + const currentlyIndexingDocs = useMemo(() => { + return Object.values(indexingStatuses).filter( + (status) => status.status === "indexing", + ); + }, [indexingStatuses]); + + return ( + <> + {currentlyIndexingDocs.map((status) => { + return ; + })} + + ); +} + +export default FooterIndexingPeeks; diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/IndexingStatus.tsx new file mode 100644 index 000000000..eb53fd794 --- /dev/null +++ b/gui/src/components/indexing/IndexingStatus.tsx @@ -0,0 +1,135 @@ +import { IndexingStatus } from "core"; +import { PropsWithChildren, useContext, useMemo } from "react"; +import { useDispatch } from "react-redux"; +import { usePostHog } from "posthog-js/react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { + ArrowPathIcon, + CheckCircleIcon, + PauseCircleIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; + +interface IndexingStatusViewerProps { + status: IndexingStatus; +} + +const STATUS_TO_ICON: Record = { + indexing: ArrowPathIcon, + paused: PauseCircleIcon, + complete: CheckCircleIcon, + aborted: null, + deleted: null, + pending: null, + failed: XMarkIcon, // Since we show an erorr message below +}; + +function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { + const ideMessenger = useContext(IdeMessengerContext); + const posthog = usePostHog(); + + const reIndex = () => + ideMessenger.post("indexing/reindex", { + type: status.type, + id: status.id, + }); + + const abort = () => + ideMessenger.post("indexing/abort", { + type: status.type, + id: status.id, + }); + + const progressPercentage = useMemo(() => { + return Math.min(100, Math.max(0, status.progress * 100)); + }, [status.progress]); + + const Icon = STATUS_TO_ICON[status.status]; + + return ( +
+ {/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */} +
+
{ + if (status.url) { + ideMessenger.post("openUrl", status.url); + } + }} + > + {status.icon ? ( + doc icon + ) : null} +

+ {status.title ?? status.id} +

+
+ {status.status === "pending" ? ( +
Pending...
+ ) : ( +
+ {progressPercentage.toFixed(0)}% + {Icon ? ( + + ) : null} +
+ )} +
+ +
+
+
+ +
+ {}, + deleted: () => {}, + pending: () => {}, + }[status.status] + } + > + { + { + complete: "Click to re-index", + indexing: "Cancel indexing", + failed: "Click to retry", + aborted: "Click to index", + paused: "", + deleted: "", + pending: "", + }[status.status] + } + + + {status.status === "indexing" && ( + + {status.description} + + )} +
+
+ ); +} + +export default IndexingStatusViewer; diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx new file mode 100644 index 000000000..bd7a61f44 --- /dev/null +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -0,0 +1,50 @@ +import { useMemo } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "./IndexingStatus"; +import { Button } from ".."; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import AddDocsDialog from "../dialogs/AddDocsDialog"; + +function IndexingStatuses() { + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexingStatuses, + ); + const docsStatuses = useMemo(() => { + const docs = Object.values(indexingStatuses).filter( + (status) => status.type === "docs" && status.status !== "deleted", + ); + + return []; + return docs; + }, [indexingStatuses]); + const dispatch = useDispatch(); + + return ( +
+

@docs indexes

+ + Manage your documentation sources + + {docsStatuses.length ? ( + docsStatuses.map((status) => { + return ; + }) + ) : ( + + )} +
+ ); +} + +export default IndexingStatuses; diff --git a/gui/src/components/indexing/utils.ts b/gui/src/components/indexing/utils.ts new file mode 100644 index 000000000..350f5008e --- /dev/null +++ b/gui/src/components/indexing/utils.ts @@ -0,0 +1,17 @@ +import { + ArrowPathIcon, + CheckCircleIcon, + PauseCircleIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { IndexingStatus } from "core"; + +export const STATUS_TO_ICON: Record = { + indexing: ArrowPathIcon, + paused: PauseCircleIcon, + complete: CheckCircleIcon, + aborted: null, + deleted: null, + pending: null, + failed: null, // XMarkIcon, // Since we show an error message below +}; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 49a6d429f..4bdfdd8bf 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -11,6 +11,7 @@ import { setInactive, setSelectedProfileId, setTTSActive, + updateIndexingStatus, } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; @@ -50,14 +51,20 @@ function useSetup(dispatch: Dispatch) { loadConfig(); const interval = setInterval(() => { if (initialConfigLoad.current) { + // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); + ideMessenger.post("indexing/initStatuses", undefined); return; } loadConfig(); }, 2_000); return () => clearInterval(interval); - }, [initialConfigLoad, loadConfig]); + }, [initialConfigLoad, loadConfig, ideMessenger]); + + useWebviewListener("configUpdate", async () => { + await loadConfig(); + }); useEffect(() => { // Override persisted state @@ -110,10 +117,6 @@ function useSetup(dispatch: Dispatch) { }); }); - useWebviewListener("configUpdate", async () => { - await loadConfig(); - }); - useWebviewListener("configError", async (error) => { dispatch(setConfigError(error)); }); @@ -136,13 +139,7 @@ function useSetup(dispatch: Dispatch) { }); useWebviewListener("indexing/statusUpdate", async (data) => { - console.log("Indexing status update", data); - // dispatch( - // addContextItemsAtIndex({ - // index: data.historyIndex, - // contextItems: [data.item], - // }), - // ); + dispatch(updateIndexingStatus(data)); }); useWebviewListener( diff --git a/gui/src/index.css b/gui/src/index.css index b1cde096f..554ce2faa 100644 --- a/gui/src/index.css +++ b/gui/src/index.css @@ -72,3 +72,22 @@ a:focus { -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ } + +.lines { + /* white-space: pre-wrap; */ + word-break: break-word; + overflow: hidden; + line-height: 1.375; +} + +.lines-3 { + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; +} + +.lines-1 { + display: -webkit-box; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; +} diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 4824c9535..e743a3834 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -15,6 +15,7 @@ import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; import IndexingProgress from "./IndexingProgress"; +import IndexingStatuses from "../../components/indexing/IndexingStatuses"; function MorePage() { useNavigationListener(); @@ -50,6 +51,9 @@ function MorePage() {
+
+ +

Help center

diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 4222b4693..fa85427e5 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -3,17 +3,15 @@ import { JSONContent } from "@tiptap/react"; import { ChatHistoryItem, ChatMessage, - ContextItemId, ContextItemWithId, + IndexingStatus, PersistedSessionInfo, PromptLog, } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; -import { RootState } from "../store"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -34,6 +32,7 @@ type State = { selectedProfileId: string; configError: ConfigValidationError[] | undefined; isInMultifileEdit: boolean; + indexingStatuses: { [id: string]: IndexingStatus }; }; const initialState: State = { @@ -61,6 +60,7 @@ const initialState: State = { defaultModelTitle: "GPT-4", selectedProfileId: "local", isInMultifileEdit: false, + indexingStatuses: {}, }; export const stateSlice = createSlice({ @@ -314,6 +314,15 @@ export const stateSlice = createSlice({ setIsInMultifileEdit: (state, action: PayloadAction) => { state.isInMultifileEdit = action.payload; }, + updateIndexingStatus: (state, action: PayloadAction) => { + console.log("update indexing status"); + state.indexingStatuses = { + ...state.indexingStatuses, + [action.payload.id]: action.payload, + }; + // consider only overwriting the one that changed + // depends on how watching + }, }, }); @@ -339,6 +348,7 @@ export const { deleteMessage, setIsGatheringContext, setIsInMultifileEdit, + updateIndexingStatus, } = stateSlice.actions; export default stateSlice.reducer; From 8e4c56ebea9e45a24ae3dcd85cfc0561289fadc6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 21:52:02 -0800 Subject: [PATCH 14/21] chat peeks --- core/indexing/docs/DocsService.ts | 57 +++++++-------- gui/src/components/Footer.tsx | 71 +++++++++---------- ...ndexingPeeks.tsx => ChatIndexingPeeks.tsx} | 49 +++++++++---- .../components/indexing/IndexingStatus.tsx | 9 ++- .../components/indexing/IndexingStatuses.tsx | 1 - gui/src/pages/gui/Chat.tsx | 2 + 6 files changed, 107 insertions(+), 82 deletions(-) rename gui/src/components/indexing/{FooterIndexingPeeks.tsx => ChatIndexingPeeks.tsx} (58%) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 7c163667b..cc75c3835 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -37,6 +37,12 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +// Progress heuristic values +// subpages -> embeddings -> delete from db -> add to db +const PROGRESS_AT_EMBEDDING = 0.5; +const PROGRESS_AT_DELETE_OPERATIONS = 0.7; +const PROGRESS_AT_ADD_OPERATIONS = 0.8; + // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -140,6 +146,8 @@ export default class DocsService { this.handleStatusUpdate({ ...status, status: "aborted", + progress: 0, + description: "Canceled", }); } } @@ -148,20 +156,20 @@ export default class DocsService { return this.statuses.get(startUrl)?.status === "aborted"; } - // Pausing not supported for docs yet - // setPaused(startUrl: string, pause: boolean) { - // const status = this.statuses.get(startUrl); - // if (status) { - // this.handleStatusUpdate({ - // ...status, - // status: pause ? "paused" : "indexing", - // }); - // } - // } + // NOTE Pausing not supported for docs yet + setPaused(startUrl: string, pause: boolean) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: pause ? "paused" : "indexing", + }); + } + } - // isPaused(startUrl: string) { - // return this.statuses.get(startUrl)?.status === "paused"; - // } + isPaused(startUrl: string) { + return this.statuses.get(startUrl)?.status === "paused"; + } /* * Currently, we generate and host embeddings for pre-indexed docs using transformers. @@ -372,11 +380,11 @@ export default class DocsService { const articles: Article[] = []; let processedPages = 0; - let maxKnownPages = 1; + let estimatedProgress = 0; // progress heuristic = sum series 1/(3*2^n) from n=0 to pages. Alternative e.g. sum 1/(2^n) // Crawl pages and retrieve info as articles for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - processedPages++; + estimatedProgress += 1 / (3 * 2 ** processedPages); const article = pageToArticle(page); @@ -386,9 +394,6 @@ export default class DocsService { articles.push(article); - // Use a heuristic approach for progress calculation - const progress = Math.min(processedPages / maxKnownPages, 1); - if (this.isAborted(startUrl)) { return; } @@ -396,15 +401,11 @@ export default class DocsService { ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", - progress, // Yield the heuristic progress + progress: 0.4 * estimatedProgress, // 0% -> 40%, a heuristic approach for progress calculation }); - // Increase maxKnownPages to delay progress reaching 100% too soon - if (processedPages === maxKnownPages) { - maxKnownPages *= 2; - } - - await new Promise((resolve) => setTimeout(resolve, 50)); + processedPages++; + await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping } void Telemetry.capture("docs_pages_crawled", { @@ -427,7 +428,7 @@ export default class DocsService { ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, - progress: i / articles.length, + progress: 0.4 + 0.4 * (i / articles.length), // 40% -> 80% }); try { @@ -484,7 +485,7 @@ export default class DocsService { ...fixedStatus, description: "Deleting old embeddings from the db", status: "indexing", - progress: 0.5, + progress: 0.8, }); // Delete indexed docs if re-indexing @@ -502,7 +503,7 @@ export default class DocsService { ...fixedStatus, description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", - progress: 0.5, + progress: 0.85, }); await this.add({ diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index bf51abc0f..0c094155c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -14,7 +14,6 @@ import { ROUTES } from "../util/navigation"; import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; import ProfileSwitcher from "./ProfileSwitcher"; -import FooterIndexingPeeks from "./indexing/FooterIndexingPeeks"; function Footer() { const navigate = useNavigate(); @@ -48,49 +47,45 @@ function Footer() { } return ( - <> - - -
-
- - {defaultModel?.provider === "free-trial" && ( - - )} -
- -
- {configError && ( - - - - )} +
+
+ + {defaultModel?.provider === "free-trial" && ( + + )} +
+
+ {configError && ( - + + )} - - - -
-
- + + + + + + + +
+
); } diff --git a/gui/src/components/indexing/FooterIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx similarity index 58% rename from gui/src/components/indexing/FooterIndexingPeeks.tsx rename to gui/src/components/indexing/ChatIndexingPeeks.tsx index c95e8db7d..d5fffd138 100644 --- a/gui/src/components/indexing/FooterIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -2,9 +2,12 @@ import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { IndexingStatus } from "core"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { STATUS_TO_ICON } from "./utils"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useNavigate } from "react-router-dom"; +import { XMarkIcon } from "@heroicons/react/24/outline"; +import { current } from "@reduxjs/toolkit"; interface IndexingStatusViewerProps { status: IndexingStatus; @@ -12,6 +15,7 @@ interface IndexingStatusViewerProps { function FooterIndexingPeek({ status }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); + const navigate = useNavigate(); const progressPercentage = useMemo(() => { return Math.min(100, Math.max(0, status.progress * 100)); @@ -20,23 +24,33 @@ function FooterIndexingPeek({ status }: IndexingStatusViewerProps) { const Icon = STATUS_TO_ICON[status.status]; return ( -
+
{ + navigate("/more"); + }} + >
{ + onClick={(e) => { if (status.url) { ideMessenger.post("openUrl", status.url); + e.stopPropagation(); } }} > {status.icon ? ( - doc icon + icon ) : null} -

+

{status.title ?? status.id}

-
+
-
+
{progressPercentage.toFixed(0)}% {Icon ? ( ) : null}
+ {/* */}
); } -function FooterIndexingPeeks() { +function ChatIndexingPeeks() { const indexingStatuses = useSelector( (store: RootState) => store.state.indexingStatuses, ); + const [hidden, setHidden] = useState(false); const currentlyIndexingDocs = useMemo(() => { return Object.values(indexingStatuses).filter( (status) => status.status === "indexing", ); }, [indexingStatuses]); + if (!currentlyIndexingDocs.length) return null; + return ( - <> - {currentlyIndexingDocs.map((status) => { - return ; - })} - +
+

Indexing in progress

+ {hidden + ? null + : currentlyIndexingDocs.map((status) => { + return ; + })} +
); } -export default FooterIndexingPeeks; +export default ChatIndexingPeeks; diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/IndexingStatus.tsx index eb53fd794..bb4f1d546 100644 --- a/gui/src/components/indexing/IndexingStatus.tsx +++ b/gui/src/components/indexing/IndexingStatus.tsx @@ -9,6 +9,7 @@ import { PauseCircleIcon, XMarkIcon, } from "@heroicons/react/24/outline"; +import { updateIndexingStatus } from "../../redux/slices/stateSlice"; interface IndexingStatusViewerProps { status: IndexingStatus; @@ -27,6 +28,7 @@ const STATUS_TO_ICON: Record = { function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); const posthog = usePostHog(); + const dispatch = useDispatch(); const reIndex = () => ideMessenger.post("indexing/reindex", { @@ -34,11 +36,16 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { id: status.id, }); - const abort = () => + const abort = () => { ideMessenger.post("indexing/abort", { type: status.type, id: status.id, }); + // Optimistic abort status + dispatch( + updateIndexingStatus({ ...status, status: "aborted", progress: 0 }), + ); + }; const progressPercentage = useMemo(() => { return Math.min(100, Math.max(0, status.progress * 100)); diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index bd7a61f44..51f28ba9f 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -18,7 +18,6 @@ function IndexingStatuses() { (status) => status.type === "docs" && status.status !== "deleted", ); - return []; return docs; }, [indexingStatuses]); const dispatch = useDispatch(); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 1cb6d66d6..366834ec6 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -62,6 +62,7 @@ import { } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -505,6 +506,7 @@ export function Chat() { )}
+ ); } From 93eddae58aea25283e24da6774caacf515788df1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 23:10:01 -0800 Subject: [PATCH 15/21] docs UI working --- core/indexing/docs/DocsService.ts | 21 +++--- gui/src/components/dialogs/AddDocsDialog.tsx | 69 ++++++++++++++++++- gui/src/components/dialogs/index.tsx | 2 +- .../components/indexing/ChatIndexingPeeks.tsx | 10 +-- .../components/indexing/IndexingStatus.tsx | 10 +-- .../components/indexing/IndexingStatuses.tsx | 11 ++- gui/src/pages/gui/Chat.tsx | 8 ++- 7 files changed, 101 insertions(+), 30 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index cc75c3835..ffb251c64 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -376,24 +376,15 @@ export default class DocsService { progress: 0, }); - // NOTE - during "indexing" phase, check if aborted before each status update - const articles: Article[] = []; let processedPages = 0; - let estimatedProgress = 0; // progress heuristic = sum series 1/(3*2^n) from n=0 to pages. Alternative e.g. sum 1/(2^n) + let estimatedProgress = 0; // progress heuristic = sum series 1/(2^n) from n=1 to pages + 1. Alternative e.g. sum 1/(2^n) // Crawl pages and retrieve info as articles for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - estimatedProgress += 1 / (3 * 2 ** processedPages); - - const article = pageToArticle(page); - - if (!article) { - continue; - } - - articles.push(article); + estimatedProgress += 1 / 2 ** (processedPages + 1); + // NOTE - during "indexing" phase, check if aborted before each status update if (this.isAborted(startUrl)) { return; } @@ -404,6 +395,12 @@ export default class DocsService { progress: 0.4 * estimatedProgress, // 0% -> 40%, a heuristic approach for progress calculation }); + const article = pageToArticle(page); + if (!article) { + continue; + } + articles.push(article); + processedPages++; await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping } diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 3c97e09e6..f373f4bc0 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,11 +1,17 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; +import { + CheckCircleIcon, + ChevronDownIcon, + ChevronUpIcon, +} from "@heroicons/react/24/outline"; import { SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { Button, HelperText, Input, lightGray } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "../indexing/IndexingStatus"; function AddDocsDialog() { const posthog = usePostHog(); @@ -18,7 +24,12 @@ function AddDocsDialog() { const [faviconUrl, setFaviconUrl] = useState(""); const [isOpen, setIsOpen] = useState(false); + const [submittedConfig, setSubmittedConfig] = useState(); + const ideMessenger = useContext(IdeMessengerContext); + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexingStatuses, + ); const isFormValid = startUrl && title; @@ -41,15 +52,67 @@ function AddDocsDialog() { ideMessenger.post("context/addDocs", siteIndexingConfig); + setSubmittedConfig(siteIndexingConfig); setTitle(""); setStartUrl(""); setFaviconUrl(""); - dispatch(setShowDialog(false)); + // dispatch(setShowDialog(false)); posthog.capture("add_docs_gui", { url: startUrl }); } + if (submittedConfig) { + const status = indexingStatuses[submittedConfig.startUrl]; + return ( +
+
+ +

{`Docs added`}

+
+
+

Title: {submittedConfig.title}

+

Start URL: {submittedConfig.startUrl}

+ {submittedConfig.rootUrl && ( +

Root URL: {submittedConfig.rootUrl}

+ )} + {submittedConfig.maxDepth && ( +

Max depth: {submittedConfig.maxDepth}

+ )} + {submittedConfig.faviconUrl && ( +

Favicon URL: {submittedConfig.faviconUrl}

+ )} +
+ {!!status && ( +
+

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

+
+ +
+
+ )} +
+ + +
+
+ ); + } + return (
diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 33214fdfb..7685109ba 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -34,7 +34,6 @@ const DialogContainer = styled.div` top: 50%; left: 50%; transform: translate(-50%, -50%); - width: 75%; `; const Dialog = styled.div` @@ -72,6 +71,7 @@ const TextDialog = (props: TextDialogProps) => { return (
- +
+ +
); } From 416fdbb69ff17f3ab02f6d2b7dce0ea5a7db058c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 09:50:10 -0800 Subject: [PATCH 16/21] unified indexing peeks --- core/indexing/docs/DocsService.ts | 138 ++++++++------- gui/src/components/dialogs/AddDocsDialog.tsx | 8 +- .../components/indexing/ChatIndexingPeeks.tsx | 161 +++++++++++------- .../components/indexing/IndexingStatuses.tsx | 1 - gui/src/components/indexing/utils.ts | 1 - gui/src/pages/gui/Chat.tsx | 1 - gui/src/redux/slices/stateSlice.ts | 65 +------ 7 files changed, 178 insertions(+), 197 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index ffb251c64..838e8fb54 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -10,6 +10,7 @@ import { IndexingStatusMap, IndexingStatus, SiteIndexingConfig, + IdeInfo, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; @@ -101,12 +102,14 @@ export default class DocsService { private sqliteDb?: Database; private docsCrawler!: DocsCrawler; + private ideInfoPromise: Promise; constructor( configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, ) { + this.ideInfoPromise = this.ide.getIdeInfo(); this.isInitialized = this.init(configHandler); } @@ -135,6 +138,31 @@ export default class DocsService { readonly statuses: IndexingStatusMap = new Map(); + // Function for GUI to retrieve initial pending statuses + // And kickoff indexing where needed + async initStatuses() { + this.config?.docs?.forEach(async (doc) => { + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + this.handleStatusUpdate(currentStatus); + } else { + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + progress: 0, + description: "Pending", + status: "pending", + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }); + } + }); + } + handleStatusUpdate(update: IndexingStatus) { this.statuses.set(update.id, update); this.messenger?.send("indexing/statusUpdate", update); @@ -143,6 +171,7 @@ export default class DocsService { abort(startUrl: string) { const status = this.statuses.get(startUrl); if (status) { + this.docsIndexingQueue.delete(startUrl); this.handleStatusUpdate({ ...status, status: "aborted", @@ -177,7 +206,7 @@ export default class DocsService { * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. */ async canUsePreindexedDocs() { - const ideInfo = await this.ide.getIdeInfo(); + const ideInfo = await this.ideInfoPromise; if (ideInfo.ideType === "jetbrains") { return false; } @@ -322,12 +351,15 @@ export default class DocsService { ): Promise { const { startUrl } = siteIndexingConfig; + // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs if (this.docsIndexingQueue.has(startUrl)) { - console.debug("Already in queue"); return; } + const embeddingsProvider = await this.getEmbeddingsProvider(); + this.docsIndexingQueue.add(startUrl); + const indexExists = await this.hasMetadata(startUrl); const fixedStatus: Pick< @@ -366,8 +398,6 @@ export default class DocsService { } } - // Mark the site as currently being indexed - this.docsIndexingQueue.add(startUrl); try { this.handleStatusUpdate({ ...fixedStatus, @@ -378,7 +408,7 @@ export default class DocsService { const articles: Article[] = []; let processedPages = 0; - let estimatedProgress = 0; // progress heuristic = sum series 1/(2^n) from n=1 to pages + 1. Alternative e.g. sum 1/(2^n) + let estimatedProgress = 0; // Crawl pages and retrieve info as articles for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { @@ -392,7 +422,10 @@ export default class DocsService { ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", - progress: 0.4 * estimatedProgress, // 0% -> 40%, a heuristic approach for progress calculation + progress: + 0.3 * estimatedProgress + + Math.min(0.2, (0.2 * processedPages) / 500), + // For the first 50%, 30% is sum of series 1/(2^n) and the other 20% is based on number of files/ 500 max }); const article = pageToArticle(page); @@ -425,7 +458,7 @@ export default class DocsService { ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, - progress: 0.4 + 0.4 * (i / articles.length), // 40% -> 80% + progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80% }); try { @@ -466,9 +499,7 @@ export default class DocsService { }); void this.ide.showToast("info", `Failed to index ${startUrl}`); - this.docsIndexingQueue.delete(startUrl); - return; } @@ -540,28 +571,34 @@ export default class DocsService { } } - // Function for GUI to retrieve initial pending statuses - // And kickoff indexing where needed - async initStatuses() { - this.config?.docs?.forEach(async (doc) => { - const currentStatus = this.statuses.get(doc.startUrl); - if (currentStatus) { - this.handleStatusUpdate(currentStatus); - } else { - this.handleStatusUpdate({ - type: "docs", - id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.id, - isReindexing: false, - progress: 0, - description: "Pending", - status: "pending", - title: doc.title, - debugInfo: `max depth: ${doc.maxDepth}`, - icon: doc.faviconUrl, - url: doc.startUrl, - }); - } + // When user requests a pre-indexed doc for the first time + // And pre-indexed embeddings are supported + // Fetch pre-indexed embeddings from S3, add to Lance, and then search those + private async fetchAndAddPreIndexedDocEmbeddings(title: string) { + const embeddingsProvider = await this.getEmbeddingsProvider(true); + + const data = await downloadFromS3( + S3Buckets.continueIndexedDocs, + getS3Filename(embeddingsProvider.id, title), + ); + + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; + const startUrl = new URL(siteEmbeddings.url).toString(); + + const faviconUrl = preIndexedDocs[startUrl].faviconUrl; + const favicon = + typeof faviconUrl === "string" + ? await getFaviconBase64(faviconUrl) + : undefined; + + await this.add({ + favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), }); } @@ -704,7 +741,7 @@ export default class DocsService { const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // Anything found in sqlite but not in new config should be deleted + // Anything found in sqlite but not in new config should be deleted if not preindexed const deletedDocs = currentlyIndexedDocs.filter( (doc) => !preIndexedDocs[doc.startUrl] && @@ -717,12 +754,12 @@ export default class DocsService { const newDocs: SiteIndexingConfig[] = []; const changedDocs: SiteIndexingConfig[] = []; for (const doc of newConfigDocs) { - const oldConfigDoc = oldConfigDocs.find( - (d) => d.startUrl === doc.startUrl, - ); const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); if (currentIndexedDoc) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); if ( oldConfigDoc && (oldConfigDoc.maxDepth !== doc.maxDepth || @@ -976,37 +1013,6 @@ export default class DocsService { this.messenger?.send("refreshSubmenuItems", undefined); } - // When user requests a pre-indexed doc for the first time - // And pre-indexed embeddings are supported - // Fetch pre-indexed embeddings from S3, add to Lance, and then search those - private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const embeddingsProvider = await this.getEmbeddingsProvider(true); - - const data = await downloadFromS3( - S3Buckets.continueIndexedDocs, - getS3Filename(embeddingsProvider.id, title), - ); - - const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const startUrl = new URL(siteEmbeddings.url).toString(); - - const faviconUrl = preIndexedDocs[startUrl].faviconUrl; - const favicon = - typeof faviconUrl === "string" - ? await getFaviconBase64(faviconUrl) - : undefined; - - await this.add({ - favicon, - siteIndexingConfig: { - startUrl, - title: siteEmbeddings.title, - }, - chunks: siteEmbeddings.chunks, - embeddings: siteEmbeddings.chunks.map((c) => c.embedding), - }); - } - /** * Currently this deletes re-crawls + re-indexes all docs. * A more optimal solution in the future will be to create diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index f373f4bc0..1a8682150 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -9,7 +9,10 @@ import { useContext, useLayoutEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Button, HelperText, Input, lightGray } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; @@ -57,8 +60,6 @@ function AddDocsDialog() { setStartUrl(""); setFaviconUrl(""); - // dispatch(setShowDialog(false)); - posthog.capture("add_docs_gui", { url: startUrl }); } @@ -103,6 +104,7 @@ function AddDocsDialog() { +
diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index f3a609c68..c77bdc323 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -1,14 +1,15 @@ -import { useSelector } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { IndexingStatus } from "core"; import { useMemo, useState } from "react"; import { useNavigate } from "react-router-dom"; import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline"; +import { setIndexingChatPeekHidden } from "../../redux/slices/stateSlice"; interface MergedIndexingState { displayName: string; - type: string; + type: IndexingStatus["type"]; titles: IndexingStatus["title"][]; progressPercentage: number; } @@ -21,14 +22,16 @@ const mergeProgress = (states: IndexingStatus[]): number => { export interface ChatIndexingPeekProps { state: MergedIndexingState; - hidden: boolean; - setHidden: (hidden: boolean) => void; } -function ChatIndexingPeek({ state, hidden, setHidden }: ChatIndexingPeekProps) { +function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { const navigate = useNavigate(); + const dispatch = useDispatch(); + const hiddenPeeks = useSelector( + (store: RootState) => store.state.indexing.hiddenChatPeekTypes, + ); - if (hidden) return null; + if (hiddenPeeks[state.type]) return null; return (
{ - setHidden(true); + dispatch( + setIndexingChatPeekHidden({ type: state.type, hidden: true }), + ); e.stopPropagation(); }} /> @@ -75,13 +80,8 @@ function ChatIndexingPeek({ state, hidden, setHidden }: ChatIndexingPeekProps) { function ChatIndexingPeeks() { const indexingStatuses = useSelector( - (store: RootState) => store.state.indexingStatuses, + (store: RootState) => store.state.indexing.statuses, ); - - const [hidden, setHidden] = useState<{ - [key: string]: boolean; - }>({}); - const mergedIndexingStates: MergedIndexingState[] = useMemo(() => { const mergedStates: MergedIndexingState[] = []; @@ -95,12 +95,6 @@ function ChatIndexingPeeks() { titles: docsStates.map((state) => state.title), progressPercentage: mergeProgress(docsStates), }); - } else { - // So that next indexing will show again if hidden - setHidden({ - ...hidden, - docs: false, - }); } return mergedStates; }, [indexingStatuses]); @@ -110,18 +104,7 @@ function ChatIndexingPeeks() { return (
{mergedIndexingStates.map((state) => { - return ( -
); diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index da10dde90..ecc35189d 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -11,7 +11,7 @@ import AddDocsDialog from "../dialogs/AddDocsDialog"; function IndexingStatuses() { const indexingStatuses = useSelector( - (store: RootState) => store.state.indexingStatuses, + (store: RootState) => store.state.indexing.statuses, ); const docsStatuses = useMemo(() => { const docs = Object.values(indexingStatuses).filter( @@ -28,6 +28,7 @@ function IndexingStatuses() { {/*
*/} + {/* TODO add some way to hide, scroll, etc. */}
Manage your documentation sources diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 7027ac54c..b31e4b01e 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -38,7 +38,10 @@ type State = { isMultifileEdit: boolean; applyStates: ApplyState[]; nextCodeBlockToApplyIndex: number; - indexingStatuses: Record; + indexing: { + hiddenChatPeekTypes: Record; + statuses: Record; + }; }; const initialState: State = { @@ -70,7 +73,12 @@ const initialState: State = { curCheckpointIndex: 0, nextCodeBlockToApplyIndex: 0, applyStates: [], - indexingStatuses: {}, + indexing: { + statuses: {}, + hiddenChatPeekTypes: { + docs: false, + }, + }, }; export const stateSlice = createSlice({ @@ -366,10 +374,37 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { - state.indexingStatuses = { - ...state.indexingStatuses, + state.indexing.statuses = { + ...state.indexing.statuses, [payload.id]: payload, }; + + // This check is so that if all indexing is stopped for e.g. docs + // The next time docs indexing starts the peek will show again + const indexingThisType = Object.values(state.indexing.statuses).filter( + (status) => + status.type === payload.type && status.status === "indexing", + ); + if (indexingThisType.length === 0) { + state.indexing.hiddenChatPeekTypes = { + ...state.indexing.hiddenChatPeekTypes, + [payload.type]: false, + }; + } + }, + setIndexingChatPeekHidden: ( + state, + { + payload, + }: PayloadAction<{ + type: IndexingStatus["type"]; + hidden: boolean; + }>, + ) => { + state.indexing.hiddenChatPeekTypes = { + ...state.indexing.hiddenChatPeekTypes, + [payload.type]: payload.hidden, + }; }, }, }); @@ -401,6 +436,7 @@ export const { resetNextCodeBlockToApplyIndex, updateApplyState, updateIndexingStatus, + setIndexingChatPeekHidden, } = stateSlice.actions; export default stateSlice.reducer; From 499b1223b7728e3766f41bc6fdf7cceb80215d37 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 13:09:47 -0800 Subject: [PATCH 19/21] docs UI tweaks --- gui/src/components/dialogs/AddDocsDialog.tsx | 1 - gui/src/components/indexing/IndexingStatus.tsx | 7 ++++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index d66c315fe..098194886 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -15,7 +15,6 @@ import { } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; -import { NewSessionButton } from "../mainInput/NewSessionButton"; function AddDocsDialog() { const posthog = usePostHog(); diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/IndexingStatus.tsx index 98014c27b..6fe72c741 100644 --- a/gui/src/components/indexing/IndexingStatus.tsx +++ b/gui/src/components/indexing/IndexingStatus.tsx @@ -5,6 +5,8 @@ import { usePostHog } from "posthog-js/react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { ArrowPathIcon, + ArrowRightStartOnRectangleIcon, + ArrowTopRightOnSquareIcon, CheckCircleIcon, PauseCircleIcon, XMarkIcon, @@ -60,7 +62,7 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { className={`flex flex-row items-center justify-between gap-2 text-sm`} >
{ if (status.url) { ideMessenger.post("openUrl", status.url); @@ -73,6 +75,9 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) {

{status.title ?? status.id}

+ {!!status.url && ( + + )}
{status.status === "pending" ? (
Pending...
From 29fb0cdb802411df16ad694ed1ffebe03a38b83f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 13:11:43 -0800 Subject: [PATCH 20/21] docs ui tweaks --- gui/src/components/indexing/IndexingStatuses.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index ecc35189d..7441212f9 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -2,7 +2,7 @@ import { useMemo } from "react"; import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "./IndexingStatus"; -import { Button } from ".."; +import { Button, SecondaryButton } from ".."; import { setDialogMessage, setShowDialog, @@ -39,14 +39,14 @@ function IndexingStatuses() { return ; }) ) : ( - + )}
// From a20374299ac6f70f5cc26bdf16690f8681e78757 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 10:25:25 -0800 Subject: [PATCH 21/21] change button height --- gui/src/components/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 3a384c995..e380f3ef6 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -154,7 +154,6 @@ export const Button = styled.button` export const SecondaryButton = styled.button` padding: 10px 12px; margin: 8px 0; - height: 2.5rem; border-radius: ${defaultBorderRadius}; border: 1px solid ${vscForeground};