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`, }, { diff --git a/core/core.ts b/core/core.ts index ddfacf5b9..82a6df62f 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(); @@ -735,7 +734,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..4477d1b41 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"; @@ -59,14 +58,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/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; 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/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" 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/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 -}; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 7625ca0d6..e7012fc7b 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"; @@ -76,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, @@ -125,22 +121,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 8383b1055..1aee79743 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -69,6 +69,7 @@ import { clearCodeToEdit, selectHasCodeToEdit, selectIsInEditMode, + setMainEditorContentTrigger, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; import { @@ -258,7 +259,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> { @@ -303,10 +303,6 @@ function TipTapEditor(props: TipTapEditorProps) { return undefined; } - const mainEditorContent = useAppSelector( - (store) => store.session.mainEditorContent, - ); - const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); const editor: Editor = useEditor({ @@ -384,7 +380,7 @@ function TipTapEditor(props: TipTapEditorProps) { onEnterRef.current({ useCodebase: false, - noContext: useActiveFile, + noContext: !!useActiveFile, }); return true; @@ -543,7 +539,7 @@ function TipTapEditor(props: TipTapEditorProps) { style: `font-size: ${getFontSize()}px;`, }, }, - content: props.editorState || mainEditorContent || "", + content: props.editorState, editable: !isStreaming || props.isMainInput, }); @@ -664,6 +660,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/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/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( 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 89c6f5e41..1ad3b2765 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/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 2ba67d164..ea514b833 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -260,8 +260,6 @@ export function Chat() { return; } - editor.commands.clearContent(true); - const promptPreamble = isInEditMode ? getMultifileEditPrompt(codeToEdit) : undefined; @@ -270,6 +268,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/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; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 715740db5..57821cc62 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -45,7 +45,8 @@ type SessionState = { streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; - mainEditorContent?: JSONContent; + currentMainEditorContent?: JSONContent; + mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; codeBlockApplyStates: { @@ -73,20 +74,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 = { allSessionMetadata: [], history: [], @@ -134,16 +121,22 @@ export const sessionSlice = createSlice({ if (state.history.length < 2) { return; } - const lastMessage = state.history[state.history.length - 1]; // Only clear in the case of an empty message if (!lastMessage.message.content.length) { - state.mainEditorContent = + 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; + }, updateFileSymbols: (state, action: PayloadAction) => { state.symbols = { ...state.symbols, @@ -163,99 +156,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 = ""; // 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({ + 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 prior to streaming + }, + 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, @@ -303,12 +288,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) { @@ -625,13 +611,13 @@ export const { streamUpdate, newSession, updateSessionTitle, - resubmitAtIndex, addHighlightedCode, addPromptCompletionPair, setActive, - initNewActiveMessage, - setMessageAtIndex, + submitEditorAndInitAtIndex, + updateHistoryItemAtIndex, clearLastEmptyResponse, + setMainEditorContentTrigger, setSelectedProfileId, deleteMessage, setIsGatheringContext, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 779909a47..5ddf55ee6 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"]), // 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 c35189de3..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 { handleErrors } 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/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 5a22a36b5..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"; @@ -17,70 +16,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..1411828d3 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,28 +1,21 @@ 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 { - initNewActiveMessage, - resubmitAtIndex, - setCurCheckpointIndex, - setMessageAtIndex, + submitEditorAndInitAtIndex, + updateHistoryItemAtIndex, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { gatherContext } from "./gatherContext"; -import { handleErrors } from "./handleErrors"; +import { streamThunkWrapper } from "./streamThunkWrapper"; 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, @@ -66,24 +59,15 @@ export const streamResponseThunk = createAsyncThunk< { dispatch, extra, getState }, ) => { await dispatch( - handleErrors(async () => { + streamThunkWrapper(async () => { 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, @@ -94,22 +78,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, + }, }), ); @@ -127,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 52b15c13f..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 { handleErrors } 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( - handleErrors(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 62% rename from gui/src/redux/thunks/handleErrors.ts rename to gui/src/redux/thunks/streamThunkWrapper.ts index 44485c400..0866e59f8 100644 --- a/gui/src/redux/thunks/handleErrors.ts +++ b/gui/src/redux/thunks/streamThunkWrapper.ts @@ -1,17 +1,19 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { setInactive } from "../slices/sessionSlice"; +import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { saveCurrentSession } from "./session"; -export const handleErrors = createAsyncThunk< +export const streamThunkWrapper = createAsyncThunk< void, () => Promise, ThunkApiType ->("chat/handleErrors", 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.debug("Error streaming response: ", e); + dispatch(clearLastEmptyResponse()); } finally { dispatch(setInactive()); // NOTE will conflict with dallin/silent-chat-errors, move this dispatch to the streamWrapper on that version 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/", },