From bb7b9781fa71f5d0fae6e6206978d73cd6138996 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 13 Nov 2024 19:22:44 -0800 Subject: [PATCH 01/54] symbols in chat p1 --- core/core.ts | 19 +++- core/index.d.ts | 11 ++- core/protocol/core.ts | 5 ++ core/protocol/passThrough.ts | 3 +- core/util/treeSitter.ts | 70 +++++++++++++++ .../mainInput/CodeBlockComponent.tsx | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 19 +++- .../components/mainInput/ContinueInputBox.tsx | 25 +----- gui/src/components/mainInput/TipTapEditor.tsx | 2 +- gui/src/components/mainInput/resolveInput.ts | 86 +++++++++++++------ gui/src/components/markdown/FilenameLink.tsx | 4 +- .../markdown/StyledMarkdownPreview.tsx | 2 + gui/src/hooks/useChatHandler.ts | 16 +--- gui/src/hooks/useSetup.ts | 2 +- gui/src/pages/edit/index.tsx | 1 + gui/src/pages/gui/Chat.tsx | 2 +- gui/src/redux/slices/stateSlice.ts | 61 ++++++++----- 17 files changed, 228 insertions(+), 102 deletions(-) diff --git a/core/core.ts b/core/core.ts index 6df1482ef..dfe3a4f4a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -32,9 +32,15 @@ import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; +import type { + ContextItemId, + IDE, + IndexingProgressUpdate, + SymbolWithLocation, +} from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; +import { getFileSymbols, getSymbolsForFiles } from "./util/treeSitter"; export class Core { // implements IMessenger @@ -83,7 +89,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 +180,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -365,6 +371,11 @@ export class Core { } }); + on("context/getSymbolsForFiles", async (msg) => { + const { uris } = msg.data; + return await getSymbolsForFiles(uris, this.ide); + }); + on("config/getSerializedProfileInfo", async (msg) => { return { config: await this.configHandler.getSerializedConfig(), @@ -684,7 +695,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) => { diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..2e6d79318 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,3 +1,4 @@ +import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -298,18 +299,26 @@ export interface InputModifiers { noContext: boolean; } +export interface SymbolWithLocation { + name: string; + type: Parser.SyntaxNode["type"]; + location: Location; +} + +export type FileSymbolMap = Record; + export interface PromptLog { modelTitle: string; completionOptions: CompletionOptions; prompt: string; completion: string; } - export interface ChatHistoryItem { message: ChatMessage; editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; + contextSymbols?: SymbolWithLocation[]; promptLogs?: PromptLog[]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..3f02c3fc0 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -17,6 +17,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, + SymbolWithLocation, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -76,6 +77,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "context/getSymbolsForFiles": [ + { uris: string[] }, + Record, + ]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..d05d773c4 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/deleteModel", "config/reload", "context/getContextItems", + "context/getSymbolsForFiles", "context/loadSubmenuItems", "context/addDocs", "context/removeDocs", @@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index b877a251b..566917ecc 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; +import { FileSymbolMap, IDE, SymbolWithLocation } from ".."; export const supportedLanguages: { [key: string]: string } = { cpp: "cpp", @@ -178,3 +179,72 @@ async function loadLanguageForFileExt( ); return await Parser.Language.load(wasmPath); } + +const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ + "class_declaration", + "function_item", // function name = first "identifier" child + "method_declaration", // method name = first "identifier" child + // "arrow_function", +]; + +export async function getSymbolsForFile( + filepath: string, + contents: string, +): Promise { + const parser = await getParserForFile(filepath); + + if (!parser) { + return; + } + + const tree = parser.parse(contents); + console.log(`file: ${filepath}`); + + // Function to recursively find all named nodes (classes and functions) + const symbols: SymbolWithLocation[] = []; + function findNamedNodesRecursive(node: Parser.SyntaxNode) { + if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { + console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); + node.children.forEach((child) => { + console.log(`child: ${child.type}, ${child.text}`); + }); + + // Empirically, the actualy name is the last identifier in the node + // Especially with languages where return type is declared before the name + const identifier = node.children.findLast( + (child) => child.type === "identifier", + )?.text; + if (identifier) { + symbols.push({ + type: node.type, + name: identifier, + location: { + filepath, + position: { + character: node.startPosition.column, + line: node.startPosition.row + 1, + }, + }, + }); + } + } + node.children.forEach(findNamedNodesRecursive); + } + findNamedNodesRecursive(tree.rootNode); + + return symbols; +} + +export async function getSymbolsForFiles( + uris: string[], + ide: IDE, +): Promise { + const filesAndSymbols = await Promise.all( + uris.map(async (uri): Promise<[string, SymbolWithLocation[]]> => { + const contents = await ide.readFile(uri); + const symbols = await getSymbolsForFile(uri, contents); + return [uri, symbols ?? []]; + }), + ); + return Object.fromEntries(filesAndSymbols); +} diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 217fcc293..4266db4f5 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -16,7 +16,7 @@ export const CodeBlockComponent = ({ const item: ContextItemWithId = node.attrs.item; const contextItems = useSelector( - (state: RootState) => state.state.contextItems, + (state: RootState) => state.state.context.items, ); return ( diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 3ae178abf..33bdbff6d 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -10,10 +10,12 @@ import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; import { getIconFromDropdownItem } from "./MentionList"; import styled from "styled-components"; import { getBasename } from "core/util"; +import { RootState } from "../../redux/store"; +import { useSelector } from "react-redux"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; - isGatheringContext: boolean; + isCurrentContextPeek: boolean; } interface ContextItemsPeekItemProps { @@ -119,7 +121,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { function ContextItemsPeek({ contextItems, - isGatheringContext, + isCurrentContextPeek, }: ContextItemsPeekProps) { const [open, setOpen] = useState(false); @@ -127,7 +129,16 @@ function ContextItemsPeek({ (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), ); - if ((!ctxItems || ctxItems.length === 0) && !isGatheringContext) { + const isGatheringContext = useSelector( + (store: RootState) => store.state.context.isGathering, + ); + const gatheringMessage = useSelector( + (store: RootState) => store.state.context.gatheringMessage, + ); + + const indicateIsGathering = isCurrentContextPeek && isGatheringContext; + + if ((!ctxItems || ctxItems.length === 0) && !indicateIsGathering) { return null; } @@ -152,7 +163,7 @@ function ContextItemsPeek({ {isGatheringContext ? ( <> - Gathering context + {gatheringMessage} ) : ( diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index c98a69403..544eb8f63 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,6 +1,5 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; @@ -70,12 +69,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const availableContextProviders = useSelector( (store: RootState) => store.state.config.contextProviders, ); - const isGatheringContextStore = useSelector( - (store: RootState) => store.state.isGatheringContext, - ); - - const [isGatheringContext, setIsGatheringContext] = useState(false); - const timeoutRef = useRef(null); const isInMultifileEdit = useSelector( (state: RootState) => state.state.isInMultifileEdit, @@ -100,22 +93,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { [props.isMainInput], ); - useEffect(() => { - if (isGatheringContextStore && !isGatheringContext) { - // 500ms delay when going from false -> true to prevent flashing loading indicator - timeoutRef.current = setTimeout(() => setIsGatheringContext(true), 500); - } else { - // Update immediately otherwise (i.e. true -> false) - setIsGatheringContext(isGatheringContextStore); - } - - return () => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - }; - }, [isGatheringContextStore]); - return (
{shouldShowAcceptRejectButtons && } @@ -145,7 +122,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index c2646415e..cb57681ea 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -223,7 +223,7 @@ function TipTapEditor(props: TipTapEditorProps) { }; const contextItems = useSelector( - (store: RootState) => store.state.contextItems, + (store: RootState) => store.state.context.items, ); const defaultModel = useSelector(defaultModelSelector); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 64acba85a..85ac9e398 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -9,6 +9,8 @@ import { } from "core"; import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; +import { Dispatch } from "@reduxjs/toolkit"; +import { setIsGatheringContext } from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -29,6 +31,7 @@ async function resolveEditorContent( modifiers: InputModifiers, ideMessenger: IIdeMessenger, defaultContextProviders: DefaultContextProvider[], + dispatch: Dispatch, ): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> { let parts: MessagePart[] = []; let contextItemAttrs: MentionAttrs[] = []; @@ -38,8 +41,7 @@ async function resolveEditorContent( if (p.type === "paragraph") { const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - // Only take the first slash command - + // Only take the first slash command\ if (foundSlashCommand && typeof slashCommand === "undefined") { slashCommand = foundSlashCommand; } @@ -103,6 +105,17 @@ async function resolveEditorContent( } } + const shouldGatherContext = modifiers.useCodebase || slashCommand; + + if (shouldGatherContext) { + dispatch( + setIsGatheringContext({ + isGathering: true, + gatheringMessage: "Gathering context", + }), + ); + } + let contextItemsText = ""; let contextItems: ContextItemWithId[] = []; for (const item of contextItemAttrs) { @@ -158,6 +171,18 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); + const contextItemFileUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri.value), + ), + ); + + const symbols = await ideMessenger.request("context/getSymbolsForFiles", { + uris: contextItemFileUris, + }); + if (contextItemsText !== "") { contextItemsText += "\n"; } @@ -172,7 +197,16 @@ async function resolveEditorContent( } } - return [contextItems, selectedCode, parts]; + if (shouldGatherContext) { + dispatch( + setIsGatheringContext({ + isGathering: false, + gatheringMessage: "Gathering context", + }), + ); + } + + return [contextItems, selectedCode, parts, symbols]; } function findLastIndex( @@ -213,30 +247,30 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } -export function hasSlashCommandOrContextProvider( - editorState: JSONContent, -): boolean { - if (!editorState.content) { - return false; - } +// export function hasSlashCommandOrContextProvider( +// editorState: JSONContent, +// ): boolean { +// if (!editorState.content) { +// return false; +// } - for (const p of editorState.content) { - if (p.type === "paragraph" && p.content) { - for (const child of p.content) { - if (child.type === "slashcommand") { - return true; - } - if ( - child.type === "mention" && - child.attrs?.itemType === "contextProvider" - ) { - return true; - } - } - } - } +// for (const p of editorState.content) { +// if (p.type === "paragraph" && p.content) { +// for (const child of p.content) { +// if (child.type === "slashcommand") { +// return true; +// } +// if ( +// child.type === "mention" && +// child.attrs?.itemType === "contextProvider" +// ) { +// return true; +// } +// } +// } +// } - return false; -} +// return false; +// } export default resolveEditorContent; diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 3674fc418..0d1166a00 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -20,7 +20,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { } return ( -
@@ -28,7 +28,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { {getBasename(rif.filepath)} -
+
); } diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 77158e96a..c5190d8e8 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -246,6 +246,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } + // const symbole = symboles + return {codeProps.children}; }, }, diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2e35acc53..8517ea5d9 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -17,9 +17,7 @@ import { getBasename, getRelativePath } from "core/util"; import { usePostHog } from "posthog-js/react"; import { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; -import resolveEditorContent, { - hasSlashCommandOrContextProvider, -} from "../components/mainInput/resolveInput"; +import resolveEditorContent from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { @@ -51,7 +49,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { ); const contextItems = useSelector( - (state: RootState) => state.state.contextItems, + (store: RootState) => store.state.context.items, ); const history = useSelector((store: RootState) => store.state.history); @@ -195,13 +193,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { // Reset current code block index dispatch(resetNextCodeBlockToApplyIndex()); - const shouldGatherContext = - modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); - - if (shouldGatherContext) { - dispatch(setIsGatheringContext(true)); - } - // Resolve context providers and construct new history const [selectedContextItems, selectedCode, content] = await resolveEditorContent( @@ -209,10 +200,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { modifiers, ideMessenger, defaultContextProviders, + dispatch, ); - dispatch(setIsGatheringContext(false)); - // Automatically use currently open file if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2fed805da..4378059e0 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -20,7 +20,7 @@ import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; -function useSetup(dispatch: Dispatch) { +function useSetup(dispatch: Dispatch) { const [configLoaded, setConfigLoaded] = useState(false); const ideMessenger = useContext(IdeMessengerContext); diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 5b1b71e66..af33ee99d 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -174,6 +174,7 @@ function Edit() { }, ideMessenger, [], + dispatch, ); const prompt = [ diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 78bbcd262..85f4eb416 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -290,7 +290,7 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [state.history, state.contextItems, defaultModel, state, streamResponse], + [state.history, state.context.items, defaultModel, state, streamResponse], ); useWebviewListener( diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e3ce22eb6..cd1e4a8bc 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -15,16 +15,6 @@ import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; import { RootState } from "../store"; -export const memoizedContextItemsSelector = createSelector( - [(state: RootState) => state.state.history], - (history) => { - return history.reduce((acc, item) => { - acc.push(...item.contextItems); - return acc; - }, []); - }, -); - // 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. type ChatHistoryItemWithMessageId = ChatHistoryItem & { @@ -33,10 +23,13 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { type State = { history: ChatHistoryItemWithMessageId[]; - contextItems: ContextItemWithId[]; + context: { + items: ContextItemWithId[]; + isGathering: boolean; + gatheringMessage: string; + }; ttsActive: boolean; active: boolean; - isGatheringContext: boolean; config: BrowserSerializedContinueConfig; title: string; sessionId: string; @@ -49,10 +42,13 @@ type State = { const initialState: State = { history: [], - contextItems: [], + context: { + items: [], + isGathering: false, + gatheringMessage: "Gathering Context", + }, ttsActive: false, active: false, - isGatheringContext: false, configError: undefined, config: { slashCommands: [ @@ -116,8 +112,17 @@ export const stateSlice = createSlice({ setActive: (state) => { state.active = true; }, - setIsGatheringContext: (state, { payload }: PayloadAction) => { - state.isGatheringContext = payload; + setIsGatheringContext: ( + state, + { + payload, + }: PayloadAction<{ + isGathering: boolean; + gatheringMessage: string; + }>, + ) => { + state.context.isGathering = payload.isGathering; + state.context.gatheringMessage = payload.gatheringMessage; }, clearLastResponse: (state) => { if (state.history.length < 2) { @@ -144,7 +149,7 @@ export const stateSlice = createSlice({ } }, addContextItems: (state, action: PayloadAction) => { - state.contextItems = state.contextItems.concat(action.payload); + state.context.items = state.context.items.concat(action.payload); }, resubmitAtIndex: ( state, @@ -190,7 +195,7 @@ export const stateSlice = createSlice({ ) => { state.history.push({ message: { role: "user", content: "", id: uuidv4() }, - contextItems: state.contextItems, + contextItems: state.context.items, editorState: payload.editorState, }); state.history.push({ @@ -253,7 +258,7 @@ export const stateSlice = createSlice({ historyItem.contextItems.push(...payload.contextItems); }, setInactive: (state) => { - state.isGatheringContext = false; + state.context.isGathering = false; state.active = false; }, streamUpdate: (state, action: PayloadAction) => { @@ -272,7 +277,7 @@ export const stateSlice = createSlice({ state.sessionId = payload.sessionId; } else { state.history = []; - state.contextItems = []; + state.context.items = []; state.active = false; state.title = "New Session"; state.sessionId = v4(); @@ -289,7 +294,7 @@ export const stateSlice = createSlice({ const ids = new Set(payload.ids.map(getKey)); if (payload.index === undefined) { - state.contextItems = state.contextItems.filter( + state.context.items = state.context.items.filter( (item) => !ids.has(getKey(item.id)), ); } else { @@ -304,7 +309,7 @@ export const stateSlice = createSlice({ payload, }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>, ) => { - let contextItems = [...state.contextItems].map((item) => { + let contextItems = [...state.context.items].map((item) => { return { ...item, editing: false }; }); const base = payload.rangeInFileWithContents.filepath @@ -372,7 +377,7 @@ export const stateSlice = createSlice({ if (typeof payload.index === "undefined") { return { ...state, - contextItems: state.contextItems.map((item) => { + contextItems: state.context.items.map((item) => { return { ...item, editing: ids.includes(item.id.itemId), @@ -424,6 +429,16 @@ export const stateSlice = createSlice({ }, }); +export const memoizedContextItemsSelector = createSelector( + [(state: RootState) => state.state.history], + (history) => { + return history.reduce((acc, item) => { + acc.push(...item.contextItems); + return acc; + }, []); + }, +); + export const { setContextItemsAtIndex, addContextItems, From faf45035f9f214ad231a89a2f0d2220bd3d5e4b3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 09:37:20 -0800 Subject: [PATCH 02/54] symbol links p3 --- core/core.ts | 9 +--- core/index.d.ts | 7 ++- core/protocol/core.ts | 7 +-- core/util/treeSitter.ts | 53 +++++++++++++------ .../mainInput/CodeBlockComponent.tsx | 1 - gui/src/components/mainInput/resolveInput.ts | 19 +++++-- .../markdown/StyledMarkdownPreview.tsx | 47 +++++++++++++--- gui/src/components/markdown/SymbolLink.tsx | 33 ++++++++++++ gui/src/redux/slices/stateSlice.ts | 10 ++++ 9 files changed, 141 insertions(+), 45 deletions(-) create mode 100644 gui/src/components/markdown/SymbolLink.tsx diff --git a/core/core.ts b/core/core.ts index dfe3a4f4a..727e5f200 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,17 +30,12 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { getSymbolsForFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; -import type { - ContextItemId, - IDE, - IndexingProgressUpdate, - SymbolWithLocation, -} from "."; +import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; -import { getFileSymbols, getSymbolsForFiles } from "./util/treeSitter"; export class Core { // implements IMessenger diff --git a/core/index.d.ts b/core/index.d.ts index 2e6d79318..25d5c346d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -299,13 +299,12 @@ export interface InputModifiers { noContext: boolean; } -export interface SymbolWithLocation { +export interface SymbolWithRange extends RangeInFile { name: string; type: Parser.SyntaxNode["type"]; - location: Location; } -export type FileSymbolMap = Record; +export type FileSymbolMap = Record; export interface PromptLog { modelTitle: string; @@ -318,7 +317,7 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - contextSymbols?: SymbolWithLocation[]; + contextSymbols?: SymbolWithRange[]; promptLogs?: PromptLog[]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 3f02c3fc0..cef8c38c9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -7,6 +7,7 @@ import type { ContextItemWithId, ContextSubmenuItem, DiffLine, + FileSymbolMap, IdeSettings, LLMFullCompletionOptions, MessageContent, @@ -17,7 +18,6 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, - SymbolWithLocation, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -77,10 +77,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; - "context/getSymbolsForFiles": [ - { uris: string[] }, - Record, - ]; + "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 566917ecc..18ac14d16 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,7 +2,8 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; -import { FileSymbolMap, IDE, SymbolWithLocation } from ".."; + +import { FileSymbolMap, IDE, SymbolWithRange } from ".."; export const supportedLanguages: { [key: string]: string } = { cpp: "cpp", @@ -180,17 +181,24 @@ async function loadLanguageForFileExt( return await Parser.Language.load(wasmPath); } +// See https://tree-sitter.github.io/tree-sitter/using-parsers const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ "class_declaration", + "class_definition", "function_item", // function name = first "identifier" child + "function_definition", "method_declaration", // method name = first "identifier" child + "method_definition", + "generator_function_declaration", + // property_identifier + // field_declaration // "arrow_function", ]; export async function getSymbolsForFile( filepath: string, contents: string, -): Promise { +): Promise { const parser = await getParserForFile(filepath); if (!parser) { @@ -201,28 +209,39 @@ export async function getSymbolsForFile( console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) - const symbols: SymbolWithLocation[] = []; + const symbols: SymbolWithRange[] = []; function findNamedNodesRecursive(node: Parser.SyntaxNode) { + // console.log(`node: ${node.type}, ${node.text}`); if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { - console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); - node.children.forEach((child) => { - console.log(`child: ${child.type}, ${child.text}`); - }); + // console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); + // node.children.forEach((child) => { + // console.log(`child: ${child.type}, ${child.text}`); + // }); // Empirically, the actualy name is the last identifier in the node // Especially with languages where return type is declared before the name - const identifier = node.children.findLast( - (child) => child.type === "identifier", - )?.text; - if (identifier) { + // TODO use findLast in newer version of node target + let identifier: Parser.SyntaxNode | undefined = undefined; + for (let i = node.children.length - 1; i >= 0; i--) { + if (node.children[i].type === "identifier") { + identifier = node.children[i]; + break; + } + } + + if (identifier?.text) { symbols.push({ + filepath, type: node.type, - name: identifier, - location: { - filepath, - position: { + name: identifier.text, + range: { + start: { character: node.startPosition.column, - line: node.startPosition.row + 1, + line: node.startPosition.row, + }, + end: { + character: node.endPosition.column + 1, + line: node.endPosition.row + 1, }, }, }); @@ -240,7 +259,7 @@ export async function getSymbolsForFiles( ide: IDE, ): Promise { const filesAndSymbols = await Promise.all( - uris.map(async (uri): Promise<[string, SymbolWithLocation[]]> => { + uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { const contents = await ide.readFile(uri); const symbols = await getSymbolsForFile(uri, contents); return [uri, symbols ?? []]; diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 4266db4f5..2a63d889e 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -12,7 +12,6 @@ export const CodeBlockComponent = ({ editor, updateAttributes, }: any) => { - const dispatch = useDispatch(); const item: ContextItemWithId = node.attrs.item; const contextItems = useSelector( diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 85ac9e398..a4598ae93 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -10,7 +10,10 @@ import { import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { setIsGatheringContext } from "../../redux/slices/stateSlice"; +import { + setIsGatheringContext, + updateFileSymbols, +} from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -179,9 +182,15 @@ async function resolveEditorContent( ), ); - const symbols = await ideMessenger.request("context/getSymbolsForFiles", { - uris: contextItemFileUris, - }); + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { + uris: contextItemFileUris, + }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } if (contextItemsText !== "") { contextItemsText += "\n"; @@ -206,7 +215,7 @@ async function resolveEditorContent( ); } - return [contextItems, selectedCode, parts, symbols]; + return [contextItems, selectedCode, parts]; } function findLastIndex( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index c5190d8e8..70af5b6b4 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect } from "react"; +import { memo, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -21,6 +21,9 @@ import FilenameLink from "./FilenameLink"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; +import { RootState } from "../../redux/store"; +import { SymbolWithRange } from "core"; +import SymbolLink from "./SymbolLink"; const StyledMarkdown = styled.div<{ fontSize?: number; @@ -112,16 +115,16 @@ function getLanuageFromClassName(className: any): string | null { function getCodeChildrenContent(children: any) { if (typeof children === "string") { + console.log(children); return children; } else if ( Array.isArray(children) && children.length > 0 && - typeof children[0] === "string" && - children[0] !== "" + typeof children[0] === "string" ) { + console.log(children[0]); return children[0]; } - return undefined; } @@ -154,6 +157,25 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { const contextItems = useSelector(memoizedContextItemsSelector); + const symbols = useSelector( + (state: RootState) => state.state.context.symbols, + ); + const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + const contextUris = Array.from( + new Set( + contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), + ), + ); + const contextSymbols: SymbolWithRange[] = []; + contextUris.forEach((uri) => { + const fileSymbols = symbols[uri]; + if (fileSymbols) { + contextSymbols.push(...fileSymbols); + } + }); + console.log(contextSymbols.map((s) => s.name)); + return contextSymbols; + }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -245,9 +267,22 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const rif = ctxItemToRifWithContents(ctxItem); return ; } + // console.log("content", content); + const exactSymbol = symbolsForContextItems.find( + (s) => s.name === content, + ); + if (exactSymbol) { + return ; + } - // const symbole = symboles - + // PARTIAL - PARENTHESES + const partialSymbol = symbolsForContextItems.find( + (s) => false, + // content.startsWith(s.name), + ); + if (partialSymbol) { + return ; + } return {codeProps.children}; }, }, diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx new file mode 100644 index 000000000..84c1e8984 --- /dev/null +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -0,0 +1,33 @@ +import { SymbolWithRange } from "core"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +interface SymbolLinkProps { + symbol: SymbolWithRange; + content: string; +} + +function SymbolLink({ symbol, content }: SymbolLinkProps) { + const ideMessenger = useContext(IdeMessengerContext); + + function onClick() { + ideMessenger.post("showLines", { + filepath: symbol.filepath, + startLine: symbol.range.start.line, + endLine: symbol.range.end.line, + }); + } + + return ( + + + {content} + + + ); +} + +export default SymbolLink; diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index cd1e4a8bc..22c76e9ee 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -5,6 +5,7 @@ import { ChatMessage, ContextItemId, ContextItemWithId, + FileSymbolMap, PersistedSessionInfo, PromptLog, } from "core"; @@ -25,6 +26,7 @@ type State = { history: ChatHistoryItemWithMessageId[]; context: { items: ContextItemWithId[]; + symbols: FileSymbolMap; isGathering: boolean; gatheringMessage: string; }; @@ -44,6 +46,7 @@ const initialState: State = { history: [], context: { items: [], + symbols: {}, isGathering: false, gatheringMessage: "Gathering Context", }, @@ -135,6 +138,12 @@ export const stateSlice = createSlice({ consumeMainEditorContent: (state) => { state.mainEditorContent = undefined; }, + updateFileSymbols: (state, action: PayloadAction) => { + state.context.symbols = Object.assign( + state.context.symbols, + action.payload, + ); + }, setContextItemsAtIndex: ( state, { @@ -440,6 +449,7 @@ export const memoizedContextItemsSelector = createSelector( ); export const { + updateFileSymbols, setContextItemsAtIndex, addContextItems, addContextItemsAtIndex, From 9d2fad9ad0ce5d43a6b69c7da9aea0d54c79ad81 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 16:30:40 -0800 Subject: [PATCH 03/54] 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 04/54] 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 05/54] 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 06/54] 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 07/54] 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 08/54] 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 09/54] 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 10/54] 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 11/54] 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 12/54] 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 13/54] 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 14/54] 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 15/54] 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 16/54] 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 17/54] 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 356a4b67c0fc4988851fa2706571c8dfc59ca988 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 01:09:50 -0800 Subject: [PATCH 18/54] stream aborter --- gui/src/components/Layout.tsx | 1 + gui/src/hooks/useChatHandler.ts | 17 ++++++++++------- gui/src/hooks/useHistory.tsx | 2 +- gui/src/hooks/useSetup.ts | 1 + gui/src/redux/slices/stateSlice.ts | 12 ++++++++++-- 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 42a1182e6..92dbdb4a6 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -21,6 +21,7 @@ import TextDialog from "./dialogs"; import Footer from "./Footer"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; +import { setInactive } from "../redux/slices/stateSlice"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 229c03ebc..bf6836107 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -23,6 +23,7 @@ import resolveEditorContent, { import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { + abortStream, addPromptCompletionPair, clearLastResponse, initNewActiveMessage, @@ -51,6 +52,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const history = useSelector((store: RootState) => store.state.history); const active = useSelector((store: RootState) => store.state.active); + const streamAborter = useSelector( + (store: RootState) => store.state.streamAborter, + ); const activeRef = useRef(active); const { saveSession } = useHistory(dispatch); @@ -65,7 +69,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { - const abortController = new AbortController(); + const abortController = streamAborter ?? new AbortController(); const cancelToken = abortController.signal; try { @@ -133,9 +137,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { selectedCode: RangeInFile[], contextItems: ContextItemWithId[], ) { - const abortController = new AbortController(); - const cancelToken = abortController.signal; - if (!defaultModel) { throw new Error("Default model not defined"); } @@ -144,7 +145,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const checkActiveInterval = setInterval(() => { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); clearInterval(checkActiveInterval); } }, 100); @@ -164,7 +165,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { cancelToken, )) { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); break; } if (typeof update === "string") { @@ -319,7 +320,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - return { streamResponse }; + return { + streamResponse, + }; } export default useChatHandler; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 911a2a014..e57253924 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,7 +7,7 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession, setInactive } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2d98b1011..eae4b0acc 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -126,6 +126,7 @@ function useSetup(dispatch: Dispatch) { dispatch(setConfigError(error)); }); + // TODO - remove? useWebviewListener("submitMessage", async (data) => { streamResponse( data.message, diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 4222b4693..469ef3ead 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -34,6 +34,7 @@ type State = { selectedProfileId: string; configError: ConfigValidationError[] | undefined; isInMultifileEdit: boolean; + streamAborter: AbortController; }; const initialState: State = { @@ -61,6 +62,7 @@ const initialState: State = { defaultModelTitle: "GPT-4", selectedProfileId: "local", isInMultifileEdit: false, + streamAborter: new AbortController(), }; export const stateSlice = createSlice({ @@ -239,6 +241,10 @@ export const stateSlice = createSlice({ state.isGatheringContext = false; state.active = false; }, + abortStream: (state) => { + state.streamAborter.abort(); + state.streamAborter = new AbortController(); + }, streamUpdate: (state, action: PayloadAction) => { if (state.history.length) { state.history[state.history.length - 1].message.content += @@ -249,16 +255,17 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { + state.active = false; + state.isGatheringContext = false; + state.isInMultifileEdit = false; if (payload) { state.history = payload.history as any; state.title = payload.title; state.sessionId = payload.sessionId; } else { state.history = []; - state.active = false; state.title = "New Session"; state.sessionId = v4(); - state.isInMultifileEdit = false; } }, addHighlightedCode: ( @@ -339,6 +346,7 @@ export const { deleteMessage, setIsGatheringContext, setIsInMultifileEdit, + abortStream, } = stateSlice.actions; export default stateSlice.reducer; From 022b7a7d7d90e58f467d057b506e79ebcbe6b0e1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 01:10:03 -0800 Subject: [PATCH 19/54] stream aborter p2 --- gui/src/hooks/useChatHandler.ts | 7 +++---- gui/src/hooks/useHistory.tsx | 12 ++++++++---- gui/src/redux/slices/stateSlice.ts | 3 +++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index bf6836107..75e9e428e 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -69,8 +69,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { - const abortController = streamAborter ?? new AbortController(); - const cancelToken = abortController.signal; + const cancelToken = streamAborter.signal; try { if (!defaultModel) { @@ -85,7 +84,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { while (!next.done) { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); break; } dispatch( @@ -162,7 +161,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { historyIndex, selectedCode, }, - cancelToken, + streamAborter.signal, )) { if (!activeRef.current) { dispatch(abortStream()); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index e57253924..03657d74d 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,7 +7,11 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession, setInactive } from "../redux/slices/stateSlice"; +import { + abortStream, + newSession, + setInactive, +} from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; @@ -121,9 +125,9 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } - const persistedSessionInfo = result.content; - dispatch(newSession(persistedSessionInfo)); - return persistedSessionInfo; + const sessionContent = result.content; + dispatch(newSession(sessionContent)); + return sessionContent; } async function loadLastSession(): Promise { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 469ef3ead..3caa424b8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -255,6 +255,9 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { + state.streamAborter.abort(); + state.streamAborter = new AbortController(); + state.active = false; state.isGatheringContext = false; state.isInMultifileEdit = false; From 32ee22bf700ec4d3b63a4b687418bb8595944342 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 01:14:08 -0800 Subject: [PATCH 20/54] stream aborter cleanup --- gui/src/components/Layout.tsx | 1 - gui/src/hooks/useChatHandler.ts | 4 +--- gui/src/hooks/useHistory.tsx | 6 +----- 3 files changed, 2 insertions(+), 9 deletions(-) diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 92dbdb4a6..42a1182e6 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -21,7 +21,6 @@ import TextDialog from "./dialogs"; import Footer from "./Footer"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; -import { setInactive } from "../redux/slices/stateSlice"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 75e9e428e..760948134 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -69,15 +69,13 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { - const cancelToken = streamAborter.signal; - try { if (!defaultModel) { throw new Error("Default model not defined"); } const gen = ideMessenger.llmStreamChat( defaultModel.title, - cancelToken, + streamAborter.signal, messages, ); let next = await gen.next(); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 03657d74d..8b9a93531 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,11 +7,7 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { - abortStream, - newSession, - setInactive, -} from "../redux/slices/stateSlice"; +import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; From 0ba023cd91858f7fd8b84e1143146d5ebe837fe9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 02:26:46 -0800 Subject: [PATCH 21/54] clickable symbols to code + working for js --- core/core.ts | 4 +- core/util/treeSitter.ts | 9 ++- gui/src/components/gui/StepContainer.tsx | 2 +- .../markdown/CodeSnippetPreview.tsx | 1 - .../markdown/StyledMarkdownPreview.tsx | 58 ++++++++++--------- gui/src/components/markdown/SymbolLink.tsx | 6 +- gui/src/redux/slices/stateSlice.ts | 6 +- gui/src/redux/store.ts | 7 ++- 8 files changed, 54 insertions(+), 39 deletions(-) diff --git a/core/core.ts b/core/core.ts index 53a2a068d..8825f235c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,7 +30,7 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; -import { getSymbolsForFiles } from "./util/treeSitter"; +import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; @@ -368,7 +368,7 @@ export class Core { on("context/getSymbolsForFiles", async (msg) => { const { uris } = msg.data; - return await getSymbolsForFiles(uris, this.ide); + return await getSymbolsForManyFiles(uris, this.ide); }); on("config/getSerializedProfileInfo", async (msg) => { diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 3b7a34c29..22a59e85c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -232,7 +232,7 @@ export async function getSymbolsForFile( } const tree = parser.parse(contents); - console.log(`file: ${filepath}`); + // console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) const symbols: SymbolWithRange[] = []; @@ -249,7 +249,10 @@ export async function getSymbolsForFile( // TODO use findLast in newer version of node target let identifier: Parser.SyntaxNode | undefined = undefined; for (let i = node.children.length - 1; i >= 0; i--) { - if (node.children[i].type === "identifier") { + if ( + node.children[i].type === "identifier" || + node.children[i].type === "property_identifier" + ) { identifier = node.children[i]; break; } @@ -280,7 +283,7 @@ export async function getSymbolsForFile( return symbols; } -export async function getSymbolsForFiles( +export async function getSymbolsForManyFiles( uris: string[], ide: IDE, ): Promise { diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 22523cfb2..613b98b5b 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -105,7 +105,7 @@ function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 39c09cfb6..639e14cc8 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -124,7 +124,6 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { source={`${fence}${getMarkdownLanguageTagForFile( props.item.description.split(" ")[0], )} ${props.item.description}\n${content}\n${fence}`} - contextItems={[props.item]} />
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index aca1cca2b..a2b55ba26 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect, useMemo } from "react"; +import { memo, useCallback, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -22,7 +22,6 @@ import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { RootState } from "../../redux/store"; import { SymbolWithRange } from "core"; import SymbolLink from "./SymbolLink"; -import { ContextItemWithId } from "core"; import { useSelector } from "react-redux"; const StyledMarkdown = styled.div<{ @@ -96,7 +95,7 @@ interface StyledMarkdownPreviewProps { className?: string; isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks scrollLocked?: boolean; - contextItems?: ContextItemWithId[]; + itemIndex?: number; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -116,14 +115,12 @@ function getLanuageFromClassName(className: any): string | null { function getCodeChildrenContent(children: any) { if (typeof children === "string") { - console.log(children); return children; } else if ( Array.isArray(children) && children.length > 0 && typeof children[0] === "string" ) { - console.log(children[0]); return children[0]; } return undefined; @@ -156,13 +153,20 @@ function processCodeBlocks(tree: any) { const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { + // Grab context items from the user history item before it + const contextItems = useSelector( + (state: RootState) => + state.state.history[props.itemIndex - 1]?.contextItems, + ); const symbols = useSelector((state: RootState) => state.state.symbols); + const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + if (!contextItems) { + return []; + } const contextUris = Array.from( new Set( - props.contextItems - .filter((item) => item?.uri) - .map((item) => item.uri!.value), + contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), ), ); const contextSymbols: SymbolWithRange[] = []; @@ -172,9 +176,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - console.log(contextSymbols.map((s) => s.name)); + console.log(contextSymbols); return contextSymbols; - }, [props.contextItems, symbols]); + }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -258,30 +262,30 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (props.contextItems) { - const ctxItem = props.contextItems.find((ctxItem) => + if (content && contextItems) { + const ctxItem = contextItems.find((ctxItem) => ctxItem.uri?.value.includes(content), ); + console.log("CTX item", ctxItem); if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; } - } - // console.log("content", content); - const exactSymbol = symbolsForContextItems.find( - (s) => s.name === content, - ); - if (exactSymbol) { - return ; - } - // PARTIAL - PARENTHESES - const partialSymbol = symbolsForContextItems.find( - (s) => false, - // content.startsWith(s.name), - ); - if (partialSymbol) { - return ; + const exactSymbol = symbolsForContextItems.find( + (s) => s.name === content, + ); + if (exactSymbol) { + return ; + } + + // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` + const partialSymbol = symbolsForContextItems.find((s) => + content.startsWith(s.name), + ); + if (partialSymbol) { + return ; + } } return {codeProps.children}; }, diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 84c1e8984..b18d302df 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,12 +20,12 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( - + {content} - + ); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8f46f50ec..460b55af8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -137,6 +137,7 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { + console.log("UPDATE SYMBOLS", action.payload); state.symbols = Object.assign(state.symbols, action.payload); }, setContextItemsAtIndex: ( @@ -254,7 +255,10 @@ export const stateSlice = createSlice({ if (!historyItem) { return; } - historyItem.contextItems.push(...payload.contextItems); + historyItem.contextItems = [ + ...historyItem.contextItems, + ...payload.contextItems, + ]; }, setInactive: (state) => { state.context.isGathering = false; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 221d275c9..0c92e7f26 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -40,7 +40,12 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", ["history", "sessionId", "defaultModelTitle"]), + createFilter("state", [ + "history", + "sessionId", + "defaultModelTitle", + "symbols", + ]), ]; const persistConfig = { From 1ef7087a8923a8c6cf7628b4fbf7d7ec1e2d20e8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 02:41:59 -0800 Subject: [PATCH 22/54] chat symbols cleanup --- core/index.d.ts | 1 - gui/src/components/mainInput/resolveInput.ts | 26 ------------------- .../markdown/StyledMarkdownPreview.tsx | 2 -- 3 files changed, 29 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 25d5c346d..c22a66aff 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -317,7 +317,6 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - contextSymbols?: SymbolWithRange[]; promptLogs?: PromptLog[]; } diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index a4598ae93..e8502d89c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -256,30 +256,4 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } -// export function hasSlashCommandOrContextProvider( -// editorState: JSONContent, -// ): boolean { -// if (!editorState.content) { -// return false; -// } - -// for (const p of editorState.content) { -// if (p.type === "paragraph" && p.content) { -// for (const child of p.content) { -// if (child.type === "slashcommand") { -// return true; -// } -// if ( -// child.type === "mention" && -// child.attrs?.itemType === "contextProvider" -// ) { -// return true; -// } -// } -// } -// } - -// return false; -// } - export default resolveEditorContent; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index a2b55ba26..29bef8c91 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -176,7 +176,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - console.log(contextSymbols); return contextSymbols; }, [contextItems, symbols]); @@ -266,7 +265,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const ctxItem = contextItems.find((ctxItem) => ctxItem.uri?.value.includes(content), ); - console.log("CTX item", ctxItem); if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; From 7a3f297b20cd1abe32dcd60b7bf5d6590f94eaff Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 03:10:39 -0800 Subject: [PATCH 23/54] fix symbols not rendering bug --- .../markdown/StyledMarkdownPreview.tsx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 29bef8c91..be438e408 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useEffect, useMemo } from "react"; +import { memo, useCallback, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -20,7 +20,7 @@ import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { RootState } from "../../redux/store"; -import { SymbolWithRange } from "core"; +import { ContextItemWithId, SymbolWithRange } from "core"; import SymbolLink from "./SymbolLink"; import { useSelector } from "react-redux"; @@ -153,17 +153,23 @@ function processCodeBlocks(tree: any) { const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { - // Grab context items from the user history item before it const contextItems = useSelector( (state: RootState) => state.state.history[props.itemIndex - 1]?.contextItems, ); const symbols = useSelector((state: RootState) => state.state.symbols); - const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + // The refs are a workaround because rehype options are stored on initiation + // So they won't use the most up-to-date state values + // So in this case we just put them in refs + const symbolsForContextItems = useRef([]); + const contextItemsRef = useRef([]); + useEffect(() => { + contextItemsRef.current = contextItems || []; if (!contextItems) { - return []; + symbolsForContextItems.current = []; } + // Get unique URIs and then find relevant symbols const contextUris = Array.from( new Set( contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), @@ -176,7 +182,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - return contextSymbols; + symbolsForContextItems.current = contextSymbols; }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ @@ -261,8 +267,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (content && contextItems) { - const ctxItem = contextItems.find((ctxItem) => + if (content && contextItemsRef.current) { + const ctxItem = contextItemsRef.current.find((ctxItem) => ctxItem.uri?.value.includes(content), ); if (ctxItem) { @@ -270,7 +276,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - const exactSymbol = symbolsForContextItems.find( + const exactSymbol = symbolsForContextItems.current.find( (s) => s.name === content, ); if (exactSymbol) { @@ -278,7 +284,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` - const partialSymbol = symbolsForContextItems.find((s) => + const partialSymbol = symbolsForContextItems.current.find((s) => content.startsWith(s.name), ); if (partialSymbol) { From f76c69dfda0ae439f16a5e28db48328dfabb9309 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 18 Nov 2024 12:23:43 -0800 Subject: [PATCH 24/54] chore: merge main --- core/llm/llms/Bedrock.ts | 11 ++++++-- .../StepContainer/StepContainer.tsx | 1 + gui/src/components/mainInput/resolveInput.ts | 26 +++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..9d9f3af87 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,6 +14,11 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +/** + * Bedrock class implements AWS Bedrock LLM integration. + * It handles streaming completions and chat messages using AWS Bedrock runtime. + * Supports both text and image inputs through Claude 3 models. + */ class Bedrock extends BaseLLM { static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { @@ -120,7 +125,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -162,7 +169,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index f5673e4e8..4fdd6eda2 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -93,6 +93,7 @@ export default function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index e8502d89c..4c7f4c640 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -256,4 +256,30 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } +export function hasSlashCommandOrContextProvider( + editorState: JSONContent, +): boolean { + if (!editorState.content) { + return false; + } + + for (const p of editorState.content) { + if (p.type === "paragraph" && p.content) { + for (const child of p.content) { + if (child.type === "slashcommand") { + return true; + } + if ( + child.type === "mention" && + child.attrs?.itemType === "contextProvider" + ) { + return true; + } + } + } + } + + return false; +} + export default resolveEditorContent; From 5fc0db9f54675d30eb1242b1966f1d17cdb2c71a Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 18 Nov 2024 12:45:24 -0800 Subject: [PATCH 25/54] Update stateSlice.ts --- gui/src/redux/slices/stateSlice.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 2cdd4e72e..8c0a8e759 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,7 +4,6 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, PersistedSessionInfo, PromptLog, @@ -12,9 +11,7 @@ import { 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"; import { ApplyState } from "core/protocol/ideWebview"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. @@ -36,10 +33,10 @@ type State = { configError: ConfigValidationError[] | undefined; checkpoints: Checkpoint[]; curCheckpointIndex: number; - isMultifileEdit: boolean; applyStates: ApplyState[]; nextCodeBlockToApplyIndex: number; streamAborter: AbortController; + isMultifileEdit: boolean; }; const initialState: State = { @@ -270,7 +267,7 @@ export const stateSlice = createSlice({ state.active = false; state.isGatheringContext = false; - state.isInMultifileEdit = false; + state.isMultifileEdit = false; if (payload) { state.history = payload.history as any; state.title = payload.title; @@ -365,7 +362,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, From d56b48cad2fcb0bb8e4a3e0dd3e32ab7f704d762 Mon Sep 17 00:00:00 2001 From: burlinchen Date: Tue, 19 Nov 2024 07:51:56 +0800 Subject: [PATCH 26/54] fix: add mistral model options to config schema --- extensions/vscode/config_schema.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 21fe76ccf..7761b605f 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -771,6 +771,9 @@ "starcoder-1b", "starcoder-3b", "starcoder2-3b", + "mistral-tiny", + "mistral-small", + "mistral-medium", "qwen2.5-coder:1.5b", "qwen2.5-coder:3b", "qwen2.5-coder:7b", From 0d0c6de7124a30f2edc088f0f92b747452c8060f Mon Sep 17 00:00:00 2001 From: Rahi Dehzani Date: Tue, 19 Nov 2024 17:20:55 +0100 Subject: [PATCH 27/54] Adding Go doc to Pre-Indexed Documentations --- core/indexing/docs/preIndexedDocs.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 01935af9e..99a8ddc8a 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -330,6 +330,12 @@ const preIndexedDocs: Record< startUrl: "https://llama-stack.readthedocs.io/", rootUrl: "https://llama-stack.readthedocs.io/", }, + "https://go.dev/doc": { + title: "Go", + startUrl: "https://go.dev/doc", + rootUrl: "https://go.dev", + faviconUrl: "https://go.dev/favicon.ico", + }, }; export default preIndexedDocs; From 416fdbb69ff17f3ab02f6d2b7dce0ea5a7db058c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 09:50:10 -0800 Subject: [PATCH 28/54] 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 32/54] 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 33/54] 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 c06c31edb31f6c1837ef9758f6e7161e75b34961 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 15:00:40 -0800 Subject: [PATCH 34/54] dont clear non-empty messages on error --- core/core.ts | 56 +++++++++-------- core/llm/llms/Anthropic.ts | 8 ++- gui/src/hooks/useChatHandler.ts | 99 +++++++++++++++--------------- gui/src/pages/gui/Chat.tsx | 9 +-- gui/src/redux/slices/stateSlice.ts | 15 +++-- 5 files changed, 96 insertions(+), 91 deletions(-) diff --git a/core/core.ts b/core/core.ts index 853666174..14db3517d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -540,33 +540,39 @@ export class Core { } }, 100); - for await (const content of slashCommand.run({ - input, - history, - llm, - contextItems, - params, - ide, - addContextItem: (item) => { - void messenger.request("addContextItem", { - item, - historyIndex, - }); - }, - selectedCode, - config, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - })) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - if (content) { - yield { content }; + try { + for await (const content of slashCommand.run({ + input, + history, + llm, + contextItems, + params, + ide, + addContextItem: (item) => { + void messenger.request("addContextItem", { + item, + historyIndex, + }); + }, + selectedCode, + config, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + })) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + clearInterval(checkActiveInterval); + break; + } + if (content) { + yield { content }; + } } + } catch (e) { + throw e; + } finally { + clearInterval(checkActiveInterval); } - clearInterval(checkActiveInterval); yield { done: true, content: "" }; } on("command/run", (msg) => diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8db42eefa..dfb3065cd 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -37,7 +37,9 @@ class Anthropic extends BaseLLM { public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI - const filteredmessages = msgs.filter((m) => m.role !== "system"); + const filteredmessages = msgs.filter( + (m) => m.role !== "system" && !!m.content, + ); const lastTwoUserMsgIndices = filteredmessages .map((msg, index) => (msg.role === "user" ? index : -1)) .filter((index) => index !== -1) @@ -146,7 +148,9 @@ class Anthropic extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} + if (value.type == "message_start") { + console.log(value); + } if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index ce599454d..02f44e1be 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -24,7 +24,7 @@ import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { addPromptCompletionPair, - clearLastResponse, + clearLastEmptyResponse, initNewActiveMessage, resubmitAtIndex, setCurCheckpointIndex, @@ -69,35 +69,27 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const abortController = new AbortController(); const cancelToken = abortController.signal; - try { - if (!defaultModel) { - throw new Error("Default model not defined"); + if (!defaultModel) { + throw new Error("Default model not defined"); + } + const gen = ideMessenger.llmStreamChat( + defaultModel.title, + cancelToken, + messages, + ); + let next = await gen.next(); + while (!next.done) { + if (!activeRef.current) { + abortController.abort(); + break; } - const gen = ideMessenger.llmStreamChat( - defaultModel.title, - cancelToken, - messages, - ); - let next = await gen.next(); + dispatch(streamUpdate(stripImages((next.value as ChatMessage).content))); + next = await gen.next(); + } - while (!next.done) { - if (!activeRef.current) { - abortController.abort(); - break; - } - dispatch( - streamUpdate(stripImages((next.value as ChatMessage).content)), - ); - next = await gen.next(); - } - - let returnVal = next.value as PromptLog; - if (returnVal) { - dispatch(addPromptCompletionPair([returnVal])); - } - } catch (e) { - // If there's an error, we should clear the response so there aren't two input boxes - dispatch(clearLastResponse()); + let returnVal = next.value as PromptLog; + if (returnVal) { + dispatch(addPromptCompletionPair([returnVal])); } } @@ -150,29 +142,35 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } }, 100); - for await (const update of ideMessenger.streamRequest( - "command/run", - { - input, - history: messages, - modelTitle, - slashCommandName: slashCommand.name, - contextItems, - params: slashCommand.params, - historyIndex, - selectedCode, - }, - cancelToken, - )) { - if (!activeRef.current) { - abortController.abort(); - break; - } - if (typeof update === "string") { - dispatch(streamUpdate(update)); + try { + for await (const update of ideMessenger.streamRequest( + "command/run", + { + input, + history: messages, + modelTitle, + slashCommandName: slashCommand.name, + contextItems, + params: slashCommand.params, + historyIndex, + selectedCode, + }, + cancelToken, + )) { + if (!activeRef.current) { + abortController.abort(); + clearInterval(checkActiveInterval); + break; + } + if (typeof update === "string") { + dispatch(streamUpdate(update)); + } } + } catch (e) { + throw e; + } finally { + clearInterval(checkActiveInterval); } - clearInterval(checkActiveInterval); } async function streamResponse( @@ -252,8 +250,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - // dispatch(addContextItems(contextItems)); - const message: ChatMessage = { role: "user", content, @@ -313,6 +309,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { ); } } catch (e: any) { + dispatch(clearLastEmptyResponse()); console.debug("Error streaming response: ", e); ideMessenger.post("showToast", [ "error", diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 345fe6f37..aee6d9416 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -41,7 +41,7 @@ import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { - clearLastResponse, + clearLastEmptyResponse, newSession, setInactive, } from "../../redux/slices/stateSlice"; @@ -399,12 +399,7 @@ export function Chat() { { dispatch(setInactive()); - if ( - state.history[state.history.length - 1]?.message.content - .length === 0 - ) { - dispatch(clearLastResponse()); - } + dispatch(clearLastEmptyResponse()); }} > {getMetaKeyLabel()} ⌫ Cancel diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 2d5cb1267..9c3292c1a 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -116,13 +116,16 @@ export const stateSlice = createSlice({ setIsGatheringContext: (state, { payload }: PayloadAction) => { state.isGatheringContext = payload; }, - clearLastResponse: (state) => { + clearLastEmptyResponse: (state) => { if (state.history.length < 2) { return; } - state.mainEditorContent = - state.history[state.history.length - 2].editorState; - state.history = state.history.slice(0, -2); + // Only clear in the case of an empty message + if (!state.history[state.history.length - 1]?.message.content.length) { + state.mainEditorContent = + state.history[state.history.length - 2].editorState; + state.history = state.history.slice(0, -2); + } }, consumeMainEditorContent: (state) => { state.mainEditorContent = undefined; @@ -354,7 +357,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, @@ -380,7 +383,7 @@ export const { setActive, initNewActiveMessage, setMessageAtIndex, - clearLastResponse, + clearLastEmptyResponse, consumeMainEditorContent, setSelectedProfileId, deleteMessage, From 1adbd9a456f6c4c2f56b78d6bd5e3b8737f60ec5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 19 Nov 2024 15:21:55 -0800 Subject: [PATCH 35/54] feat: use git diff, improve comment formatting --- core/autocomplete/CompletionProvider.ts | 23 +++++---- core/autocomplete/aggregateSnippets.ts | 45 +---------------- core/autocomplete/context/ranking/index.ts | 46 ----------------- core/autocomplete/templating/index.ts | 59 +++++++++++++--------- core/autocomplete/util/HelperVars.ts | 9 +++- core/config/types.ts | 2 +- core/index.d.ts | 2 +- core/util/parameters.ts | 4 +- extensions/vscode/src/util/ideUtils.ts | 19 +++---- packages/config-types/src/index.ts | 2 +- 10 files changed, 70 insertions(+), 141 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 381dc63b7..9fe11df79 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -176,17 +176,22 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let snippets = await aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ); - - const { prompt, prefix, suffix, completionOptions } = renderPrompt( - snippets, + const [snippets, diff, workspaceDirs] = await Promise.all([ + await aggregateSnippets( + helper, + extraSnippets, + this.contextRetrievalService, + ), + await this.ide.getDiff(true), await this.ide.getWorkspaceDirs(), + ]); + + const { prompt, prefix, suffix, completionOptions } = renderPrompt({ + snippets, + diff, + workspaceDirs, helper, - ); + }); // Completion let completion: string | undefined = ""; diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts index 90196de87..f47b9021f 100644 --- a/core/autocomplete/aggregateSnippets.ts +++ b/core/autocomplete/aggregateSnippets.ts @@ -1,10 +1,7 @@ -import { Position, Range } from "../index.js"; - import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, rankAndOrderSnippets, - removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; import { HelperVars } from "./util/HelperVars.js"; @@ -21,29 +18,6 @@ function filterSnippetsAlreadyInCaretWindow( ); } -function getRangeOfPrefixAndSuffixWithBuffer( - prefix: string, - suffix: string, - caretPos: Position, -): Range { - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: caretPos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: caretPos.line + suffixLines + buffer, - character: 0, - }, - }; - - return prefixSuffixRangeWithBuffer; -} - export async function aggregateSnippets( helper: HelperVars, extraSnippets: AutocompleteSnippet[], @@ -61,24 +35,7 @@ export async function aggregateSnippets( const scoredSnippets = rankAndOrderSnippets(snippets, helper); - // This might be redundant with filterSnippetsAlreadyInCaretWindow - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - getRangeOfPrefixAndSuffixWithBuffer( - helper.prunedPrefix, - helper.prunedSuffix, - helper.pos, - ), - ); - - // Filter snippets below similarity threshold - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - - finalSnippets = fillPromptWithSnippets( + const finalSnippets = fillPromptWithSnippets( scoredSnippets, helper.maxSnippetTokens, helper.modelName, diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index e761d994e..3e83afca5 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -153,24 +153,6 @@ export function fillPromptWithSnippets( return keptSnippets; } -function rangeIntersectionByLines(a: Range, b: Range): Range | null { - const startLine = Math.max(a.start.line, b.start.line); - const endLine = Math.min(a.end.line, b.end.line); - if (startLine >= endLine) { - return null; - } - return { - start: { - line: startLine, - character: 0, - }, - end: { - line: endLine, - character: 0, - }, - }; -} - /** * Remove one range from another range, which may lead to returning two disjoint ranges */ @@ -225,31 +207,3 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { } return [orig]; } - -export function removeRangeFromSnippets( - snippets: Required[], - filepath: string, - range: Range, -): Required[] { - const finalSnippets: Required[] = []; - for (const snippet of snippets) { - if (snippet.filepath !== filepath) { - finalSnippets.push(snippet); - continue; - } - - const intersection = rangeIntersectionByLines(range, snippet.range); - if (!intersection) { - finalSnippets.push(snippet); - } else { - finalSnippets.push( - ...rangeDifferenceByLines(snippet.range, intersection).map((range) => ({ - ...snippet, - range, - })), - ); - } - } - - return finalSnippets; -} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index d0d67db85..f847e3b2a 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -11,6 +11,7 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; +import { countTokens } from "../../llm/countTokens"; export function formatExternalSnippet( filepath: string, @@ -33,25 +34,17 @@ function getContextComments( snippets: AutocompleteSnippet[], lang: AutocompleteLanguageInfo, filepath: string, - prefix: string, - suffix: string, ) { - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - return `${formattedSnippets}\n\n`; - } + const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - const isEmptyFile = prefix.trim().length === 0 && suffix.trim().length === 0; - if (isEmptyFile) { - // Include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n`; - } + const formattedSnippets = + snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n") + fileNameSnippet; - return ""; + return formattedSnippets; } function getTemplate(helper: HelperVars): AutocompleteTemplate { @@ -85,11 +78,29 @@ function renderStringTemplate( }); } -export function renderPrompt( - snippets: AutocompleteSnippet[], - workspaceDirs: string[], - helper: HelperVars, -): { +const formatDiff = (helper: HelperVars, diff?: string) => { + if (!diff) return ""; + + const tokenCount = countTokens(diff, helper.modelName); + + if (tokenCount > helper.maxDiffTokens) { + return ""; + } + + return `${diff}\n\n`; +}; + +export function renderPrompt({ + snippets, + workspaceDirs, + helper, + diff, +}: { + snippets: AutocompleteSnippet[]; + workspaceDirs: string[]; + helper: HelperVars; + diff?: string; +}): { prompt: string; prefix: string; suffix: string; @@ -119,10 +130,10 @@ export function renderPrompt( snippets, helper.lang, helper.filepath, - prefix, - suffix, ); - prefix = `${contextComments}${prefix}`; + const formattedDiff = formatDiff(helper, diff); + + prefix = `${formattedDiff}${contextComments}${prefix}`; } const prompt = diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 2d9f74ab5..190e9b8ec 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -39,7 +39,9 @@ export class HelperVars { private async init() { // Don't do anything if already initialized - if (this._fileContents !== undefined) {return;} + if (this._fileContents !== undefined) { + return; + } this._fileContents = this.input.manuallyPassFileContents ?? @@ -115,6 +117,11 @@ export class HelperVars { get maxSnippetTokens() { return this.options.maxPromptTokens * this.options.maxSnippetPercentage; } + + get maxDiffTokens() { + return this.options.maxPromptTokens * this.options.maxDiffPercentage; + } + get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; } diff --git a/core/config/types.ts b/core/config/types.ts index ad80cdeab..370689dde 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -836,7 +836,7 @@ declare global { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/index.d.ts b/core/index.d.ts index c30119968..ca6c8482d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -937,7 +937,7 @@ export interface TabAutocompleteOptions { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 7a94abc03..269f3489e 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -11,8 +11,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, - maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. + maxSnippetPercentage: 0.5, + maxDiffPercentage: 0.5, useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 60fc6b72d..2ce332f02 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -21,7 +21,6 @@ import { uriFromFilePath, } from "./vscode"; - import type { FileEdit, RangeInFile, Thread } from "core"; const util = require("node:util"); @@ -181,7 +180,8 @@ export class VsCodeIdeUtils { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${VsCodeExtension.continueVirtualDocumentScheme + `${ + VsCodeExtension.continueVirtualDocumentScheme }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`, ), ) @@ -305,8 +305,8 @@ export class VsCodeIdeUtils { return `${lines .slice(range.start.line, range.end.line) .join("\n")}\n${lines[ - range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 - ].slice(0, range.end.character)}`; + range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 + ].slice(0, range.end.character)}`; } async getTerminalContents(commands = -1): Promise { @@ -572,7 +572,6 @@ export class VsCodeIdeUtils { async getDiff(includeUnstaged: boolean): Promise { let diffs: string[] = []; - let repos = []; for (const dir of this.getWorkspaceDirectories()) { const repo = await this.getRepo(vscode.Uri.file(dir)); @@ -580,20 +579,16 @@ export class VsCodeIdeUtils { continue; } - repos.push(repo.state.HEAD?.name); - const staged = await repo.diff(true); - diffs.push(`${staged}`); + diffs.push(staged); if (includeUnstaged) { const unstaged = await repo.diff(false); - diffs.push(`\n${unstaged}`); + diffs.push(unstaged); } } const fullDiff = diffs.join("\n\n"); - if (fullDiff.trim() === "") { - console.log(`Diff empty for repos: ${repos}`); - } + return fullDiff; } diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 4d989c127..a4ba53b8e 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -142,7 +142,7 @@ export const tabAutocompleteOptionsSchema = z.object({ slidingWindowPrefixPercentage: z.number(), slidingWindowSize: z.number(), maxSnippetPercentage: z.number(), - recentlyEditedSimilarityThreshold: z.number(), + maxDiffPercentage: z.number(), useCache: z.boolean(), onlyMyCode: z.boolean(), useOtherFiles: z.boolean(), From a830dca11d50596d9cd5f29df99c91b9fb630e45 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 19 Nov 2024 16:26:31 -0800 Subject: [PATCH 36/54] refactor: clean up code --- core/autocomplete/CompletionProvider.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 9fe11df79..f6b783be0 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -177,13 +177,9 @@ export class CompletionProvider { const extraSnippets = await this._getExtraSnippets(helper); const [snippets, diff, workspaceDirs] = await Promise.all([ - await aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ), - await this.ide.getDiff(true), - await this.ide.getWorkspaceDirs(), + aggregateSnippets(helper, extraSnippets, this.contextRetrievalService), + this.ide.getDiff(true), + this.ide.getWorkspaceDirs(), ]); const { prompt, prefix, suffix, completionOptions } = renderPrompt({ From 389b2c94c2f6ed178c109bb3872fd368c24155b5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 16:39:28 -0800 Subject: [PATCH 37/54] symbols bug fixes --- .../components/History/HistoryTableRow.tsx | 13 +++++-- gui/src/components/mainInput/resolveInput.ts | 19 ++--------- gui/src/components/markdown/FilenameLink.tsx | 4 +-- .../markdown/StyledMarkdownPreview.tsx | 32 ++++++----------- gui/src/components/markdown/SymbolLink.tsx | 4 +-- gui/src/hooks/useHistory.tsx | 15 ++++++-- gui/src/redux/slices/stateSlice.ts | 4 +-- gui/src/redux/store.ts | 7 +--- gui/src/util/symbols.ts | 34 +++++++++++++++++++ 9 files changed, 76 insertions(+), 56 deletions(-) create mode 100644 gui/src/util/symbols.ts diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 26107c199..695389c29 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,11 +1,12 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionInfo } from "core"; import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; import useHistory from "../../hooks/useHistory"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { RootState } from "../../redux/store"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -29,6 +30,9 @@ export function HistoryTableRow({ const [sessionTitleEditValue, setSessionTitleEditValue] = useState( session.title, ); + const currentSessionId = useSelector( + (state: RootState) => state.state.sessionId, + ); const { saveSession, deleteSession, loadSession, getSession, updateSession } = useHistory(dispatch); @@ -59,8 +63,11 @@ export function HistoryTableRow({ className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { // Save current session - await saveSession(); - await loadSession(session.sessionId); + if (session.sessionId !== currentSessionId) { + await saveSession(); + await loadSession(session.sessionId); + } + navigate("/"); }} > diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 4c7f4c640..a933bd1a3 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -14,6 +14,7 @@ import { setIsGatheringContext, updateFileSymbols, } from "../../redux/slices/stateSlice"; +import { updateFileSymbolsFromContextItems } from "../../util/symbols"; interface MentionAttrs { label: string; @@ -174,23 +175,7 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); - const contextItemFileUris = Array.from( - new Set( - contextItems - .filter((item) => item.uri?.type === "file" && item?.uri?.value) - .map((item) => item.uri.value), - ), - ); - - const symbolsResult = await ideMessenger.request( - "context/getSymbolsForFiles", - { - uris: contextItemFileUris, - }, - ); - if (symbolsResult.status === "success") { - dispatch(updateFileSymbols(symbolsResult.content)); - } + await updateFileSymbolsFromContextItems(contextItems, ideMessenger, dispatch); if (contextItemsText !== "") { contextItemsText += "\n"; diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 0d1166a00..d63bf8309 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,11 +21,11 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( - + {getBasename(rif.filepath)} diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 9ded0464f..ca1ea2afd 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -164,28 +164,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // The refs are a workaround because rehype options are stored on initiation // So they won't use the most up-to-date state values // So in this case we just put them in refs - const symbolsForContextItems = useRef([]); + const symbolsRef = useRef([]); const contextItemsRef = useRef([]); + useEffect(() => { contextItemsRef.current = contextItems || []; - if (!contextItems) { - symbolsForContextItems.current = []; - } - // Get unique URIs and then find relevant symbols - const contextUris = Array.from( - new Set( - contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), - ), - ); - const contextSymbols: SymbolWithRange[] = []; - contextUris.forEach((uri) => { - const fileSymbols = symbols[uri]; - if (fileSymbols) { - contextSymbols.push(...fileSymbols); - } - }); - symbolsForContextItems.current = contextSymbols; - }, [contextItems, symbols]); + }, [contextItems]); + useEffect(() => { + // Note, before I was only looking for symbols that matched + // Context item files on current history item + // but in practice global symbols for session makes way more sense + symbolsRef.current = Object.values(symbols).flat(); + }, [symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -278,7 +268,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - const exactSymbol = symbolsForContextItems.current.find( + const exactSymbol = symbolsRef.current.find( (s) => s.name === content, ); if (exactSymbol) { @@ -286,7 +276,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` - const partialSymbol = symbolsForContextItems.current.find((s) => + const partialSymbol = symbolsRef.current.find((s) => content.startsWith(s.name), ); if (partialSymbol) { diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index b18d302df..569a493e5 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,10 +20,10 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( - + {content} diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index f159ffea3..b52271ab4 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,9 +7,10 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession, updateFileSymbols } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; const MAX_TITLE_LENGTH = 100; @@ -22,7 +23,6 @@ function truncateText(text: string, maxLength: number) { function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootState) => state.state); - const defaultModel = useSelector(defaultModelSelector); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -122,7 +122,18 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } + const persistedSessionInfo = result.content; + + // Update file symbols on session load for all context items + await updateFileSymbolsFromContextItems( + persistedSessionInfo.history + .map((item) => item.contextItems ?? []) + .flat(), + ideMessenger, + dispatch, + ); + dispatch(newSession(persistedSessionInfo)); return persistedSessionInfo; } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c8abe266e..09735499f 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,7 +4,6 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, FileSymbolMap, PersistedSessionInfo, @@ -146,7 +145,6 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { - console.log("UPDATE SYMBOLS", action.payload); state.symbols = Object.assign(state.symbols, action.payload); }, setContextItemsAtIndex: ( @@ -379,7 +377,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 986075a84..725d88c01 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -39,12 +39,7 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", [ - "history", - "sessionId", - "defaultModelTitle", - "symbols", - ]), + createFilter("state", ["history", "sessionId", "defaultModelTitle"]), ]; const persistConfig = { diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts new file mode 100644 index 000000000..98848053a --- /dev/null +++ b/gui/src/util/symbols.ts @@ -0,0 +1,34 @@ +import { ContextItemWithId } from "core"; +import { IIdeMessenger } from "../context/IdeMessenger"; +import { updateFileSymbols } from "../redux/slices/stateSlice"; +import { Dispatch } from "@reduxjs/toolkit"; + +export async function updateFileSymbolsFromContextItems( + contextItems: ContextItemWithId[], + ideMessenger: IIdeMessenger, + dispatch: Dispatch, +) { + // Given a list of context items, + // Get unique file uris + try { + const contextUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri.value), + ), + ); + // And then update symbols for those files + if (contextUris.length > 0) { + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { uris: contextUris }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } + } + } catch (e) { + console.error("Error updating file symbols from context items", e); + } +} From 3f7daee8f30ee241cdf19cb16589865509c2e424 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 21:56:53 -0800 Subject: [PATCH 38/54] restore domain --- core/context/providers/GitHubIssuesContextProvider.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts index c0f25c12b..7bd64d860 100644 --- a/core/context/providers/GitHubIssuesContextProvider.ts +++ b/core/context/providers/GitHubIssuesContextProvider.ts @@ -24,6 +24,9 @@ class GitHubIssuesContextProvider extends BaseContextProvider { const octokit = new Octokit({ auth: this.options?.githubToken, + baseUrl: this.options?.domain + ? `https://${this.options.domain}/api/v3` + : undefined, request: { fetch: extras.fetch, }, From a9845386f054179651bd1e71e768175a3b873c2e Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 22:11:20 -0800 Subject: [PATCH 39/54] add pre-commit hook with husky --- .husky/pre-commit | 1 + .prettierignore | 13 +++++++++++++ package-lock.json | 16 ++++++++++++++++ package.json | 10 +++++++--- 4 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 .husky/pre-commit diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..d59df2ef6 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx prettier --write . \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index db326191f..15619929d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,17 @@ +binary/bin +binary/build +binary/out +binary/tmp +core/.continue-test +docs/.docusaurus +extensions/.continue-debug extensions/vscode/continue_rc_schema.json +extensions/vscode/.vscode-test +extensions/vscode/bin +extensions/vscode/build +extensions/vscode/out +gui/dist **/.continueignore CHANGELOG.md **/continue_tutorial.py +**/node_modules \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c147efa72..42ecd2cd8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" } @@ -1645,6 +1646,21 @@ "node": ">= 0.4" } }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", diff --git a/package.json b/package.json index 6d93be403..e5dbe76f2 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,12 @@ { "devDependencies": { - "prettier": "^3.3.3", - "prettier-plugin-tailwindcss": "^0.6.8", "@typescript-eslint/parser": "^7.8.0", - "eslint-plugin-import": "^2.29.1" + "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", + "prettier": "^3.3.3", + "prettier-plugin-tailwindcss": "^0.6.8" + }, + "scripts": { + "prepare": "husky" } } From f9883fbf095f398118ce06bae28672b83f06f00e Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 22:57:50 -0800 Subject: [PATCH 40/54] fix zh-CN links --- .../model-providers/top-level/vertexai.md | 2 +- .../current/actions/how-to-customize.md | 2 +- .../current/autocomplete/how-to-customize.md | 2 +- .../current/chat/model-setup.mdx | 2 +- .../customize/deep-dives/autocomplete.md | 2 +- .../customize/model-providers/more/nvidia.md | 52 ++ .../model-providers/top-level/vertexai.md | 65 +++ .../model-providers/top-level/xai.md | 53 +++ .../current/customize/overview.md | 4 +- .../current/edit/model-setup.md | 4 +- .../current/reference.md | 446 ++++++++++++++++++ 11 files changed, 625 insertions(+), 9 deletions(-) create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md index 1778ce3c6..50958cae0 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -27,7 +27,6 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. } ``` - ## Autocomplete model We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. @@ -43,6 +42,7 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo } } ``` + ## Embeddings model We recommend configuring **text-embedding-004** as your embeddings model. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 940fedc65..095d75918 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 ## 内置的斜杠命令 -Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。 +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。 ## 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md index 5e7b8fad2..aa2a04d5f 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -5,7 +5,7 @@ keywords: [定制] sidebar_position: 5 --- -Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: +Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: ```json title="config.json" "tabAutocompleteOptions": { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx index fe24f18fb..b95d976f1 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。 +这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。 ::: ## 最好的总体体验 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index ea07525ee..b85cfe323 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -44,7 +44,7 @@ ollama run starcoder2:3b } ``` -如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。 +如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。 ## 配置选项 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md new file mode 100644 index 000000000..049ff7754 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md @@ -0,0 +1,52 @@ +--- +title: NVIDIA +--- + +:::info + +[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. + +::: + +## Chat model + +We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Nemotron-4-340B-Instruct", + "provider": "nvidia", + "model": "nvidia-nemotron-4-340b-instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +NVIDIA currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } +} +``` + +## Reranking model + +NVIDIA currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md new file mode 100644 index 000000000..daf966d9e --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -0,0 +1,65 @@ +--- +title: Vertex AI +slug: ../vertexai +--- + +:::info + +You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). + +::: + +## Chat model + +We recommend configuring **Claude 3.5 Sonnet** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", + "projectId": "[PROJECT_ID]", + "region": "us-east5" + } + ] +} +``` + +## Autocomplete model + +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Codestral (Vertex AI)", + "provider": "vertexai", + "model": "codestral", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Embeddings model + +We recommend configuring **text-embedding-004** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "vertexai", + "model": "text-embedding-004", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Reranking model + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md new file mode 100644 index 000000000..fbdfa83ad --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md @@ -0,0 +1,53 @@ +--- +title: xAI +slug: ../xai +--- + +:::info + +You can get an API key from the [xAI console](https://console.x.ai/) + +::: + +## Chat model + +We recommend configuring **grok-beta** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Legacy Completions + +To force usage of `chat/completions` instead of `completions` endpoint you can set + +```json +"useLegacyCompletionsEndpoint": false +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md index 784c0bd59..f95574dae 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md @@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config ## 开始 -要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。 +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。 当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 ## 每个工作区的配置 -如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。 +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。 ## 可编程的配置 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md index f96a8fe6d..07a0a6c65 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md @@ -5,6 +5,6 @@ description: 如何设置一个编辑模型 keywords: [编辑, cmd l, 模型] --- -默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 +默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 -你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。 +你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md new file mode 100644 index 000000000..09dd150a6 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -0,0 +1,446 @@ +--- +title: Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). + +**All properties at all levels are optional unless explicitly marked required** + +### `models` + +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). +Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. + +**Properties:** + +- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. +- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. +- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere. +- `apiBase`: The base URL of the LLM API. +- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. +- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. +- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). +- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. +- `systemMessage`: A system message that will precede responses from the LLM. +- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. +- `apiType`: Specifies the type of API (`openai` or `azure`). +- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). +- `engine`: Engine for Azure OpenAI requests. +- `capabilities`: Override auto-detected capabilities: + - `uploadImage`: Boolean indicating if the model supports image uploads. + +_(AWS Only)_ + +- `profile`: AWS security profile for authorization. +- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). +- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). + +Example: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "AUTODETECT" + }, + { + "model": "gpt-4o", + "contextLength": 128000, + "title": "GPT-4o", + "provider": "openai", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +### `tabAutocompleteModel` + +Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. + +Example + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "My Starcoder", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +### `tabAutocompleteOptions` + +Specifies options for tab autocompletion behavior. + +**Properties:** + +- `disable`: If `true`, disables tab autocomplete (default: `false`). +- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. +- `useFileSuffix`: If `true`, includes file suffix in the prompt. +- `maxPromptTokens`: Maximum number of tokens for the prompt. +- `debounceDelay`: Delay (in ms) before triggering autocomplete. +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. +- `prefixPercentage`: Percentage of input for prefix. +- `template`: Template string for autocomplete, using Mustache templating. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). +- `useCache`: If `true`, caches completions. +- `onlyMyCode`: If `true`, only includes code within the repository. +- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +### `embeddingsProvider` + +Embeddings model settings - the model used for @Codebase and @docs. + +**Properties:** + +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc +- `model`: Model name for embeddings. +- `apiKey`: API key for the provider. +- `apiBase`: Base URL for API requests. +- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. +- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + +(AWS ONLY) + +- `region`: Specifies the region hosting the model. +- `profile`: AWS security profile. + +Example: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-ada-002", + "apiKey": "", + "maxChunkSize": 256, + "maxBatchSize": 5 + } +} +``` + +### `completionOptions` + +Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. + +**Properties:** + +- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). +- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. +- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. +- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. +- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. +- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). +- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. +- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). +- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. +- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). +- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. + +Example + +```json title="config.json" +{ + "completionOptions": { + "stream": false, + "temperature": 0.5 + } +} +``` + +### `requestOptions` + +Default HTTP request options that apply to all models and context providers, unless overridden at the model level. + +**Properties:** + +- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). +- `verifySsl`: Whether to verify SSL certificates for requests. +- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) +- `proxy`: Proxy URL to use for HTTP requests. +- `headers`: Custom headers for HTTP requests. +- `extraBodyProperties`: Additional properties to merge with the HTTP request body. +- `noProxy`: List of hostnames that should bypass the specified proxy. +- `clientCertificate`: Client certificate for HTTP requests. + + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +Example + +```json title="config.json" +{ + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } +} +``` + +### `reranker` + +Configuration for the reranker model used in response ranking. + +**Properties:** + +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `params`: + - `model`: Model name + - `apiKey`: Api key + +Example + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } +} +``` + +### `docs` + +List of documentation sites to index. + +**Properties:** + +- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL +- `maxDepth`: Maximum depth for crawling. Default `3` +- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). + +Example + +```json title="config.json" +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +### `analytics` + +Configuration for analytics tracking. + +**Properties:** + +- `provider`: Analytics provider (`"posthog"` or `"logstash"`). +- `url`: URL for analytics data. +- `clientKey`: Client key for analytics. + +### `slashCommands` + +Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. + +**Properties:** + +- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. +- `params`: Additional parameters to configure command behavior (command-specific - see code for command) + +Example: + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message" + }, + { + "name": "share", + "description": "Export this session as markdown" + }, + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `customCommands` + +User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. + +**Properties:** + +- `name`: The name of the custom command. +- `prompt`: Text prompt for the command. +- `description`: Brief description explaining the command's function. + +Example: + +```json title="config.json" +{ + "customCommands": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "Write unit tests for highlighted code" + } + ] +} +``` + +### `contextProviders` + +List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. + +**Properties:** + +- `name`: Name of the context provider, e.g. `docs` or `web` +- `params`: A context-provider-specific record of params to configure the context behavior + +Example + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code", + "params": {} + }, + { + "name": "docs", + "params": {} + }, + { + "name": "diff", + "params": {} + }, + { + "name": "open", + "params": {} + } + ] +} +``` + +### `disableSessionTitles` + +Prevents generating summary titles for each chat session when set to `true`. + +### `ui` + +Customizable UI settings to control interface appearance and behavior. + +**Properties:** + +- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. +- `fontSize`: Specifies font size for UI elements. +- `displayRawMarkdown`: If `true`, shows raw markdown in responses. +- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false + } +} +``` + +### `allowAnonymousTelemetry` + +When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. + +### `userToken` + +An optional token that identifies the user, primarily for authenticated services. + +### `systemMessage` + +Defines a system message that appears before every response from the language model, providing guidance or context. + +### `disableIndexing` + +Prevents indexing of the codebase, useful primarily for debugging purposes. + +### `experimental` + +Several experimental config parameters are available, as described below: + +`experimental`: + +- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= +- `modelRoles`: + - `inlineEdit`: Model title for inline edits. + - `applyCodeBlock`: Model title for applying code blocks. + - `repoMapFileSelection`: Model title for repo map selections. +- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. +- `promptPath`: Change the path to custom prompt files from the default ".prompts" +- `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. + - `prompt` (**required**): Prompt for quick action. + - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. +- `contextMenuPrompts`: + - `comment`: Prompt for commenting code. + - `docstring`: Prompt for adding docstrings. + - `fix`: Prompt for fixing code. + - `optimize`: Prompt for optimizing code. + - `fixGrammar`: Prompt for fixing grammar or spelling. +- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "promptPath": "custom/.prompts", + "quickActions": [ + { + "title": "Tags", + "prompt": "Return a list of any function and class names from the included code block", + "sendToChat": true + } + ], + "contextMenuPrompts": { + "fixGrammar": "Fix grammar in the above but allow for typos." + }, + "readResponseTTS": false, + "useChromiumForDocsCrawling": true + } +} +``` From 6013e6e0d551c14dbbe28fa1f11bcadc684e39a5 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:03:36 -0800 Subject: [PATCH 41/54] fix "ignore not defined" --- core/autocomplete/prefiltering/index.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index bc3b3bcaa..40ffa5384 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,5 +1,7 @@ import path from "node:path"; +import ignore from "ignore"; + import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; @@ -31,7 +33,7 @@ async function isDisabledForFile( } // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); + const pattern = ignore.default().add(disableInFiles); if (pattern.ignores(filepath)) { return true; } From ce7866b23823159d486ccc98628aa2249755f626 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:07:49 -0800 Subject: [PATCH 42/54] no predicted outputs for azure openai --- core/llm/llms/Azure.ts | 4 ++++ core/llm/llms/OpenAI.ts | 19 +++++++++---------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index 0daec0850..d563ca78e 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -5,6 +5,10 @@ import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { static providerName: ModelProvider = "azure"; + protected supportsPrediction(model: string): boolean { + return false; + } + static defaultOptions: Partial = { apiVersion: "2024-02-15-preview", apiType: "azure", diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 168e0afff..8498cd8cb 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,11 +95,8 @@ class OpenAI extends BaseLLM { ); } - private supportsPrediction(model: string): boolean { - return [ - "gpt-4o-mini", - "gpt-4o" - ].includes(model); + protected supportsPrediction(model: string): boolean { + return ["gpt-4o-mini", "gpt-4o"].includes(model); } protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { @@ -120,9 +117,9 @@ class OpenAI extends BaseLLM { : url.host === "api.deepseek.com" ? options.stop?.slice(0, 16) : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, }; @@ -143,10 +140,12 @@ class OpenAI extends BaseLLM { } if (options.prediction && this.supportsPrediction(options.model)) { - if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + if (finalOptions.presence_penalty) { + // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } - if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + if (finalOptions.frequency_penalty) { + // prediction doesn't support > 0 finalOptions.frequency_penalty = undefined; } finalOptions.max_completion_tokens = undefined; From 867d509263063bb7d29e0e9ffb8ae9a936ca897d Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:15:28 -0800 Subject: [PATCH 43/54] config.json reference --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 09dd150a6..7fefa4347 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,5 +1,5 @@ --- -title: Reference +title: `config.json` Reference description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- From ca78284986571717cb5af8746139d20b31e01680 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:17:43 -0800 Subject: [PATCH 44/54] oops --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 7fefa4347..f39e68998 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,5 +1,5 @@ --- -title: `config.json` Reference +title: config.json Reference description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- From 3b292cf732b73e9d4bd57354042ab165f1321a86 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:40:47 -0800 Subject: [PATCH 45/54] update symbols on load --- gui/src/hooks/useSetup.ts | 14 +++++++++++++- gui/src/redux/slices/stateSlice.ts | 10 ---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 593283849..6aeaae25c 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -19,9 +19,11 @@ import { isJetBrains } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; function useSetup(dispatch: Dispatch) { const ideMessenger = useContext(IdeMessengerContext); + const history = useSelector((store: RootState) => store.state.history); const initialConfigLoad = useRef(false); const loadConfig = useCallback(async () => { @@ -59,6 +61,17 @@ function useSetup(dispatch: Dispatch) { return () => clearInterval(interval); }, [initialConfigLoad, loadConfig]); + useEffect(() => { + // currently persist gate ensures that + // State.history is loaded before this is called + // Load symbols for chat on startup + updateFileSymbolsFromContextItems( + history.flatMap((item) => item.contextItems), + ideMessenger, + dispatch, + ); + }, []); + useEffect(() => { // Override persisted state dispatch(setInactive()); @@ -86,7 +99,6 @@ function useSetup(dispatch: Dispatch) { ); // IDE event listeners - const history = useSelector((store: RootState) => store.state.history); useWebviewListener( "getWebviewHistoryLength", async () => { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 09735499f..56bc9d7b5 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -387,16 +387,6 @@ export const stateSlice = createSlice({ }, }); -export const memoizedContextItemsSelector = createSelector( - [(state: RootState) => state.state.history], - (history) => { - return history.reduce((acc, item) => { - acc.push(...item.contextItems); - return acc; - }, []); - }, -); - export const { updateFileSymbols, setContextItemsAtIndex, From b80833158b430779dbc4141cc6dac68ab3b7b447 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:47:43 -0800 Subject: [PATCH 46/54] better styling on file and symbol links --- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/components/markdown/SymbolLink.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index d63bf8309..20b7c0343 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,7 +21,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 569a493e5..0dea98a28 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,7 +20,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( From f210faf09d36805f58ff3a843383d665027c036f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:57:11 -0800 Subject: [PATCH 47/54] chat symbols - active file working --- gui/src/components/mainInput/resolveInput.ts | 8 +------- gui/src/hooks/useChatHandler.ts | 7 ++++++- gui/src/hooks/useHistory.tsx | 3 +-- gui/src/pages/edit/index.tsx | 2 ++ gui/src/util/symbols.ts | 1 + 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index a933bd1a3..b12804d72 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -10,11 +10,7 @@ import { import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { - setIsGatheringContext, - updateFileSymbols, -} from "../../redux/slices/stateSlice"; -import { updateFileSymbolsFromContextItems } from "../../util/symbols"; +import { setIsGatheringContext } from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -175,8 +171,6 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); - await updateFileSymbolsFromContextItems(contextItems, ideMessenger, dispatch); - if (contextItemsText !== "") { contextItemsText += "\n"; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index b9342d4e9..a4aeb799e 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -37,6 +37,7 @@ import { import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import useHistory from "./useHistory"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const posthog = usePostHog(); @@ -256,7 +257,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - // dispatch(addContextItems(contextItems)); + await updateFileSymbolsFromContextItems( + selectedContextItems, + ideMessenger, + dispatch, + ); const message: ChatMessage = { role: "user", diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index b52271ab4..4bdd1e2c1 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -6,8 +6,7 @@ import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession, updateFileSymbols } from "../redux/slices/stateSlice"; +import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 2e93a16aa..26fbacbb1 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -177,6 +177,8 @@ function Edit() { dispatch, ); + // Note, not currently updating file symbols in edit mode + const prompt = [ ...contextItems.map((item) => item.content), stripImages(userInstructions), diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts index 98848053a..5c4e1be12 100644 --- a/gui/src/util/symbols.ts +++ b/gui/src/util/symbols.ts @@ -29,6 +29,7 @@ export async function updateFileSymbolsFromContextItems( } } } catch (e) { + // Catch all - don't want file symbols to break the chat experience for now console.error("Error updating file symbols from context items", e); } } From f5ab00d3ae0da78318af4e1463756a5d3be1f20c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 20 Nov 2024 00:02:50 -0800 Subject: [PATCH 48/54] chat symbols style tweaks --- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/components/markdown/SymbolLink.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 20b7c0343..161bd0b0a 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,7 +21,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 0dea98a28..45d54ba8f 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,7 +20,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( From f9c1b37c80b35aec65f4eb376ea4b965f098f37b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 20 Nov 2024 01:15:59 -0800 Subject: [PATCH 49/54] move update file symbols on load to use setup --- gui/src/hooks/useHistory.tsx | 9 --------- gui/src/hooks/useSetup.ts | 21 ++++++++++++--------- gui/src/redux/slices/stateSlice.ts | 7 +++++-- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 38aa5ec2b..e6feec628 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -9,7 +9,6 @@ import { useLastSessionContext } from "../context/LastSessionContext"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { updateFileSymbolsFromContextItems } from "../util/symbols"; const MAX_TITLE_LENGTH = 100; @@ -123,14 +122,6 @@ function useHistory(dispatch: Dispatch) { } const sessionContent = result.content; - - // Update file symbols on session load for all context items - await updateFileSymbolsFromContextItems( - sessionContent.history.map((item) => item.contextItems ?? []).flat(), - ideMessenger, - dispatch, - ); - dispatch(newSession(sessionContent)); return sessionContent; } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e95db68b3..ee80c36c3 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -61,16 +61,19 @@ function useSetup(dispatch: Dispatch) { return () => clearInterval(interval); }, [initialConfigLoad, loadConfig]); + // Load symbols for chat on any session change + const sessionId = useSelector((store: RootState) => store.state.sessionId); + const sessionIdRef = useRef(""); useEffect(() => { - // currently persist gate ensures that - // State.history is loaded before this is called - // Load symbols for chat on startup - updateFileSymbolsFromContextItems( - history.flatMap((item) => item.contextItems), - ideMessenger, - dispatch, - ); - }, []); + if (sessionIdRef.current !== sessionId) { + updateFileSymbolsFromContextItems( + history.flatMap((item) => item.contextItems), + ideMessenger, + dispatch, + ); + } + sessionIdRef.current = sessionId; + }, [sessionId, history, ideMessenger, dispatch]); useEffect(() => { // Override persisted state diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8f1906409..c0132cf41 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -145,7 +145,10 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { - state.symbols = Object.assign(state.symbols, action.payload); + state.symbols = { + ...state.symbols, + ...action.payload, + }; }, setContextItemsAtIndex: ( state, @@ -290,7 +293,7 @@ export const stateSlice = createSlice({ state.streamAborter = new AbortController(); state.active = false; - state.isGatheringContext = false; + state.context.isGathering = false; state.isMultifileEdit = false; if (payload) { state.history = payload.history as any; From 57b18d73d67bccbb0726b9170b3d1620c8402dcd Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Wed, 13 Nov 2024 16:20:57 +0100 Subject: [PATCH 50/54] Cancel stale completion requests as you type Signed-off-by: Fred Bricon --- .gitignore | 6 ++-- core/autocomplete/CompletionProvider.ts | 1 + .../generation/CompletionStreamer.ts | 6 ++-- .../generation/GeneratorReuseManager.test.ts | 2 +- .../generation/GeneratorReuseManager.ts | 8 +++-- .../generation/ListenableGenerator.ts | 4 +++ core/commands/index.ts | 2 +- core/commands/slash/cmd.ts | 4 ++- core/commands/slash/commit.ts | 2 +- core/commands/slash/draftIssue.ts | 4 +-- core/commands/slash/edit.ts | 6 ++-- core/commands/slash/multifileEdit.ts | 2 +- core/commands/slash/onboard.ts | 4 +-- core/commands/slash/review.ts | 2 +- core/config/promptFile.ts | 2 +- core/context/rerankers/llm.ts | 9 +++--- core/context/retrieval/repoMapRequest.ts | 2 +- core/core.ts | 3 ++ core/edit/lazy/replace.ts | 2 +- core/edit/lazy/streamLazyApply.ts | 2 +- core/edit/streamDiffLines.ts | 4 +-- core/index.d.ts | 12 ++++++- core/llm/index.ts | 32 +++++++++++++------ core/llm/llms/Anthropic.ts | 5 ++- core/llm/llms/Asksage.ts | 6 +++- core/llm/llms/Bedrock.ts | 6 ++-- core/llm/llms/BedrockImport.ts | 3 +- core/llm/llms/Cloudflare.ts | 4 +++ core/llm/llms/Cohere.ts | 5 ++- core/llm/llms/CustomLLM.ts | 9 +++++- core/llm/llms/Deepseek.ts | 2 ++ core/llm/llms/Flowise.ts | 5 ++- core/llm/llms/FreeTrial.ts | 6 ++++ core/llm/llms/Gemini.ts | 9 ++++++ core/llm/llms/HuggingFaceInferenceAPI.ts | 2 ++ core/llm/llms/HuggingFaceTGI.ts | 2 ++ core/llm/llms/LlamaCpp.ts | 2 ++ core/llm/llms/Mock.ts | 2 ++ core/llm/llms/Moonshot.ts | 2 ++ core/llm/llms/Ollama.ts | 10 ++++-- core/llm/llms/OpenAI.ts | 11 +++++++ core/llm/llms/Replicate.ts | 10 ++++-- core/llm/llms/SageMaker.ts | 6 ++-- core/llm/llms/Together.ts | 3 +- core/llm/llms/VertexAI.ts | 14 ++++++-- core/llm/llms/WatsonX.ts | 6 ++++ .../v1/slashCommandFromPromptFile.ts | 2 +- core/util/chatDescriber.ts | 1 + 48 files changed, 192 insertions(+), 62 deletions(-) diff --git a/.gitignore b/.gitignore index 106cef892..9621811de 100644 --- a/.gitignore +++ b/.gitignore @@ -142,7 +142,7 @@ codeql .tiktoken_cache -# IntelliJ Plugin +# IntelliJ Plugin **/**/.gradle **/**/.qodana **/**/build @@ -168,4 +168,6 @@ extensions/intellij/.idea/** **/.idea/shelf/ extensions/intellij/bin -extensions/.continue-debug/ \ No newline at end of file +extensions/.continue-debug/ + +*.vsix \ No newline at end of file diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f6b783be0..3cc1ce65c 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -29,6 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get(); const ERRORS_TO_IGNORE = [ // From Ollama "unexpected server status", + "operation was aborted" ]; export type GetLspDefinitionsFunction = ( diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index f516ad04b..d44957d15 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -25,10 +25,10 @@ export class CompletionStreamer { // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, - () => + (abortSignal: AbortSignal) => llm.supportsFim() - ? llm.streamFim(prefix, suffix, completionOptions) - : llm.streamComplete(prompt, { + ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) + : llm.streamComplete(prompt, abortSignal, { ...completionOptions, raw: true, }), diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts index 2454377d3..039059903 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.test.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -4,7 +4,7 @@ import { GeneratorReuseManager } from "./GeneratorReuseManager"; function createMockGenerator( data: string[], delay: number = 0, -): () => AsyncGenerator { +): (abortSignal: AbortSignal) => AsyncGenerator { const mockGenerator = async function* () { for (const chunk of data) { yield chunk; diff --git a/core/autocomplete/generation/GeneratorReuseManager.ts b/core/autocomplete/generation/GeneratorReuseManager.ts index 0b19183ce..e099b92f4 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -8,12 +8,13 @@ export class GeneratorReuseManager { constructor(private readonly onError: (err: any) => void) {} private _createListenableGenerator( + abortController: AbortController, gen: AsyncGenerator, prefix: string, ) { this.currentGenerator?.cancel(); - const listenableGen = new ListenableGenerator(gen, this.onError); + const listenableGen = new ListenableGenerator(gen, this.onError, abortController); listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? "")); this.pendingGeneratorPrefix = prefix; @@ -35,13 +36,14 @@ export class GeneratorReuseManager { async *getGenerator( prefix: string, - newGenerator: () => AsyncGenerator, + newGenerator: (abortSignal: AbortSignal) => AsyncGenerator, multiline: boolean, ): AsyncGenerator { // If we can't reuse, then create a new generator if (!this.shouldReuseExistingGenerator(prefix)) { // Create a wrapper over the current generator to fix the prompt - this._createListenableGenerator(newGenerator(), prefix); + const abortController = new AbortController(); + this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix); } // Already typed characters are those that are new in the prefix from the old generator diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts index 0cc9f664e..e6b36019b 100644 --- a/core/autocomplete/generation/ListenableGenerator.ts +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -3,16 +3,20 @@ export class ListenableGenerator { private _buffer: T[] = []; private _listeners: Set<(value: T) => void> = new Set(); private _isEnded = false; + private _abortController: AbortController constructor( source: AsyncGenerator, private readonly onError: (e: any) => void, + abortController: AbortController ) { this._source = source; + this._abortController = abortController; this._start(); } public cancel() { + this._abortController.abort(); this._isEnded = true; } diff --git a/core/commands/index.ts b/core/commands/index.ts index 806e918db..cb5e162f7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -58,7 +58,7 @@ export function slashFromCustomCommand( } } - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/cmd.ts b/core/commands/slash/cmd.ts index 00ba5b0de..1c3968172 100644 --- a/core/commands/slash/cmd.ts +++ b/core/commands/slash/cmd.ts @@ -24,7 +24,9 @@ const GenerateTerminalCommand: SlashCommand = { "${input}" -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`); +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, + new AbortController().signal + ); const lines = streamLines(gen); let cmd = ""; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 034e07e5e..7d5f22a90 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = { const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 25da6b559..268c68384 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -30,7 +30,7 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, { maxTokens: 20 }, ); @@ -43,7 +43,7 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { body += chunk.content; yield stripImages(chunk.content); } diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index fc71838df..78d86beee 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -478,7 +478,7 @@ const EditSlashCommand: SlashCommand = { messages = rendered; } - const completion = llm.streamComplete(rendered as string, { + const completion = llm.streamComplete(rendered as string, new AbortController().signal, { maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096), raw: true, }); @@ -494,7 +494,7 @@ const EditSlashCommand: SlashCommand = { ); } else { async function* gen() { - for await (const chunk of llm.streamChat(messages, { + for await (const chunk of llm.streamChat(messages, new AbortController().signal,{ temperature: 0.5, // TODO maxTokens: Math.min( maxTokens, @@ -609,7 +609,7 @@ ${lines.join("\n")} Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - for await (const update of llm.streamComplete(prompt)) { + for await (const update of llm.streamComplete(prompt, new AbortController().signal)) { yield update; } } diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index 740243a5a..c8cf64679 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -39,7 +39,7 @@ const MultiFileEditSlashCommand: SlashCommand = { const content = createPrompt(filesToEditStr, additionalContextStr, input); - for await (const chunk of llm.streamChat([{ role: "user", content }])) { + for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 8d3433c25..4d8aa3a38 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -47,7 +47,7 @@ const OnboardSlashCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, @@ -134,7 +134,7 @@ function createOnboardingPrompt(context: string): string { Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. Here is an example of a valid response: - + ## Important folders ### /folder1 diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 34859d94c..77357647a 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -45,7 +45,7 @@ const ReviewMessageCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: content }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index aa19f3b0c..1ec963513 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -125,7 +125,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } diff --git a/core/context/rerankers/llm.ts b/core/context/rerankers/llm.ts index 5396c8d9b..a673f5dc4 100644 --- a/core/context/rerankers/llm.ts +++ b/core/context/rerankers/llm.ts @@ -6,7 +6,7 @@ const RERANK_PROMPT = ( documentId: string, document: string, ) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. - + Query: Where is the FastAPI server? Snippet: \`\`\`/Users/andrew/Desktop/server/main.py @@ -17,7 +17,7 @@ const RERANK_PROMPT = ( return {{"Hello": "World"}} \`\`\` Relevant: Yes - + Query: Where in the documentation does it talk about the UI? Snippet: \`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs @@ -32,13 +32,13 @@ const RERANK_PROMPT = ( }} \`\`\` Relevant: No - + Query: ${query} Snippet: \`\`\`${documentId} ${document} \`\`\` - Relevant: + Relevant: `; export class LLMReranker implements Reranker { @@ -49,6 +49,7 @@ export class LLMReranker implements Reranker { async scoreChunk(chunk: Chunk, query: string): Promise { const completion = await this.llm.complete( RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), + new AbortController().signal, { maxTokens: 1, model: diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index e4b3e072e..8dc55df9d 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -61,7 +61,7 @@ This is the question that you should select relevant files for: "${input}"`; const response = await llm.chat([ { role: "user", content: prompt }, { role: "assistant", content: "" }, - ]); + ], new AbortController().signal); const content = stripImages(response.content); console.debug("Repo map retrieval response: ", content); diff --git a/core/core.ts b/core/core.ts index 853666174..b40eb8208 100644 --- a/core/core.ts +++ b/core/core.ts @@ -387,6 +387,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -428,6 +429,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -460,6 +462,7 @@ export class Core { const model = await this.configHandler.llmFromTitle(msg.data.title); const completion = await model.complete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); return completion; diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index e6c3183f0..26e174c17 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -86,7 +86,7 @@ export async function* getReplacementWithLlm( const completion = await llm.streamChat([ { role: "user", content: userPrompt }, { role: "assistant", content: assistantPrompt }, - ]); + ], new AbortController().signal); let lines = streamLines(completion); lines = filterLeadingNewline(lines); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 135aa3170..a5c85ee4d 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -23,7 +23,7 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat(promptMessages); + const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal); // Do find and replace over the lazy edit response async function* replacementFunction( diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index ca47f010d..5ecf273c5 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -96,8 +96,8 @@ export async function* streamDiffLines( const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true, prediction }) - : llm.streamChat(prompt, { + ? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction }) + : llm.streamChat(prompt, new AbortController().signal, { prediction, }); diff --git a/core/index.d.ts b/core/index.d.ts index ca6c8482d..392a9e11c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -78,26 +78,34 @@ export interface ILLM extends LLMOptions { region?: string; projectId?: string; - complete(prompt: string, options?: LLMFullCompletionOptions): Promise; + complete( + prompt: string, + signal: AbortSignal, + options?: LLMFullCompletionOptions + ): Promise; streamComplete( prompt: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamFim( prefix: string, suffix: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamChat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; chat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): Promise; @@ -388,11 +396,13 @@ export interface CustomLLMWithOptionals { options: LLMOptions; streamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; streamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; diff --git a/core/llm/index.ts b/core/llm/index.ts index d3148f833..1156120a6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -372,10 +372,11 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - console.debug( - `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, - ); - + if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + console.debug( + `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, + ); + } if ( e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") @@ -424,6 +425,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -432,6 +434,7 @@ export abstract class BaseLLM implements ILLM { async *streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log } = this._parseCompletionOptions(options); @@ -452,6 +455,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamFim( prefix, suffix, + signal, completionOptions, )) { completion += chunk; @@ -477,6 +481,7 @@ export abstract class BaseLLM implements ILLM { async *streamComplete( _prompt: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { const { completionOptions, log, raw } = @@ -506,6 +511,7 @@ export abstract class BaseLLM implements ILLM { try { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -527,7 +533,7 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, options: LLMFullCompletionOptions = {}) { + async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -551,7 +557,7 @@ export abstract class BaseLLM implements ILLM { } } - const completion = await this._complete(prompt, completionOptions); + const completion = await this._complete(prompt, signal, completionOptions); this._logTokensGenerated(completionOptions.model, prompt, completion); @@ -562,9 +568,9 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) { + async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { let completion = ""; - for await (const chunk of this.streamChat(messages, options)) { + for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } return { role: "assistant" as ChatMessageRole, content: completion }; @@ -572,6 +578,7 @@ export abstract class BaseLLM implements ILLM { async *streamChat( _messages: ChatMessage[], + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log, raw } = @@ -597,6 +604,7 @@ export abstract class BaseLLM implements ILLM { if (this.templateMessages) { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -605,6 +613,7 @@ export abstract class BaseLLM implements ILLM { } else { for await (const chunk of this._streamChat( messages, + signal, completionOptions, )) { completion += chunk.content; @@ -633,6 +642,7 @@ export abstract class BaseLLM implements ILLM { // biome-ignore lint/correctness/useYield: Purposefully not implemented protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -640,6 +650,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.templateMessages) { @@ -650,15 +661,16 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamComplete( this.templateMessages(messages), + signal, options, )) { yield { role: "assistant", content: chunk }; } } - protected async _complete(prompt: string, options: CompletionOptions) { + protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { let completion = ""; - for await (const chunk of this._streamComplete(prompt, options)) { + for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; } return completion; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8db42eefa..3f860511b 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -95,16 +95,18 @@ class Anthropic extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const shouldCacheSystemMessage = @@ -137,6 +139,7 @@ class Anthropic extends BaseLLM { ] : systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 85fb19184..74b1ddc27 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -98,6 +98,7 @@ class Asksage extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): Promise { if (typeof prompt !== "string" || prompt.trim() === "") { @@ -126,14 +127,16 @@ class Asksage extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { - const completion = await this._complete(prompt, options); + const completion = await this._complete(prompt, signal, options); yield completion; } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { const args = this._convertArgs(options, messages); @@ -142,6 +145,7 @@ class Asksage extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(args), + signal }); if (!response.ok) { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..01a0201eb 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -37,16 +37,18 @@ class Bedrock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -84,7 +86,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal}); if (response.stream) { for await (const chunk of response.stream) { diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 44a57205e..5726cd91e 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -37,6 +37,7 @@ class BedrockImport extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -51,7 +52,7 @@ class BedrockImport extends BaseLLM { const input = this._generateInvokeModelCommandInput(prompt, options); const command = new InvokeModelWithResponseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, {abortSignal: signal}); if (response.body) { for await (const item of response.body) { diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 93b9c4433..07e2e427c 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -16,6 +16,7 @@ export default class Cloudflare extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -35,6 +36,7 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), + signal }); for await (const value of streamSse(resp)) { @@ -46,10 +48,12 @@ export default class Cloudflare extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 83f255904..98135c7cc 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -46,16 +46,18 @@ class Cohere extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -73,6 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index d35dfabde..81d038f9d 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -13,12 +13,14 @@ class CustomLLMClass extends BaseLLM { private customStreamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; private customStreamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; @@ -31,18 +33,20 @@ class CustomLLMClass extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamChat) { for await (const content of this.customStreamChat( messages, + signal, options, (...args) => this.fetch(...args), )) { yield { role: "assistant", content }; } } else { - for await (const update of super._streamChat(messages, options)) { + for await (const update of super._streamChat(messages, signal, options)) { yield update; } } @@ -50,11 +54,13 @@ class CustomLLMClass extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamCompletion) { for await (const content of this.customStreamCompletion( prompt, + signal, options, (...args) => this.fetch(...args), )) { @@ -63,6 +69,7 @@ class CustomLLMClass extends BaseLLM { } else if (this.customStreamChat) { for await (const content of this.customStreamChat( [{ role: "user", content: prompt }], + signal, options, (...args) => this.fetch(...args), )) { diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index cfba34e85..177ac7efa 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -23,6 +23,7 @@ class Deepseek extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("beta/completions", this.apiBase); @@ -45,6 +46,7 @@ class Deepseek extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].text; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 0d9e617a0..ecca89d16 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -121,16 +121,18 @@ class Flowise extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; - for await (const chunk of this._streamChat([message], options)) { + for await (const chunk of this._streamChat([message], signal, options)) { yield stripImages(chunk.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); @@ -139,6 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), + signal }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 9f307d125..8f80c7418 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -60,6 +60,7 @@ class FreeTrial extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -73,6 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), + signal }); let completion = ""; @@ -103,6 +105,7 @@ class FreeTrial extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -120,6 +123,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), + signal }); let completion = ""; @@ -140,6 +144,7 @@ class FreeTrial extends BaseLLM { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -153,6 +158,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), + signal }); let completion = ""; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 2e33968d5..ada603240 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -46,10 +46,12 @@ class Gemini extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -72,6 +74,7 @@ class Gemini extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { // Ensure this.apiBase is used if available, otherwise use default @@ -89,6 +92,7 @@ class Gemini extends BaseLLM { if (options.model.includes("gemini")) { for await (const message of this.streamChatGemini( convertedMsgs, + signal, options, )) { yield message; @@ -96,6 +100,7 @@ class Gemini extends BaseLLM { } else { for await (const message of this.streamChatBison( convertedMsgs, + signal, options, )) { yield message; @@ -118,6 +123,7 @@ class Gemini extends BaseLLM { private async *streamChatGemini( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiURL = new URL( @@ -159,6 +165,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); let buffer = ""; @@ -211,6 +218,7 @@ class Gemini extends BaseLLM { } private async *streamChatBison( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const msgList = []; @@ -226,6 +234,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts index 21b607163..7e8d11c56 100644 --- a/core/llm/llms/HuggingFaceInferenceAPI.ts +++ b/core/llm/llms/HuggingFaceInferenceAPI.ts @@ -16,6 +16,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.apiBase) { @@ -36,6 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { stream: true, parameters: this._convertArgs(options), }), + signal }); async function* stream() { diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 9636dbc63..df84083dc 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -48,6 +48,7 @@ class HuggingFaceTGI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, prompt); @@ -60,6 +61,7 @@ class HuggingFaceTGI extends BaseLLM { "Content-Type": "application/json", }, body: JSON.stringify({ inputs: prompt, parameters: args }), + signal }, ); diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index e37b445e6..80ada3fdf 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -26,6 +26,7 @@ class LlamaCpp extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -42,6 +43,7 @@ class LlamaCpp extends BaseLLM { stream: true, ...this._convertArgs(options, prompt), }), + signal }); for await (const value of streamSse(resp)) { diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index e6097a60d..5f3880e3c 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -7,6 +7,7 @@ class Mock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { yield this.completion; @@ -14,6 +15,7 @@ class Mock extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for (const char of this.completion) { diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts index 022fa8af2..5a015dcca 100644 --- a/core/llm/llms/Moonshot.ts +++ b/core/llm/llms/Moonshot.ts @@ -23,6 +23,7 @@ class Moonshot extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("v1/chat/completions", this.apiBase); @@ -49,6 +50,7 @@ class Moonshot extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index a9ac7ab75..dcaa078ba 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -30,7 +30,7 @@ interface ModelFileParams { min_p?: number; // deprecated? num_thread?: number; - use_mmap?: boolean; + use_mmap?: boolean; num_gqa?: number; num_gpu?: number; } @@ -77,7 +77,6 @@ class Ollama extends BaseLLM { if (options.model === "AUTODETECT") { return; } - this.fetch(this.getEndpoint("api/show"), { method: "POST", headers: { @@ -262,6 +261,7 @@ class Ollama extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/generate"), { @@ -271,6 +271,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prompt)), + signal }); let buffer = ""; @@ -301,6 +302,7 @@ class Ollama extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/chat"), { @@ -310,6 +312,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getChatOptions(options, messages)), + signal }); let buffer = ""; @@ -348,8 +351,10 @@ class Ollama extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", headers: { @@ -357,6 +362,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), + signal }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 8498cd8cb..36abb746d 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -166,11 +166,13 @@ class OpenAI extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -199,10 +201,12 @@ class OpenAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -211,6 +215,7 @@ class OpenAI extends BaseLLM { protected async *_legacystreamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args: any = this._convertArgs(options, []); @@ -224,6 +229,7 @@ class OpenAI extends BaseLLM { ...args, stream: true, }), + signal }); for await (const value of streamSse(response)) { @@ -235,6 +241,7 @@ class OpenAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if ( @@ -246,6 +253,7 @@ class OpenAI extends BaseLLM { ) { for await (const content of this._legacystreamComplete( stripImages(messages[messages.length - 1]?.content || ""), + signal, options, )) { yield { @@ -266,6 +274,7 @@ class OpenAI extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(body), + signal }); // Handle non-streaming response @@ -285,6 +294,7 @@ class OpenAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); @@ -308,6 +318,7 @@ class OpenAI extends BaseLLM { "x-api-key": this.apiKey ?? "", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 414975ac4..59994cec1 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -41,11 +41,13 @@ class Replicate extends BaseLLM { private _convertArgs( options: CompletionOptions, prompt: string, - ): [`${string}/${string}:${string}`, { input: any }] { + signal: AbortSignal + ): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] { return [ Replicate.MODEL_IDS[options.model] || (options.model as any), { input: { prompt, message: prompt }, + signal }, ]; } @@ -57,9 +59,10 @@ class Replicate extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); const response = await this._replicate.run(model, args); return (response as any)[0]; @@ -67,9 +70,10 @@ class Replicate extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); for await (const event of this._replicate.stream(model, args)) { if (event.event === "output") { yield event.data; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index c88261941..edbda4d34 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -32,6 +32,7 @@ class SageMaker extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -45,7 +46,7 @@ class SageMaker extends BaseLLM { }); const toolkit = new CompletionAPIToolkit(this); const command = toolkit.generateCommand([], prompt, options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { @@ -82,6 +83,7 @@ class SageMaker extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -96,7 +98,7 @@ class SageMaker extends BaseLLM { const toolkit = new MessageAPIToolkit(this); const command = toolkit.generateCommand(messages, "", options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index f5b5f0bac..b0044c4a8 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -41,9 +41,10 @@ class Together extends OpenAI { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - for await (const chunk of this._legacystreamComplete(prompt, options)) { + for await (const chunk of this._legacystreamComplete(prompt,signal, options)) { yield chunk; } } diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index e945831e6..c17aac90d 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -49,7 +49,7 @@ class VertexAI extends BaseLLM { "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -307,6 +307,7 @@ class VertexAI extends BaseLLM { protected async *StreamFimMistral( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiBase = this.apiBase!; @@ -329,6 +330,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); for await (const chunk of streamSse(response)) { @@ -342,6 +344,7 @@ class VertexAI extends BaseLLM { protected async *streamFimGecko( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); @@ -363,6 +366,7 @@ class VertexAI extends BaseLLM { } }), + signal }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -373,6 +377,7 @@ class VertexAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const isV1API = this.apiBase.includes("/v1/"); @@ -396,10 +401,12 @@ class VertexAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -409,15 +416,16 @@ class VertexAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.model === "code-gecko") { - yield* this.streamFimGecko(prefix, suffix, options); + yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { - yield* this.StreamFimMistral(prefix, suffix, options); + yield* this.StreamFimMistral(prefix, suffix, signal, options); } else { throw new Error(`Unsupported model: ${this.model}`); } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 89a2d13dc..808557692 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -140,11 +140,13 @@ class WatsonX extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -155,10 +157,12 @@ class WatsonX extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -167,6 +171,7 @@ class WatsonX extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { var now = new Date().getTime() / 1000; @@ -219,6 +224,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), + signal }); if (!response.ok || response.body === null) { diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 4b77360fe..9e4f0c194 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -90,7 +90,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 5f3d1bdc1..b8ca609a2 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -52,6 +52,7 @@ export class ChatDescriber { content: ChatDescriber.prompt + message, }, ], + new AbortController().signal, completionOptions, ); From e60341647fcf9834844ad7ef4d5aa44fe1edf801 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 08:50:24 -0800 Subject: [PATCH 51/54] bump version --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 697bf61c1..ef2d12c82 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.231", + "version": "0.9.232", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From a20374299ac6f70f5cc26bdf16690f8681e78757 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 10:25:25 -0800 Subject: [PATCH 52/54] 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}; From eb4030207f41ee68f3e6de433b1d0023d2b030b8 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 10:31:49 -0800 Subject: [PATCH 53/54] clear symbols on new session --- gui/src/redux/slices/stateSlice.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c0132cf41..29fee95d3 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -12,8 +12,8 @@ import { import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { v4 as uuidv4, v4 } from "uuid"; import { ApplyState } from "core/protocol/ideWebview"; +import { v4 as uuidv4, v4 } from "uuid"; // 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. @@ -295,6 +295,7 @@ export const stateSlice = createSlice({ state.active = false; state.context.isGathering = false; state.isMultifileEdit = false; + state.symbols = {}; if (payload) { state.history = payload.history as any; state.title = payload.title; From d909621a9337ffd6eae5970c64c33b32c1e0b91a Mon Sep 17 00:00:00 2001 From: Ari Roffe Date: Wed, 20 Nov 2024 15:23:25 -0600 Subject: [PATCH 54/54] Update context-providers.md --- docs/docs/customize/context-providers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index e582beb1b..a423ff4dc 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -291,7 +291,7 @@ Reference the conversation in a Jira issue. "name": "jira", "params": { "domain": "company.atlassian.net", - "token ": "ATATT..." + "token": "ATATT..." } } ]