From e9f85b6b330489c646ca84c4679eea63b5fd9916 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 5 Dec 2024 12:48:38 -0800 Subject: [PATCH 01/14] recommend voyage-code-3 --- core/indexing/embeddings/VoyageEmbeddingsProvider.ts | 2 +- docs/docs/customize/model-types/embeddings.md | 4 ++-- docs/docs/customize/tutorials/custom-code-rag.md | 8 ++++---- .../current/customize/model-types/embeddings.md | 4 ++-- .../current/customize/tutorials/custom-code-rag.md | 8 ++++---- packages/llm-info/src/providers/voyage.ts | 5 +++++ packages/openai-adapters/test/main.test.ts | 2 +- 7 files changed, 19 insertions(+), 14 deletions(-) diff --git a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts index df78f401b..95da27982 100644 --- a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts +++ b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts @@ -7,7 +7,7 @@ class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider { static defaultOptions: Partial | undefined = { apiBase: "https://api.voyageai.com/v1/", - model: "voyage-code-2", + model: "voyage-code-3", }; } diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index 882c5da79..137f6c260 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -19,7 +19,7 @@ The free trial supports embeddings (provider: `free-trial`) ## Recommended embedding models -If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. +If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models. If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.md#embeddings-model). @@ -31,7 +31,7 @@ After obtaining an API key from [here](https://www.voyageai.com/), you can confi { "embeddingsProvider": { "provider": "voyage", - "model": "voyage-code-2", + "model": "voyage-code-3", "apiKey": "" } } diff --git a/docs/docs/customize/tutorials/custom-code-rag.md b/docs/docs/customize/tutorials/custom-code-rag.md index acd778b91..b6f1cc251 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.md +++ b/docs/docs/customize/tutorials/custom-code-rag.md @@ -4,7 +4,7 @@ While Continue comes with [@Codebase](../deep-dives/codebase.md) out of the box, ## Step 1: Choose an embeddings model -If possible, we recommend using [`voyage-code-2`](https://docs.voyageai.com/docs/embeddings), which will give the most accurate answers of any existing embeddings model for code. You can obtain an API key [here](https://dash.voyageai.com/api-keys). Because their API is [OpenAI-compatible](https://docs.voyageai.com/reference/embeddings-api), you can use any OpenAI client by swapping out the URL. +If possible, we recommend using [`voyage-code-3`](https://docs.voyageai.com/docs/embeddings), which will give the most accurate answers of any existing embeddings model for code. You can obtain an API key [here](https://dash.voyageai.com/api-keys). Because their API is [OpenAI-compatible](https://docs.voyageai.com/reference/embeddings-api), you can use any OpenAI client by swapping out the URL. ## Step 2: Choose a vector database @@ -16,7 +16,7 @@ There are a number of available vector databases, but because most vector databa Most embeddings models can only handle a limited amount of text at once. To get around this, we "chunk" our code into smaller pieces. -If you use `voyage-code-2`, it has a maximum context length of 16,000 tokens, which is enough to fit most files. This means that in the beginning you can get away with a more naive strategy of truncating files that exceed the limit. In order of easiest to most comprehensive, 3 chunking strategies you can use are: +If you use `voyage-code-3`, it has a maximum context length of 16,000 tokens, which is enough to fit most files. This means that in the beginning you can get away with a more naive strategy of truncating files that exceed the limit. In order of easiest to most comprehensive, 3 chunking strategies you can use are: 1. Truncate the file when it goes over the context length: in this case you will always have 1 chunk per file. 2. Split the file into chunks of a fixed length: starting at the top of the file, add lines you your current chunk until it reaches the limit, then start a new chunk. @@ -40,7 +40,7 @@ from lancedb.embeddings import get_registry db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create( - name="voyage-code-2", + name="voyage-code-3", base_url="https://api.voyageai.com/v1/", api_key=os.environ["VOYAGE_API_KEY"], ) @@ -48,7 +48,7 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-2` model. + # 1536 is the embedding dimension of the `voyage-code-3` model. vector: Vector(1536) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md index eb73c3ad4..d5534b62a 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md @@ -11,7 +11,7 @@ sidebar_position: 3 ## 推荐的嵌入模型 -如果你有使用任何模型的能力,我们推荐 `voyage-code-2` ,它独立列在下面,和其他的嵌入模型选项一起。 +如果你有使用任何模型的能力,我们推荐 `voyage-code-3` ,它独立列在下面,和其他的嵌入模型选项一起。 如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#嵌入模型) 使用 `nomic-embed-text` 。 @@ -23,7 +23,7 @@ sidebar_position: 3 { "embeddingsProvider": { "provider": "voyage", - "model": "voyage-code-2", + "model": "voyage-code-3", "apiKey": "" } } diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md index 118e7945d..311d20d34 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md @@ -4,7 +4,7 @@ ## 步骤 1 :选择嵌入模型 -如果可能,我们推荐使用 [`voyage-code-2`](https://docs.voyageai.com/docs/embeddings) ,它将给出最准确的答案,关于任何已存的代码嵌入模型。你可以在 [这里](https://dash.voyageai.com/api-keys) 获取 API key 。因为他门的 API 是 [OpenAI-兼容的](https://docs.voyageai.com/reference/embeddings-api) ,你可以使用任何 OpenAI 客户端换出 URL 。 +如果可能,我们推荐使用 [`voyage-code-3`](https://docs.voyageai.com/docs/embeddings) ,它将给出最准确的答案,关于任何已存的代码嵌入模型。你可以在 [这里](https://dash.voyageai.com/api-keys) 获取 API key 。因为他门的 API 是 [OpenAI-兼容的](https://docs.voyageai.com/reference/embeddings-api) ,你可以使用任何 OpenAI 客户端换出 URL 。 ## 步骤 2 :选择向量模型 @@ -16,7 +16,7 @@ 大多数嵌入模型只能一次处理有限的文本数量。为了解决这个问题,我们 "分块" 我们的代码到较小的部分。 -如果你使用 `voyage-code-2` ,它可以有最大 16,000 token 上下文长度,足够容纳大多数文件。这意味着,在开始的时候,你可以使用更朴素的策略避免超过限制。为了最简单到最综合,你可以使用 3 分块策略: +如果你使用 `voyage-code-3` ,它可以有最大 16,000 token 上下文长度,足够容纳大多数文件。这意味着,在开始的时候,你可以使用更朴素的策略避免超过限制。为了最简单到最综合,你可以使用 3 分块策略: 1. 截断文件,当它超过上下文长度:在这种情况下,你总是每个文件有 1 个分块。 2. 拆分文件到一个固定长度的分块:从文件的最上面开始,添加你当前分块的行,直到它到达限制,然后开始一个新的分块。 @@ -42,7 +42,7 @@ from lancedb.embeddings import get_registry db = lancedb.connect("/tmp/db") func = get_registry().get("openai").create( - name="voyage-code-2", + name="voyage-code-3", base_url="https://api.voyageai.com/v1/", api_key=os.environ["VOYAGE_API_KEY"], ) @@ -50,7 +50,7 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-2` model. + # 1536 is the embedding dimension of the `voyage-code-3` model. vector: Vector(1536) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") diff --git a/packages/llm-info/src/providers/voyage.ts b/packages/llm-info/src/providers/voyage.ts index 9bc5f6250..dc89305d4 100644 --- a/packages/llm-info/src/providers/voyage.ts +++ b/packages/llm-info/src/providers/voyage.ts @@ -6,6 +6,11 @@ export const Voyage: ModelProvider = { model: "voyage-code-2", displayName: "Voyage Code 2", contextLength: 8096, + }, + { + model: "voyage-code-3", + displayName: "Voyage Code 3", + contextLength: 8096, recommendedFor: ["embed"], }, { diff --git a/packages/openai-adapters/test/main.test.ts b/packages/openai-adapters/test/main.test.ts index efe8cc7c5..7dc73c489 100644 --- a/packages/openai-adapters/test/main.test.ts +++ b/packages/openai-adapters/test/main.test.ts @@ -303,7 +303,7 @@ const EMBEDDINGS_TESTS: LlmApiConfig[] = [ }, { provider: "openai", - model: "voyage-code-2", + model: "voyage-code-3", apiKey: process.env.VOYAGE_API_KEY!, apiBase: "https://api.voyageai.com/v1/", }, From 23c48080bed24574d8e67e3e4ac7a3a336fa2d80 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 10:17:09 -0800 Subject: [PATCH 02/14] handleStreamErrors --- extensions/vscode/package-lock.json | 4 +- gui/src/components/mainInput/TipTapEditor.tsx | 1 + gui/src/redux/thunks/handleErrors.ts | 9 +- gui/src/redux/thunks/index.ts | 2 +- gui/src/redux/thunks/streamNormalInput.ts | 113 +++++++++--------- gui/src/redux/thunks/streamResponse.ts | 5 +- .../thunks/streamResponseAfterToolCall.ts | 4 +- 7 files changed, 68 insertions(+), 70 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 923f4c9b5..ea5966c13 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.244", + "version": "0.9.240", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.244", + "version": "0.9.240", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index bf6a65b85..b2c64f8c6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -304,6 +304,7 @@ function TipTapEditor(props: TipTapEditorProps) { const mainEditorContent = useAppSelector( (store) => store.session.mainEditorContent, ); + console.log("MAIN EDITOR", mainEditorContent?.content); const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/handleErrors.ts index b0beef06f..7e6d99f49 100644 --- a/gui/src/redux/thunks/handleErrors.ts +++ b/gui/src/redux/thunks/handleErrors.ts @@ -1,17 +1,18 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { setInactive } from "../slices/sessionSlice"; +import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -export const handleErrors = createAsyncThunk< +export const handleStreamErrors = createAsyncThunk< void, () => Promise, ThunkApiType ->("chat/handleErrors", async (runStream, { dispatch, extra }) => { +>("chat/handleStreamErrors", async (runStream, { dispatch, extra }) => { try { await runStream(); } catch (e: any) { - console.debug("Error streaming response: ", e); + console.error("Error streaming response: ", e); } finally { + dispatch(clearLastEmptyResponse()); dispatch(setInactive()); // triggerSave(!save); TODO } diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index c35189de3..d5445d09d 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -1,6 +1,6 @@ export { exitEditMode } from "./exitEditMode"; export { gatherContext } from "./gatherContext"; -export { handleErrors } from "./handleErrors"; +export { handleStreamErrors } from "./handleErrors"; export { resetStateForNewMessage } from "./resetStateForNewMessage"; export { streamNormalInput } from "./streamNormalInput"; export { streamResponseThunk } from "./streamResponse"; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 5a22a36b5..88df9d65f 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -17,70 +17,65 @@ export const streamNormalInput = createAsyncThunk< ChatMessage[], ThunkApiType >("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => { - try { - // Gather state - const state = getState(); - const defaultModel = selectDefaultModel(state); - const toolSettings = state.ui.toolSettings; - const streamAborter = state.session.streamAborter; - const useTools = state.ui.useTools; + // Gather state + const state = getState(); + const defaultModel = selectDefaultModel(state); + const toolSettings = state.ui.toolSettings; + const streamAborter = state.session.streamAborter; + const useTools = state.ui.useTools; - if (!defaultModel) { - throw new Error("Default model not defined"); + if (!defaultModel) { + throw new Error("Default model not defined"); + } + + // Send request + const gen = extra.ideMessenger.llmStreamChat( + defaultModel.title, + streamAborter.signal, + messages, + { + tools: useTools + ? Object.keys(toolSettings) + .filter((tool) => toolSettings[tool] !== "disabled") + .map((toolName) => + state.config.config.tools.find( + (tool) => tool.function.name === toolName, + ), + ) + .filter(Boolean) + : undefined, + }, + ); + + // Stream response + let next = await gen.next(); + while (!next.done) { + if (!getState().session.isStreaming) { + dispatch(abortStream()); + break; } - // Send request - const gen = extra.ideMessenger.llmStreamChat( - defaultModel.title, - streamAborter.signal, - messages, - { - tools: useTools - ? Object.keys(toolSettings) - .filter((tool) => toolSettings[tool] !== "disabled") - .map((toolName) => - state.config.config.tools.find( - (tool) => tool.function.name === toolName, - ), - ) - .filter(Boolean) - : undefined, - }, - ); + const updates = next.value as ChatMessage[]; + dispatch(streamUpdate(updates)); + next = await gen.next(); + } - // Stream response - let next = await gen.next(); - while (!next.done) { - if (!getState().session.isStreaming) { - dispatch(abortStream()); - break; - } + // Attach prompt log + let returnVal = next.value as PromptLog; + if (returnVal) { + dispatch(addPromptCompletionPair([returnVal])); + } - const updates = next.value as ChatMessage[]; - dispatch(streamUpdate(updates)); - next = await gen.next(); + // If it's a tool call that is automatically accepted, we should call it + const toolCallState = selectCurrentToolCall(getState()); + if (toolCallState) { + dispatch(setToolGenerated()); + + if ( + toolSettings[toolCallState.toolCall.function.name] === + "allowedWithoutPermission" + ) { + await dispatch(callTool()); } - - // Attach prompt log - let returnVal = next.value as PromptLog; - if (returnVal) { - dispatch(addPromptCompletionPair([returnVal])); - } - - // If it's a tool call that is automatically accepted, we should call it - const toolCallState = selectCurrentToolCall(getState()); - if (toolCallState) { - dispatch(setToolGenerated()); - - if ( - toolSettings[toolCallState.toolCall.function.name] === - "allowedWithoutPermission" - ) { - await dispatch(callTool()); - } - } - } catch (e) { - // If there's an error, we should clear the response so there aren't two input boxes - dispatch(clearLastEmptyResponse()); } }); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 1ee3d65d5..0103e57df 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -18,7 +18,7 @@ import { } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { gatherContext } from "./gatherContext"; -import { handleErrors } from "./handleErrors"; +import { handleStreamErrors } from "./handleErrors"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamSlashCommand } from "./streamSlashCommand"; @@ -66,7 +66,8 @@ export const streamResponseThunk = createAsyncThunk< { dispatch, extra, getState }, ) => { await dispatch( - handleErrors(async () => { + handleStreamErrors(async () => { + throw new Error("intentional"); const state = getState(); const defaultModel = selectDefaultModel(state); const slashCommands = state.config.config.slashCommands || []; diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 52b15c13f..c516592e1 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -9,7 +9,7 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { handleErrors } from "./handleErrors"; +import { handleStreamErrors } from "./handleErrors"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; @@ -24,7 +24,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< "chat/streamAfterToolCall", async ({ toolCallId, toolOutput }, { dispatch, getState }) => { await dispatch( - handleErrors(async () => { + handleStreamErrors(async () => { const state = getState(); const initialHistory = state.session.history; const defaultModel = selectDefaultModel(state); From c73657a3a9986bba8e82f330cb23192439c5c702 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 14:33:39 -0800 Subject: [PATCH 03/14] (BROKEN COMMIT) editor content tinkering --- core/core.ts | 5 +- .../components/mainInput/ContinueInputBox.tsx | 18 -- gui/src/components/mainInput/TipTapEditor.tsx | 28 ++- gui/src/hooks/useNavigationListener.tsx | 1 - gui/src/hooks/useSetup.ts | 6 +- gui/src/redux/slices/sessionSlice.ts | 164 ++++++++---------- gui/src/redux/thunks/handleErrors.ts | 1 + gui/src/redux/thunks/streamResponse.ts | 41 ++--- 8 files changed, 116 insertions(+), 148 deletions(-) diff --git a/core/core.ts b/core/core.ts index 4dce3ca64..519b4c755 100644 --- a/core/core.ts +++ b/core/core.ts @@ -366,7 +366,6 @@ export class Core { msg: Message, ) { const config = await configHandler.loadConfig(); - // Stop TTS on new StreamChat if (config.experimental?.readResponseTTS) { void TTS.kill(); @@ -381,6 +380,10 @@ export class Core { ); let next = await gen.next(); while (!next.done) { + if (Math.random() > 0) { + // + // throw new Error("Intentional"); + } if (abortedMessageIds.has(msg.messageId)) { abortedMessageIds.delete(msg.messageId); next = await gen.return({ diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 7625ca0d6..5cb334c6d 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -3,12 +3,10 @@ import { ContextItemWithId, InputModifiers } from "core"; import { useDispatch } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; -import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; import { useAppSelector } from "../../redux/hooks"; -import { newSession, setMessageAtIndex } from "../../redux/slices/sessionSlice"; import { ToolbarOptions } from "./InputToolbar"; import { useMemo } from "react"; @@ -125,22 +123,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { hideTools: !useTools, }; - useWebviewListener( - "newSessionWithPrompt", - async (data) => { - if (props.isMainInput) { - dispatch(newSession()); - dispatch( - setMessageAtIndex({ - message: { role: "user", content: data.prompt }, - index: 0, - }), - ); - } - }, - [props.isMainInput], - ); - return (
diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index b2c64f8c6..9347cafe1 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -301,10 +301,19 @@ function TipTapEditor(props: TipTapEditorProps) { return undefined; } - const mainEditorContent = useAppSelector( - (store) => store.session.mainEditorContent, + const lastMainEditorState = useAppSelector( + (store) => store.session.lastMainEditorState, ); - console.log("MAIN EDITOR", mainEditorContent?.content); + const [fakeContent, setFakeContent] = useState("hello"); + useEffect(() => { + setTimeout(() => { + setFakeContent("Hello world"); + }, 2000); + }, []); + + if (props.isMainInput) { + console.log("Main input editor state prop:", props.editorState); + } const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); @@ -540,7 +549,18 @@ function TipTapEditor(props: TipTapEditorProps) { style: `font-size: ${getFontSize()}px;`, }, }, - content: props.editorState || mainEditorContent || "", + content: props.editorState ?? { + type: "doc", + content: [ + (() => { + console.log("set here"); + return { + type: "paragraph", + content: [{ type: "text", text: fakeContent }], + }; + })(), + ], + }, editable: !isStreaming || props.isMainInput, }); diff --git a/gui/src/hooks/useNavigationListener.tsx b/gui/src/hooks/useNavigationListener.tsx index 503b4a997..3c09dc2d0 100644 --- a/gui/src/hooks/useNavigationListener.tsx +++ b/gui/src/hooks/useNavigationListener.tsx @@ -5,7 +5,6 @@ import { useWebviewListener } from "./useWebviewListener"; const openGUITypes: (keyof ToWebviewProtocol)[] = [ "highlightedCode", - "newSessionWithPrompt", "focusContinueInput", "focusContinueInputWithoutClear", "newSession", diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index b828824a8..ec1284e06 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -9,11 +9,7 @@ import { setLocalStorage } from "../util/localStorage"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; import { useWebviewListener } from "./useWebviewListener"; import { useAppSelector } from "../redux/hooks"; -import { - selectDefaultModel, - setConfig, - setConfigError, -} from "../redux/slices/configSlice"; +import { setConfig, setConfigError } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { updateDocsSuggestions } from "../redux/slices/miscSlice"; import { diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 1b6f4d7f4..2857d334b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -41,7 +41,7 @@ type SessionState = { streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; - mainEditorContent?: JSONContent; + lastMainEditorState?: JSONContent; symbols: FileSymbolMap; mode: MessageModes; codeBlockApplyStates: { @@ -69,20 +69,6 @@ function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { return !("range" in a) && !("range" in b); } -function getBaseHistoryItem(): ChatHistoryItemWithMessageId { - return { - message: { - id: uuidv4(), - role: "assistant", - content: "", - }, - contextItems: [], - isGatheringContext: false, - checkpoint: {}, - isBeforeCheckpoint: false, - }; -} - const initialState: SessionState = { history: [], isStreaming: false, @@ -133,7 +119,11 @@ export const sessionSlice = createSlice({ // Only clear in the case of an empty message if (!lastMessage.message.content.length) { - state.mainEditorContent = + console.log( + "setting editor state to", + state.history[state.history.length - 2].editorState, + ); + state.lastMainEditorState = state.history[state.history.length - 2].editorState; state.history = state.history.slice(0, -2); } @@ -157,99 +147,91 @@ export const sessionSlice = createSlice({ state.history[index].contextItems = contextItems; } }, - resubmitAtIndex: ( + submitEditorAndInitAtIndex: ( state, { payload, }: PayloadAction<{ - index: number; + index?: number; editorState: JSONContent; }>, ) => { - const historyItem = state.history[payload.index]; - const lastHistoryItem = state.history[payload.index - 1]; + const { index, editorState } = payload; - if (!historyItem) { - return; + if (typeof index === "number" && index < state.history.length) { + // Resubmission - update input message, truncate history after resubmit with new empty response message + if (index % 2 === 1) { + console.warn( + "Corrupted history: resubmitting at odd index, shouldn't happen", + ); + } + const historyItem = state.history[index]; + + historyItem.message.content = ""; + historyItem.editorState = payload.editorState; + + state.history = state.history.slice(0, index + 1).concat({ + message: { + id: uuidv4(), + role: "assistant", + content: "", // IMPORTANT - this is subsequently updated by response streaming + }, + contextItems: [], + }); + + state.curCheckpointIndex = Math.floor(index / 2); + } else { + // New input/response messages + state.history = state.history.concat([ + { + message: { + id: uuidv4(), + role: "user", + content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state + }, + contextItems: [], + editorState, + }, + { + message: { + id: uuidv4(), + role: "assistant", + content: "", // IMPORTANT - this is subsequently updated by response streaming + }, + contextItems: [], + }, + ]); + + state.curCheckpointIndex = Math.floor((state.history.length - 1) / 2); // TODO this feels really fragile } - historyItem.message.content = ""; - historyItem.editorState = payload.editorState; - - // Cut off history after the resubmitted message - state.history = state.history - .slice(0, payload.index + 1) - .concat(getBaseHistoryItem()); - state.isStreaming = true; }, deleteMessage: (state, action: PayloadAction) => { // Deletes the current assistant message and the previous user message state.history.splice(action.payload - 1, 2); }, - initNewActiveMessage: ( + updateHistoryItemAtIndex: ( state, { payload, }: PayloadAction<{ - editorState: JSONContent; - }>, - ) => { - const baseHistoryItem = getBaseHistoryItem(); - - state.history.push({ - ...baseHistoryItem, - message: { ...baseHistoryItem.message, id: uuidv4(), role: "user" }, - editorState: payload.editorState, - }); - - state.history.push({ - ...baseHistoryItem, - message: { - ...baseHistoryItem.message, - id: uuidv4(), - role: "assistant", - }, - editorState: payload.editorState, - }); - - state.isStreaming = true; - state.curCheckpointIndex = state.curCheckpointIndex + 1; - }, - setMessageAtIndex: ( - state, - { - payload, - }: PayloadAction<{ - message: ChatMessage; index: number; - contextItems?: ContextItemWithId[]; + updates: Partial; }>, ) => { - if (payload.index >= state.history.length) { - const baseHistoryItem = getBaseHistoryItem(); - - state.history.push({ - ...baseHistoryItem, - message: { ...baseHistoryItem.message, ...payload.message }, - editorState: { - type: "doc", - content: renderChatMessage(payload.message) - .split("\n") - .map((line) => ({ - type: "paragraph", - content: line === "" ? [] : [{ type: "text", text: line }], - })), - }, - }); + const { index, updates } = payload; + if (!state.history[index]) { + console.error( + `attempting to update history item at nonexistent index ${index}`, + updates, + ); + return; } - - state.history[payload.index].message = { - ...payload.message, - id: uuidv4(), + state.history[index] = { + ...state.history[index], + ...updates, }; - - state.history[payload.index].contextItems = payload.contextItems || []; }, addContextItemsAtIndex: ( state, @@ -297,12 +279,13 @@ export const sessionSlice = createSlice({ message.role === "assistant" && message.toolCalls?.length)) ) { - const baseHistoryItem = getBaseHistoryItem(); - // Create a new message const historyItem: ChatHistoryItemWithMessageId = { - ...baseHistoryItem, - message: { ...baseHistoryItem.message, ...message }, + message: { + ...message, + id: uuidv4(), + }, + contextItems: [], }; if (message.role === "assistant" && message.toolCalls) { @@ -574,12 +557,11 @@ export const { streamUpdate, newSession, updateSessionTitle, - resubmitAtIndex, addHighlightedCode, addPromptCompletionPair, setActive, - initNewActiveMessage, - setMessageAtIndex, + submitEditorAndInitAtIndex, + updateHistoryItemAtIndex, clearLastEmptyResponse, setSelectedProfileId, deleteMessage, diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/handleErrors.ts index 7e6d99f49..156f208f1 100644 --- a/gui/src/redux/thunks/handleErrors.ts +++ b/gui/src/redux/thunks/handleErrors.ts @@ -10,6 +10,7 @@ export const handleStreamErrors = createAsyncThunk< try { await runStream(); } catch (e: any) { + // NOTE - streaming errors are shown as ide toasts in core, don't show duplicate here console.error("Error streaming response: ", e); } finally { dispatch(clearLastEmptyResponse()); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 0103e57df..d873a691f 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -11,10 +11,9 @@ import { constructMessages } from "core/llm/constructMessages"; import { renderChatMessage } from "core/util/messageContent"; import posthog from "posthog-js"; import { - initNewActiveMessage, - resubmitAtIndex, + submitEditorAndInitAtIndex, setCurCheckpointIndex, - setMessageAtIndex, + updateHistoryItemAtIndex, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { gatherContext } from "./gatherContext"; @@ -23,6 +22,7 @@ import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamSlashCommand } from "./streamSlashCommand"; import { selectDefaultModel } from "../slices/configSlice"; +import { v4 as uuidv4 } from "uuid"; const getSlashCommandForInput = ( input: MessageContent, @@ -67,24 +67,14 @@ export const streamResponseThunk = createAsyncThunk< ) => { await dispatch( handleStreamErrors(async () => { - throw new Error("intentional"); const state = getState(); const defaultModel = selectDefaultModel(state); const slashCommands = state.config.config.slashCommands || []; const inputIndex = index ?? state.session.history.length; - if (typeof index === "number") { - dispatch(resubmitAtIndex({ index, editorState })); - } else { - dispatch(initNewActiveMessage({ editorState })); - } - + dispatch(submitEditorAndInitAtIndex({ index, editorState })); resetStateForNewMessage(); - if (index) { - dispatch(setCurCheckpointIndex(Math.floor(index / 2))); - } - const result = await dispatch( gatherContext({ editorState, @@ -95,22 +85,17 @@ export const streamResponseThunk = createAsyncThunk< const unwrapped = unwrapResult(result); const { selectedContextItems, selectedCode, content } = unwrapped; - // Add the message to the history - const message: ChatMessage = { - role: "user", - content, - }; - const historyItem: ChatHistoryItem = { - message, - contextItems: selectedContextItems, - editorState, - }; - dispatch( - setMessageAtIndex({ - message, + updateHistoryItemAtIndex({ index: inputIndex, - contextItems: selectedContextItems, + updates: { + message: { + role: "user", + content, + id: uuidv4(), + }, + contextItems: selectedContextItems, + }, }), ); From 76bba305799977c9d2ac96e91a1e648a7b6cafd2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 14:45:08 -0800 Subject: [PATCH 04/14] clear abort listener when done --- gui/src/context/IdeMessenger.ts | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index fbbfc21b1..b2462af05 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -184,25 +184,32 @@ export class IdeMessenger implements IIdeMessenger { }; window.addEventListener("message", handler); - cancelToken?.addEventListener("abort", () => { + const handleAbort = () => { this.post("abort", undefined, messageId); - }); + }; + cancelToken?.addEventListener("abort", handleAbort); + + try { + while (!done) { + if (buffer.length > index) { + const chunks = buffer.slice(index); + index = buffer.length; + yield chunks; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } - while (!done) { if (buffer.length > index) { const chunks = buffer.slice(index); - index = buffer.length; yield chunks; } - await new Promise((resolve) => setTimeout(resolve, 50)); - } - if (buffer.length > index) { - const chunks = buffer.slice(index); - yield chunks; + return returnVal; + } catch (e) { + throw e; + } finally { + cancelToken?.removeEventListener("abort", handleAbort); } - - return returnVal; } async *llmStreamChat( From ddb711721ceb15c03a1db625233b5a756007b564 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 17:29:05 -0800 Subject: [PATCH 05/14] update thunks --- core/index.d.ts | 16 +++++- .../components/mainInput/ContinueInputBox.tsx | 2 - gui/src/components/mainInput/TipTapEditor.tsx | 50 +++++++++---------- gui/src/pages/gui/Chat.tsx | 4 +- gui/src/redux/slices/sessionSlice.ts | 34 +++++++++---- gui/src/redux/store.ts | 3 +- gui/src/redux/thunks/index.ts | 2 +- gui/src/redux/thunks/streamResponse.ts | 15 ++---- .../thunks/streamResponseAfterToolCall.ts | 8 +-- ...{handleErrors.ts => streamThunkWrapper.ts} | 8 +-- 10 files changed, 79 insertions(+), 63 deletions(-) rename gui/src/redux/thunks/{handleErrors.ts => streamThunkWrapper.ts} (73%) diff --git a/core/index.d.ts b/core/index.d.ts index 6160f57c3..9fac83018 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,6 +1,5 @@ import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; - declare global { interface Window { ide?: "vscode"; @@ -418,10 +417,23 @@ interface ToolCallState { output?: ContextItem[]; } +export type TipTapJsonContent = { + type?: string; + attrs?: Record; + content?: TipTapJsonContent[]; + marks?: { + type: string; + attrs?: Record; + [key: string]: any; + }[]; + text?: string; + [key: string]: any; +}; + export interface ChatHistoryItem { message: ChatMessage; contextItems: ContextItemWithId[]; - editorState?: any; + editorState?: TipTapJsonContent; modifiers?: InputModifiers; promptLogs?: PromptLog[]; toolCallState?: ToolCallState; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 5cb334c6d..e7012fc7b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -74,8 +74,6 @@ const GradientBorder = styled.div<{ `; function ContinueInputBox(props: ContinueInputBoxProps) { - const dispatch = useDispatch(); - const isStreaming = useAppSelector((state) => state.session.isStreaming); const availableSlashCommands = useAppSelector( selectSlashCommandComboBoxInputs, diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 9347cafe1..3b46bbb21 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -70,6 +70,8 @@ import { clearCodeToEdit, selectHasCodeToEdit, selectIsInEditMode, + setLastMainEditorContent, + setMainEditorContentTrigger, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; @@ -256,7 +258,6 @@ function TipTapEditor(props: TipTapEditorProps) { const isInEditModeRef = useUpdatingRef(isInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - async function handleImageFile( file: File, ): Promise<[HTMLImageElement, string] | undefined> { @@ -301,22 +302,12 @@ function TipTapEditor(props: TipTapEditorProps) { return undefined; } - const lastMainEditorState = useAppSelector( - (store) => store.session.lastMainEditorState, - ); - const [fakeContent, setFakeContent] = useState("hello"); - useEffect(() => { - setTimeout(() => { - setFakeContent("Hello world"); - }, 2000); - }, []); - - if (props.isMainInput) { - console.log("Main input editor state prop:", props.editorState); - } - const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); + const handleContentUpdate = useUpdatingRef((content: JSONContent) => { + dispatch(setLastMainEditorContent(content)); + }, []); + const editor: Editor = useEditor({ extensions: [ Document, @@ -392,7 +383,7 @@ function TipTapEditor(props: TipTapEditorProps) { onEnterRef.current({ useCodebase: false, - noContext: useActiveFile, + noContext: !!useActiveFile, }); return true; @@ -549,18 +540,11 @@ function TipTapEditor(props: TipTapEditorProps) { style: `font-size: ${getFontSize()}px;`, }, }, - content: props.editorState ?? { - type: "doc", - content: [ - (() => { - console.log("set here"); - return { - type: "paragraph", - content: [{ type: "text", text: fakeContent }], - }; - })(), - ], + onUpdate: (event) => { + const editorContent = event.editor.getJSON(); + handleContentUpdate.current(editorContent); }, + content: props.editorState, editable: !isStreaming || props.isMainInput, }); @@ -681,6 +665,18 @@ function TipTapEditor(props: TipTapEditorProps) { } }, [props.isMainInput, isStreaming, editor]); + // This allows anywhere in the app to set the content of the main input + const mainInputContentTrigger = useAppSelector( + (store) => store.session.mainEditorContentTrigger, + ); + useEffect(() => { + if (!props.isMainInput || !mainInputContentTrigger) { + return; + } + editor.commands.setContent(mainInputContentTrigger); + dispatch(setMainEditorContentTrigger(undefined)); + }, [editor, props.isMainInput, mainInputContentTrigger]); + // IDE event listeners useWebviewListener( "userInput", diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index db0367969..f9de0dcd8 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -258,8 +258,6 @@ export function Chat() { return; } - editor.commands.clearContent(true); - const promptPreamble = isInEditMode ? getMultifileEditPrompt(codeToEdit) : undefined; @@ -268,6 +266,8 @@ export function Chat() { streamResponseThunk({ editorState, modifiers, promptPreamble, index }), ); + editor.commands.clearContent(true); + // Increment localstorage counter for popup const currentCount = getLocalStorage("mainTextEntryCounter"); if (currentCount) { diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 2857d334b..85cdebdb4 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -41,7 +41,9 @@ type SessionState = { streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; - lastMainEditorState?: JSONContent; + currentMainEditorContent?: JSONContent; + lastMainEditorContent?: JSONContent | undefined; + mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; codeBlockApplyStates: { @@ -114,20 +116,32 @@ export const sessionSlice = createSlice({ if (state.history.length < 2) { return; } - const lastMessage = state.history[state.history.length - 1]; + console.log("CLEARING LAST EMPTY RESPONSE", { ...lastMessage }); // Only clear in the case of an empty message if (!lastMessage.message.content.length) { - console.log( - "setting editor state to", - state.history[state.history.length - 2].editorState, - ); - state.lastMainEditorState = + console.log("CLEARING", { + ...state.history[state.history.length - 2].editorState, + }); + state.mainEditorContentTrigger = state.history[state.history.length - 2].editorState; state.history = state.history.slice(0, -2); } }, + // Trigger value picked up by editor with isMainInput to set its content + setMainEditorContentTrigger: ( + state, + action: PayloadAction, + ) => { + state.mainEditorContentTrigger = action.payload; + }, + setLastMainEditorContent: ( + state, + action: PayloadAction, + ) => { + state.lastMainEditorContent = action.payload; + }, updateFileSymbols: (state, action: PayloadAction) => { state.symbols = { ...state.symbols, @@ -167,7 +181,7 @@ export const sessionSlice = createSlice({ } const historyItem = state.history[index]; - historyItem.message.content = ""; + historyItem.message.content = ""; // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming historyItem.editorState = payload.editorState; state.history = state.history.slice(0, index + 1).concat({ @@ -187,7 +201,7 @@ export const sessionSlice = createSlice({ message: { id: uuidv4(), role: "user", - content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state + content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming }, contextItems: [], editorState, @@ -563,6 +577,8 @@ export const { submitEditorAndInitAtIndex, updateHistoryItemAtIndex, clearLastEmptyResponse, + setMainEditorContentTrigger, + setLastMainEditorContent, setSelectedProfileId, deleteMessage, setIsGatheringContext, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 779909a47..07d93df42 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -31,9 +31,10 @@ const rootReducer = combineReducers({ }); const saveSubsetFilters = [ - createFilter("session", ["history", "sessionId", "defaultModelTitle"]), + createFilter("session", ["history", "sessionId", "lastMainEditorContent"]), // Don't persist any of the edit state for now createFilter("editModeState", []), + createFilter("config", ["defaultModelTitle"]), ]; const migrations: MigrationManifest = { diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index d5445d09d..31f0fa0cc 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -1,6 +1,6 @@ export { exitEditMode } from "./exitEditMode"; export { gatherContext } from "./gatherContext"; -export { handleStreamErrors } from "./handleErrors"; +export { streamThunkWrapper } from "./streamThunkWrapper"; export { resetStateForNewMessage } from "./resetStateForNewMessage"; export { streamNormalInput } from "./streamNormalInput"; export { streamResponseThunk } from "./streamResponse"; diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index d873a691f..1411828d3 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,23 +1,16 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { - ChatHistoryItem, - ChatMessage, - InputModifiers, - MessageContent, - SlashCommandDescription, -} from "core"; +import { InputModifiers, MessageContent, SlashCommandDescription } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderChatMessage } from "core/util/messageContent"; import posthog from "posthog-js"; import { submitEditorAndInitAtIndex, - setCurCheckpointIndex, updateHistoryItemAtIndex, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { gatherContext } from "./gatherContext"; -import { handleStreamErrors } from "./handleErrors"; +import { streamThunkWrapper } from "./streamThunkWrapper"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamSlashCommand } from "./streamSlashCommand"; @@ -66,7 +59,7 @@ export const streamResponseThunk = createAsyncThunk< { dispatch, extra, getState }, ) => { await dispatch( - handleStreamErrors(async () => { + streamThunkWrapper(async () => { const state = getState(); const defaultModel = selectDefaultModel(state); const slashCommands = state.config.config.slashCommands || []; @@ -113,7 +106,7 @@ export const streamResponseThunk = createAsyncThunk< let commandAndInput = getSlashCommandForInput(content, slashCommands); if (!commandAndInput) { - await dispatch(streamNormalInput(messages)); + unwrapResult(await dispatch(streamNormalInput(messages))); } else { const [slashCommand, commandInput] = commandAndInput; let updatedContextItems = []; diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index c516592e1..39ba0a24a 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,4 +1,4 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage, ContextItem } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; @@ -9,7 +9,7 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { handleStreamErrors } from "./handleErrors"; +import { streamThunkWrapper } from "./streamThunkWrapper"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; @@ -24,7 +24,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< "chat/streamAfterToolCall", async ({ toolCallId, toolOutput }, { dispatch, getState }) => { await dispatch( - handleStreamErrors(async () => { + streamThunkWrapper(async () => { const state = getState(); const initialHistory = state.session.history; const defaultModel = selectDefaultModel(state); @@ -60,7 +60,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< [...updatedHistory], defaultModel.model, ); - await dispatch(streamNormalInput(messages)); + unwrapResult(await dispatch(streamNormalInput(messages))); }), ); }, diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/streamThunkWrapper.ts similarity index 73% rename from gui/src/redux/thunks/handleErrors.ts rename to gui/src/redux/thunks/streamThunkWrapper.ts index 156f208f1..39c41a5f1 100644 --- a/gui/src/redux/thunks/handleErrors.ts +++ b/gui/src/redux/thunks/streamThunkWrapper.ts @@ -2,18 +2,18 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -export const handleStreamErrors = createAsyncThunk< +export const streamThunkWrapper = createAsyncThunk< void, () => Promise, ThunkApiType ->("chat/handleStreamErrors", async (runStream, { dispatch, extra }) => { +>("chat/streamWrapper", async (runStream, { dispatch, extra }) => { try { await runStream(); } catch (e: any) { // NOTE - streaming errors are shown as ide toasts in core, don't show duplicate here - console.error("Error streaming response: ", e); - } finally { + // console.debug("Error streaming response: ", e); dispatch(clearLastEmptyResponse()); + } finally { dispatch(setInactive()); // triggerSave(!save); TODO } From 17c384e168e83df2865da1ae0df29b1d5ff59b1b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 17:36:17 -0800 Subject: [PATCH 06/14] chat fixes cleanup --- core/core.ts | 4 ---- gui/src/redux/slices/sessionSlice.ts | 4 ---- gui/src/redux/thunks/streamNormalInput.ts | 1 - gui/src/redux/thunks/streamThunkWrapper.ts | 2 +- 4 files changed, 1 insertion(+), 10 deletions(-) diff --git a/core/core.ts b/core/core.ts index 519b4c755..e943e7a7d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -380,10 +380,6 @@ export class Core { ); let next = await gen.next(); while (!next.done) { - if (Math.random() > 0) { - // - // throw new Error("Intentional"); - } if (abortedMessageIds.has(msg.messageId)) { abortedMessageIds.delete(msg.messageId); next = await gen.return({ diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 85cdebdb4..f15648eec 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -117,13 +117,9 @@ export const sessionSlice = createSlice({ return; } const lastMessage = state.history[state.history.length - 1]; - console.log("CLEARING LAST EMPTY RESPONSE", { ...lastMessage }); // Only clear in the case of an empty message if (!lastMessage.message.content.length) { - console.log("CLEARING", { - ...state.history[state.history.length - 2].editorState, - }); state.mainEditorContentTrigger = state.history[state.history.length - 2].editorState; state.history = state.history.slice(0, -2); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 88df9d65f..aec7bb38e 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -5,7 +5,6 @@ import { selectDefaultModel } from "../slices/configSlice"; import { abortStream, addPromptCompletionPair, - clearLastEmptyResponse, setToolGenerated, streamUpdate, } from "../slices/sessionSlice"; diff --git a/gui/src/redux/thunks/streamThunkWrapper.ts b/gui/src/redux/thunks/streamThunkWrapper.ts index 39c41a5f1..da67b2814 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.ts +++ b/gui/src/redux/thunks/streamThunkWrapper.ts @@ -11,7 +11,7 @@ export const streamThunkWrapper = createAsyncThunk< await runStream(); } catch (e: any) { // NOTE - streaming errors are shown as ide toasts in core, don't show duplicate here - // console.debug("Error streaming response: ", e); + console.debug("Error streaming response: ", e); dispatch(clearLastEmptyResponse()); } finally { dispatch(setInactive()); From a146ed9886a94d0c6c257bb5ebbaa503bf9ebccc Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 17:37:45 -0800 Subject: [PATCH 07/14] remove duplicate tiptap jsoncontent typ --- core/index.d.ts | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 9fac83018..39a920499 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -417,23 +417,10 @@ interface ToolCallState { output?: ContextItem[]; } -export type TipTapJsonContent = { - type?: string; - attrs?: Record; - content?: TipTapJsonContent[]; - marks?: { - type: string; - attrs?: Record; - [key: string]: any; - }[]; - text?: string; - [key: string]: any; -}; - export interface ChatHistoryItem { message: ChatMessage; contextItems: ContextItemWithId[]; - editorState?: TipTapJsonContent; + editorState?: any; modifiers?: InputModifiers; promptLogs?: PromptLog[]; toolCallState?: ToolCallState; From 57d7e8153327acbff85fc9aa1b6d006b7ef865d8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 17:48:03 -0800 Subject: [PATCH 08/14] remove last main input paradigm --- gui/src/components/mainInput/TipTapEditor.tsx | 9 --------- gui/src/redux/slices/sessionSlice.ts | 8 -------- gui/src/redux/store.ts | 2 +- 3 files changed, 1 insertion(+), 18 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 3b46bbb21..561d044d0 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -70,7 +70,6 @@ import { clearCodeToEdit, selectHasCodeToEdit, selectIsInEditMode, - setLastMainEditorContent, setMainEditorContentTrigger, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; @@ -304,10 +303,6 @@ function TipTapEditor(props: TipTapEditorProps) { const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); - const handleContentUpdate = useUpdatingRef((content: JSONContent) => { - dispatch(setLastMainEditorContent(content)); - }, []); - const editor: Editor = useEditor({ extensions: [ Document, @@ -540,10 +535,6 @@ function TipTapEditor(props: TipTapEditorProps) { style: `font-size: ${getFontSize()}px;`, }, }, - onUpdate: (event) => { - const editorContent = event.editor.getJSON(); - handleContentUpdate.current(editorContent); - }, content: props.editorState, editable: !isStreaming || props.isMainInput, }); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index f15648eec..2ddcfccc6 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -42,7 +42,6 @@ type SessionState = { codeToEdit: CodeToEdit[]; curCheckpointIndex: number; currentMainEditorContent?: JSONContent; - lastMainEditorContent?: JSONContent | undefined; mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; @@ -132,12 +131,6 @@ export const sessionSlice = createSlice({ ) => { state.mainEditorContentTrigger = action.payload; }, - setLastMainEditorContent: ( - state, - action: PayloadAction, - ) => { - state.lastMainEditorContent = action.payload; - }, updateFileSymbols: (state, action: PayloadAction) => { state.symbols = { ...state.symbols, @@ -574,7 +567,6 @@ export const { updateHistoryItemAtIndex, clearLastEmptyResponse, setMainEditorContentTrigger, - setLastMainEditorContent, setSelectedProfileId, deleteMessage, setIsGatheringContext, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 07d93df42..5ddf55ee6 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -31,7 +31,7 @@ const rootReducer = combineReducers({ }); const saveSubsetFilters = [ - createFilter("session", ["history", "sessionId", "lastMainEditorContent"]), + createFilter("session", ["history", "sessionId"]), // Don't persist any of the edit state for now createFilter("editModeState", []), createFilter("config", ["defaultModelTitle"]), From d709b8053406f0936a013272df5a6c3e68be8eb9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 19:28:48 -0800 Subject: [PATCH 09/14] remove monaco --- extensions/vscode/package-lock.json | 10 +-- extensions/vscode/package.json | 1 - gui/package-lock.json | 36 --------- gui/package.json | 1 - gui/src/App.tsx | 5 -- gui/src/components/markdown/monaco.css | 3 - gui/src/pages/monaco.tsx | 107 ------------------------- 7 files changed, 2 insertions(+), 161 deletions(-) delete mode 100644 gui/src/components/markdown/monaco.css delete mode 100644 gui/src/pages/monaco.tsx diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 923f4c9b5..75db2a18d 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.244", + "version": "0.9.241", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.244", + "version": "0.9.241", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -34,7 +34,6 @@ "ignore": "^5.3.0", "jsdom": "^24.0.0", "minisearch": "^7.0.0", - "monaco-editor": "^0.45.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", "ncp": "^2.0.0", "node-fetch": "^3.3.2", @@ -8890,11 +8889,6 @@ "node": ">=10" } }, - "node_modules/monaco-editor": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.45.0.tgz", - "integrity": "sha512-mjv1G1ZzfEE3k9HZN0dQ2olMdwIfaeAAjFiwNprLfYNRSz7ctv9XuCT7gPtBGrMUeV1/iZzYKj17Khu1hxoHOA==" - }, "node_modules/monaco-vscode-textmate-theme-converter": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/monaco-vscode-textmate-theme-converter/-/monaco-vscode-textmate-theme-converter-0.1.7.tgz", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9cf7db2b1..8a073d134 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -688,7 +688,6 @@ "ignore": "^5.3.0", "jsdom": "^24.0.0", "minisearch": "^7.0.0", - "monaco-editor": "^0.45.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", "ncp": "^2.0.0", "node-fetch": "^3.3.2", diff --git a/gui/package-lock.json b/gui/package-lock.json index 91410e6df..b2b6ceaea 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -9,7 +9,6 @@ "dependencies": { "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", - "@monaco-editor/react": "^4.6.0", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", @@ -1336,30 +1335,6 @@ "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, - "node_modules/@monaco-editor/loader": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.4.0.tgz", - "integrity": "sha512-00ioBig0x642hytVspPl7DbQyaSWRaolYie/UFNjoTdvoKPzo6xrXLhTk9ixgIKcLH5b5vDOjVNiGyY+uDCUlg==", - "dependencies": { - "state-local": "^1.0.6" - }, - "peerDependencies": { - "monaco-editor": ">= 0.21.0 < 1" - } - }, - "node_modules/@monaco-editor/react": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.6.0.tgz", - "integrity": "sha512-RFkU9/i7cN2bsq/iTkurMWOEErmYcY6JiQI3Jn+WeR/FGISH8JbHERjpS9oRuSOPvDMJI0Z8nJeKkbOs9sBYQw==", - "dependencies": { - "@monaco-editor/loader": "^1.4.0" - }, - "peerDependencies": { - "monaco-editor": ">= 0.25.0 < 1", - "react": "^16.8.0 || ^17.0.0 || ^18.0.0", - "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" - } - }, "node_modules/@napi-rs/nice": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.0.1.tgz", @@ -8871,12 +8846,6 @@ "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.1.0.tgz", "integrity": "sha512-tv7c/uefWdEhcu6hvrfTihflgeEi2tN6VV7HJnCjK6VxM75QQJh4t9FwJCsA2EsRS8LCnu3W87CuGPWMocOLCA==" }, - "node_modules/monaco-editor": { - "version": "0.52.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.0.tgz", - "integrity": "sha512-OeWhNpABLCeTqubfqLMXGsqf6OmPU6pHM85kF3dhy6kq5hnhuVS1p3VrEW/XhWHc71P2tHyS5JFySD8mgs1crw==", - "peer": true - }, "node_modules/mrmime": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.0.tgz", @@ -11435,11 +11404,6 @@ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", "dev": true }, - "node_modules/state-local": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz", - "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==" - }, "node_modules/std-env": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.7.0.tgz", diff --git a/gui/package.json b/gui/package.json index b5e16103d..ba889ca39 100644 --- a/gui/package.json +++ b/gui/package.json @@ -17,7 +17,6 @@ "dependencies": { "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", - "@monaco-editor/react": "^4.6.0", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 244d811b5..3e2345949 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -9,7 +9,6 @@ import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; import MigrationPage from "./pages/migration"; -import MonacoPage from "./pages/monaco"; import MorePage from "./pages/More"; import Stats from "./pages/stats"; import { ROUTES } from "./util/navigation"; @@ -53,10 +52,6 @@ const router = createMemoryRouter([ path: ROUTES.CONFIG_ERROR, element: , }, - { - path: "/monaco", - element: , - }, { path: "/migration", element: , diff --git a/gui/src/components/markdown/monaco.css b/gui/src/components/markdown/monaco.css deleted file mode 100644 index 1e53f45fe..000000000 --- a/gui/src/components/markdown/monaco.css +++ /dev/null @@ -1,3 +0,0 @@ -.monaco-editor .margin { - padding-top: 4px; -} diff --git a/gui/src/pages/monaco.tsx b/gui/src/pages/monaco.tsx deleted file mode 100644 index c0cfbd8ec..000000000 --- a/gui/src/pages/monaco.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { DiffEditor } from "@monaco-editor/react"; -import React, { useContext, useEffect } from "react"; -import { v4 } from "uuid"; -import { vscInputBackground } from "../components"; -import HeaderButtonWithToolTip from "../components/gui/HeaderButtonWithToolTip"; -import { IdeMessengerContext } from "../context/IdeMessenger"; - -interface EditorFrameProps { - filename: string; -} - -function EditorFrame(props: EditorFrameProps) { - const [contents, setContents] = React.useState( - "function sum(a, b) {return a + b;}", - ); - - const ideMessenger = useContext(IdeMessengerContext); - - useEffect(() => { - const messageId = v4(); - const eventListener = (event: any) => { - if ( - event.data.messageId === messageId && - event.data.type === "readRangeInFile" - ) { - setContents(event.data.contents); - } - }; - window.addEventListener("message", eventListener); - - ideMessenger.post("readFile", { filepath: props.filename }); - - return () => window.removeEventListener("message", eventListener); - }, []); - - return ( -
-
- { - ideMessenger.post("showFile", { - filepath: props.filename, - }); - }} - > - {props.filename.split("/").pop()} - -
- {}}> - - - {}}> - - -
-
- {/* */} - -
- ); -} - -const FILENAMES = [ - "/Users/natesesti/Desktop/continue/gui/src/hooks/CustomPostHogProvider.tsx", - "/Users/natesesti/Desktop/continue/gui/src/hooks/CustomPostHogProvider.tsx", - "/Users/natesesti/Desktop/continue/gui/src/hooks/CustomPostHogProvider.tsx", -]; - -function MonacoPage() { - return ( -
-

Multi-File Edit

- {FILENAMES.map((filename) => { - return ; - })} -
- ); -} - -export default MonacoPage; From 9189cfffafc8dc29311421a78ec015a449896ab0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Dec 2024 19:32:06 -0800 Subject: [PATCH 10/14] revert to previous package files for vscode --- extensions/vscode/package-lock.json | 10 ++++++++-- extensions/vscode/package.json | 1 + 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 75db2a18d..923f4c9b5 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.241", + "version": "0.9.244", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.241", + "version": "0.9.244", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -34,6 +34,7 @@ "ignore": "^5.3.0", "jsdom": "^24.0.0", "minisearch": "^7.0.0", + "monaco-editor": "^0.45.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", "ncp": "^2.0.0", "node-fetch": "^3.3.2", @@ -8889,6 +8890,11 @@ "node": ">=10" } }, + "node_modules/monaco-editor": { + "version": "0.45.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.45.0.tgz", + "integrity": "sha512-mjv1G1ZzfEE3k9HZN0dQ2olMdwIfaeAAjFiwNprLfYNRSz7ctv9XuCT7gPtBGrMUeV1/iZzYKj17Khu1hxoHOA==" + }, "node_modules/monaco-vscode-textmate-theme-converter": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/monaco-vscode-textmate-theme-converter/-/monaco-vscode-textmate-theme-converter-0.1.7.tgz", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 8a073d134..9cf7db2b1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -688,6 +688,7 @@ "ignore": "^5.3.0", "jsdom": "^24.0.0", "minisearch": "^7.0.0", + "monaco-editor": "^0.45.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", "ncp": "^2.0.0", "node-fetch": "^3.3.2", From bd79418c8b5ef7f8b7192f2a599c508f75aea2b1 Mon Sep 17 00:00:00 2001 From: Casey Hillers Date: Sun, 8 Dec 2024 16:47:30 -0800 Subject: [PATCH 11/14] Add Flutter and Dart to pre-indexed docs --- core/indexing/docs/preIndexedDocs.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 99a8ddc8a..93eaa8411 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -336,6 +336,18 @@ const preIndexedDocs: Record< rootUrl: "https://go.dev", faviconUrl: "https://go.dev/favicon.ico", }, + "https://api.flutter.dev": { + title: "Flutter", + startUrl: "https://api.flutter.dev", + rootUrl: "https://api.flutter.dev", + faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png", + }, + "https://api.dart.dev": { + title: "Dart", + startUrl: "https://api.dart.dev", + rootUrl: "https://api.dart.dev", + faviconUrl: "https://api.dart.dev/static-assets/favicon.png", + }, }; export default preIndexedDocs; From 767f7e1c9c7ecab7cc3515f0dabf3798a14df612 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 8 Dec 2024 21:30:03 -0800 Subject: [PATCH 12/14] fix autocomplete filtering cases --- .../streamTransforms/StreamTransformPipeline.ts | 7 +++++++ .../filtering/streamTransforms/lineStream.ts | 15 ++++++++++++++- core/autocomplete/filtering/test/testCases.ts | 12 ++++-------- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 55cde067a..180c339e6 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -10,6 +10,7 @@ import { showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, + stopAtLinesExact, stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, @@ -42,6 +43,12 @@ export class StreamTransformPipeline { let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator, fullStop); + const lineBelowCursor = this.getLineBelowCursor(helper); + if (lineBelowCursor.trim() !== "") { + lineGenerator = stopAtLinesExact(lineGenerator, fullStop, [ + lineBelowCursor, + ]); + } lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); lineGenerator = avoidEmptyComments( lineGenerator, diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index aaeec1291..851dea88a 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -2,7 +2,6 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; -import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService"; export type LineFilter = (args: { lines: LineStream; @@ -270,6 +269,20 @@ export async function* stopAtLines( } } +export async function* stopAtLinesExact( + stream: LineStream, + fullStop: () => void, + linesToStopAt: string[], +): LineStream { + for await (const line of stream) { + if (linesToStopAt.some((stopAt) => line === stopAt)) { + fullStop(); + break; + } + yield line; + } +} + /** * Filters a LineStream, skipping specified prefixes on the first line. * @param {LineStream} lines - The input stream of lines. diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 277c8cdc8..f83de1607 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -810,8 +810,7 @@ func main() {}`, }`, expectedCompletion: `string State string - ZipCode string -}`, + ZipCode string`, }, { @@ -1118,8 +1117,7 @@ impl Calculator { self.result /= number; } else { println!("Cannot divide by zero."); - } -}`, + }`, }, { description: "Should autocomplete Rust struct definition", @@ -1600,8 +1598,7 @@ interface User { age: number; }`, expectedCompletion: `mail: string; - age: number; -}`, + age: number;`, }, { description: "Should autocomplete TypeScript interface declarations", @@ -1853,8 +1850,7 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, Address: string }`, expectedCompletion: ` - Address: string -}`, + Address: string`, }, { From fc11a987756ac0f43e1ae3ab1a624e7d77f44f2c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 8 Dec 2024 21:30:22 -0800 Subject: [PATCH 13/14] update package.json --- 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 9cf7db2b1..b63ed82f9 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.241", + "version": "0.9.242", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 28aad1a668a50a1e17feb471806f6d1a48c0531d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 9 Dec 2024 00:16:14 -0800 Subject: [PATCH 14/14] docs UI updates + delete docs --- core/core.ts | 2 +- core/index.d.ts | 9 +-- core/indexing/docs/DocsService.ts | 61 ++++++++----------- gui/src/components/dialogs/AddDocsDialog.tsx | 14 ++++- .../indexing/DocsIndexingStatus.tsx | 43 ++++++++++--- .../indexing/DocsIndexingStatuses.tsx | 26 ++++---- gui/src/components/indexing/utils.ts | 16 ----- 7 files changed, 88 insertions(+), 83 deletions(-) delete mode 100644 gui/src/components/indexing/utils.ts diff --git a/core/core.ts b/core/core.ts index ddfacf5b9..d28d2e25c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -735,7 +735,7 @@ export class Core { }); on("indexing/setPaused", async (msg) => { if (msg.data.type === "docs") { - this.docsService.setPaused(msg.data.id, msg.data.paused); + // this.docsService.setPaused(msg.data.id, msg.data.paused); } }); on("docs/getSuggestedDocs", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index cd3518c36..aac57bdf5 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -59,14 +59,7 @@ export interface IndexingStatus { type: "docs"; progress: number; description: string; - status: - | "indexing" - | "complete" - | "paused" - | "failed" - | "aborted" - | "deleted" - | "pending"; + status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending"; embeddingsProviderId: string; isReindexing?: boolean; debugInfo?: string; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index b52577a5f..994cb6aa2 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -37,12 +37,6 @@ 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; @@ -206,19 +200,19 @@ export default class DocsService { } // 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", - }); - } - } + // 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. @@ -383,16 +377,9 @@ export default class DocsService { const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values - const fixedStatus: Pick< + const fixedStatus: Omit< IndexingStatus, - | "type" - | "id" - | "embeddingsProviderId" - | "isReindexing" - | "debugInfo" - | "icon" - | "url" - | "title" + "progress" | "description" | "status" > = { type: "docs", id: siteIndexingConfig.startUrl, @@ -405,7 +392,6 @@ export default class DocsService { }; // Clear current indexes if reIndexing - // if (indexExists) { if (reIndex) { await this.deleteIndexes(startUrl); @@ -452,9 +438,9 @@ export default class DocsService { description: `Finding subpages (${page.path})`, status: "indexing", 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 + 0.15 * estimatedProgress + + Math.min(0.35, (0.35 * processedPages) / 500), + // For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max }); const article = pageToArticle(page); @@ -464,7 +450,11 @@ export default class DocsService { articles.push(article); processedPages++; - await new Promise((resolve) => setTimeout(resolve, 100)); // Locks down GUI if no sleeping + + // Locks down GUI if no sleeping + // Wait proportional to how many docs are indexing + const toWait = 100 * this.docsIndexingQueue.size + 50; + await new Promise((resolve) => setTimeout(resolve, toWait)); } void Telemetry.capture("docs_pages_crawled", { @@ -1017,13 +1007,10 @@ export default class DocsService { } async delete(startUrl: string) { + this.docsIndexingQueue.delete(startUrl); + this.abort(startUrl); await this.deleteIndexes(startUrl); this.deleteFromConfig(startUrl); - - const status = this.statuses.get(startUrl); - if (status) { - this.handleStatusUpdate({ ...status, status: "deleted" }); - } this.messenger?.send("refreshSubmenuItems", undefined); } diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 51d11498d..0bcd40fd9 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -215,13 +215,23 @@ function AddDocsDialog() { {/*
*/} -

+

{ + e.stopPropagation(); + ideMessenger.post("openUrl", details.docsLink); + }} + > {details.docsLink}

)}
-
+
{ + e.stopPropagation(); + }} + > = { paused: PauseCircleIcon, complete: CheckCircleIcon, aborted: null, - deleted: null, pending: null, - failed: XMarkIcon, // Since we show an erorr message below + failed: XMarkIcon, // Since we show an error message below }; function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const status = useAppSelector( (store) => store.indexing.indexing.statuses[docConfig.startUrl], @@ -53,6 +54,26 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { } }; + const [hasDeleted, setHasDeleted] = useState(false); // simple alternative to optimistic redux update + const onDelete = () => { + // optimistic update + dispatch( + setDialogMessage( + { + ideMessenger.post("context/removeDocs", { + startUrl: docConfig.startUrl, + }); + setHasDeleted(true); + }} + />, + ), + ); + dispatch(setShowDialog(true)); + }; + const progressPercentage = useMemo(() => { if (!status) { return 0; @@ -62,6 +83,8 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { const Icon = STATUS_TO_ICON[status?.status]; + if (hasDeleted) return null; + return (
{/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */} @@ -100,6 +123,12 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { }`} > ) : null} + {status?.status !== "indexing" ? ( + + ) : null}
)}
@@ -125,7 +154,6 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { failed: reIndex, aborted: reIndex, paused: () => {}, - deleted: () => {}, pending: () => {}, }[status?.status] } @@ -137,7 +165,6 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { failed: "Click to retry", aborted: "Click to index", paused: "", - deleted: "", pending: "", }[status?.status] } diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx index a54ffd2a5..76feb21e0 100644 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -10,16 +10,6 @@ function DocsIndexingStatuses() { const config = useAppSelector((store) => store.config.config); const configDocs = config.docs ?? []; - // const indexingStatuses = useSelector( - // (store: RootState) => store.indexing.indexing.statuses, - // ); - // const docsStatuses = useMemo(() => { - // const docs = Object.values(indexingStatuses).filter( - // (status) => status.type === "docs" && status.status !== "deleted", - // ); - // return docs; - // }, [indexingStatuses]); - return (
@@ -38,9 +28,23 @@ function DocsIndexingStatuses() { ) : null}
- Manage your documentation sources + {configDocs.length + ? "Manage your documentation sources" + : "No docs yet"}
+
+ {configDocs.length === 0 && ( + { + dispatch(setShowDialog(true)); + dispatch(setDialogMessage()); + }} + > + Add Docs + + )} +
{configDocs.map((doc) => { return ; })} diff --git a/gui/src/components/indexing/utils.ts b/gui/src/components/indexing/utils.ts deleted file mode 100644 index 768384a52..000000000 --- a/gui/src/components/indexing/utils.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { - ArrowPathIcon, - CheckCircleIcon, - PauseCircleIcon, -} 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 -};