diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index b73cdb3ad..ae0359027 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -49,11 +49,11 @@ jobs: platform: alpine arch: x64 npm_config_arch: x64 - - os: macos-12 # should migrate this to the newer x64 version of macos-14 + - os: macos-13 platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-12 # same here, especially + - os: macos-13 platform: darwin arch: arm64 npm_config_arch: arm64 diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index a65e79c7f..bd5f4b7ac 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -49,11 +49,11 @@ jobs: platform: alpine arch: x64 npm_config_arch: x64 - - os: macos-12 # should migrate this to the newer x64 version of macos-14 + - os: macos-13 platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-12 # same here, especially + - os: macos-13 platform: darwin arch: arm64 npm_config_arch: arm64 diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index 128dbf78e..309310738 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -29,14 +29,23 @@ export class ImportDefinitionsService { return this.cache.get(filepath); } - private async _getFileInfo(filepath: string): Promise { + private async _getFileInfo(filepath: string): Promise { const parser = await getParserForFile(filepath); if (!parser) { return { imports: {}, }; } - const ast = parser.parse(await this.ide.readFile(filepath), undefined, { + + let fileContents: string | undefined = undefined; + try { + fileContents = await this.ide.readFile(filepath); + } catch (err) { + // File removed + return null; + } + + const ast = parser.parse(fileContents, undefined, { includedRanges: [ { startIndex: 0, diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index a052aace2..db8d99131 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -1,7 +1,7 @@ import fs from "node:fs"; import path from "node:path"; -import Mock from "../../../llm/llms/Mock"; +import MockLLM from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/fixtures"; import { CompletionProvider } from "../../CompletionProvider"; import { AutocompleteInput } from "../../util/types"; @@ -30,7 +30,7 @@ export async function testAutocompleteFiltering( const { prefix, suffix } = parseFimExample(test.input); // Setup necessary objects - const llm = new Mock({ + const llm = new MockLLM({ model: "mock", }); llm.completion = test.llmOutput; diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts new file mode 100644 index 000000000..071910bd9 --- /dev/null +++ b/core/context/rerankers/bedrock.ts @@ -0,0 +1,99 @@ +import { + BedrockRuntimeClient, + InvokeModelCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { Chunk, Reranker, RerankerName } from "../../index.js"; + +export class BedrockReranker implements Reranker { + name: RerankerName = "bedrock"; + + static defaultOptions = { + region: "us-east-1", + model: "amazon.rerank-v1:0", + profile: "bedrock", + }; + + private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"]; + + constructor( + private readonly params: { + region?: string; + model?: string; + profile?: string; + } = {}, + ) { + if (params.model && !this.supportedModels.includes(params.model)) { + throw new Error( + `Unsupported model: ${params.model}. Supported models are: ${this.supportedModels.join(", ")}`, + ); + } + } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + + try { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.params.region ?? BedrockReranker.defaultOptions.region, + credentials, + }); + + const model = this.params.model ?? BedrockReranker.defaultOptions.model; + + // Base payload for both models + const payload: any = { + query: query, + documents: chunks.map((chunk) => chunk.content), + top_n: chunks.length, + }; + + // Add api_version for Cohere model + if (model.startsWith("cohere.rerank")) { + payload.api_version = 2; + } + + const input = { + body: JSON.stringify(payload), + modelId: model, + accept: "*/*", + contentType: "application/json", + }; + + const command = new InvokeModelCommand(input); + const response = await client.send(command); + + if (!response.body) { + throw new Error("Empty response received from Bedrock"); + } + + const responseBody = JSON.parse(new TextDecoder().decode(response.body)); + + // Sort results by index to maintain original order + return responseBody.results + .sort((a: any, b: any) => a.index - b.index) + .map((result: any) => result.relevance_score); + } catch (error) { + console.error("Error in BedrockReranker.rerank:", error); + throw error; + } + } + + private async _getCredentials() { + try { + const credentials = await fromIni({ + profile: this.params.profile ?? BedrockReranker.defaultOptions.profile, + ignoreCache: true, + })(); + return credentials; + } catch (e) { + console.warn( + `AWS profile with name ${this.params.profile ?? BedrockReranker.defaultOptions.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} diff --git a/core/context/rerankers/index.ts b/core/context/rerankers/index.ts index 9b1db230d..ba6af849c 100644 --- a/core/context/rerankers/index.ts +++ b/core/context/rerankers/index.ts @@ -1,5 +1,6 @@ import { RerankerName } from "../../index.js"; +import { BedrockReranker } from "./bedrock.js"; import { CohereReranker } from "./cohere.js"; import { ContinueProxyReranker } from "./ContinueProxyReranker.js"; import { FreeTrialReranker } from "./freeTrial.js"; @@ -9,9 +10,10 @@ import { VoyageReranker } from "./voyage.js"; export const AllRerankers: { [key in RerankerName]: any } = { cohere: CohereReranker, + bedrock: BedrockReranker, llm: LLMReranker, voyage: VoyageReranker, "free-trial": FreeTrialReranker, "huggingface-tei": HuggingFaceTEIReranker, "continue-proxy": ContinueProxyReranker, -}; +}; \ No newline at end of file diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 57f2b339e..5c82ace95 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -66,7 +66,6 @@ This is the question that you should select relevant files for: "${input}"`; new AbortController().signal, ); const content = renderChatMessage(response); - console.debug("Repo map retrieval response: ", content); if (!content.includes("\n")) { return []; diff --git a/core/core.ts b/core/core.ts index 4dce3ca64..ddfacf5b9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -860,10 +860,7 @@ export class Core { this.indexingCancellationController && !this.indexingCancellationController.signal.aborted ) { - return console.debug( - "Codebase indexing already in progress, skipping indexing of files\n" + - files.join("\n"), - ); + return; } this.indexingCancellationController = new AbortController(); for await (const update of (await this.codebaseIndexerPromise).refreshFiles( diff --git a/core/index.d.ts b/core/index.d.ts index 06fbd7275..cd3518c36 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -807,6 +807,7 @@ type ModelProvider = | "nvidia" | "vllm" | "mock" + | "test" | "cerebras" | "askSage" | "vertexai" @@ -1086,6 +1087,7 @@ export interface EmbeddingsProvider { export type RerankerName = | "cohere" + | "bedrock" | "voyage" | "llm" | "free-trial" diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 6e841f6be..b52577a5f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,9 +7,9 @@ import { ContinueConfig, EmbeddingsProvider, IDE, + IdeInfo, IndexingStatus, SiteIndexingConfig, - IdeInfo, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; @@ -69,7 +69,6 @@ export type AddParams = { favicon?: string; }; - /* General process: - On config update: @@ -476,8 +475,6 @@ export default class DocsService { const embeddings: number[][] = []; // Create embeddings of retrieved articles - console.debug(`Creating embeddings for ${articles.length} articles`); - for (let i = 0; i < articles.length; i++) { const article = articles[i]; diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 1bc74c62e..2ae0e7995 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -25,59 +25,75 @@ function breakdownArticleComponent( max_chunk_size: number, ): Chunk[] { const chunks: Chunk[] = []; - const lines = article.body.split("\n"); let startLine = 0; let endLine = 0; let content = ""; let index = 0; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - if (content.length + line.length <= max_chunk_size) { - content += `${line}\n`; - endLine = i; - } else { - chunks.push({ - content: content.trim(), - startLine: startLine, - endLine: endLine, - otherMetadata: { - title: cleanHeader(article.title), - }, - index: index, - filepath: new URL( - `${subpath}#${cleanFragment(article.title)}`, - url, - ).toString(), - digest: subpath, - }); - content = `${line}\n`; - startLine = i; - endLine = i; - index += 1; - } - } - - // Push the last chunk - if (content) { + const createChunk = ( + chunkContent: string, + chunkStartLine: number, + chunkEndLine: number, + ) => { chunks.push({ - content: content.trim(), - startLine: startLine, - endLine: endLine, + content: chunkContent.trim(), + startLine: chunkStartLine, + endLine: chunkEndLine, otherMetadata: { title: cleanHeader(article.title), }, - index: index, + index: index++, filepath: new URL( `${subpath}#${cleanFragment(article.title)}`, url, ).toString(), digest: subpath, }); + }; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Handle oversized lines by splitting them + if (line.length > max_chunk_size) { + // First push any accumulated content + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); + content = ""; + } + + // Split the long line into chunks + let remainingLine = line; + let subLineStart = i; + while (remainingLine.length > 0) { + const chunk = remainingLine.slice(0, max_chunk_size); + createChunk(chunk, subLineStart, i); + remainingLine = remainingLine.slice(max_chunk_size); + } + startLine = i + 1; + continue; + } + + // Normal line handling + if (content.length + line.length + 1 <= max_chunk_size) { + content += `${line}\n`; + endLine = i; + } else { + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); + } + content = `${line}\n`; + startLine = i; + endLine = i; + } + } + + // Push the last chunk + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); } - // Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model. return chunks.filter((c) => c.content.trim().length > 20); } diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index 5f3880e3c..6f564cce7 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -1,7 +1,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; -class Mock extends BaseLLM { +class MockLLM extends BaseLLM { public completion: string = "Test Completion"; static providerName: ModelProvider = "mock"; @@ -27,4 +27,4 @@ class Mock extends BaseLLM { } } -export default Mock; +export default MockLLM; diff --git a/core/llm/llms/Test.ts b/core/llm/llms/Test.ts new file mode 100644 index 000000000..b35984f3e --- /dev/null +++ b/core/llm/llms/Test.ts @@ -0,0 +1,39 @@ +import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; +import { BaseLLM } from "../index.js"; + +const RESPONSES: Record = { + "How are you?": "I'm fine", +}; + +const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE"; + +class TestLLM extends BaseLLM { + static providerName: ModelProvider = "test"; + + private findResponse(prompt: string) { + return Object.entries(RESPONSES).find(([key]) => prompt.includes(key))?.[1]; + } + + protected async *_streamComplete( + prompt: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + yield this.findResponse(prompt) || `PROMPT: ${prompt}`; + } + + protected async *_streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + for (const char of HARDCODED_CHAT_RESPONSE) { + yield { + role: "assistant", + content: char, + }; + } + } +} + +export default TestLLM; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 632607ed1..9604cb9f6 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -31,7 +31,7 @@ import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; -import Mock from "./Mock"; +import MockLLM from "./Mock"; import Moonshot from "./Moonshot"; import Msty from "./Msty"; import Nebius from "./Nebius"; @@ -50,6 +50,7 @@ import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; import SiliconFlow from "./SiliconFlow"; +import TestLLM from "./Test"; const LLMs = [ Anthropic, @@ -87,7 +88,8 @@ const LLMs = [ Nvidia, Vllm, SambaNova, - Mock, + MockLLM, + TestLLM, Cerebras, Asksage, Nebius, diff --git a/core/util/LruCache.ts b/core/util/LruCache.ts index f6d923fed..86925a6bc 100644 --- a/core/util/LruCache.ts +++ b/core/util/LruCache.ts @@ -1,7 +1,7 @@ export class PrecalculatedLruCache { private items: [string, V][] = []; constructor( - private readonly calculateValue: (key: string) => Promise, + private readonly calculateValue: (key: string) => Promise, private readonly N: number, ) {} @@ -11,7 +11,11 @@ export class PrecalculatedLruCache { if (index < 0) { // Calculate info for new file - const value: V = await this.calculateValue(key); + const value: V | null = await this.calculateValue(key); + + if (value === null) { + return; + } this.items.push([key, value]); if (this.items.length > this.N) { diff --git a/core/util/constants.ts b/core/util/constants.ts new file mode 100644 index 000000000..188fc0005 --- /dev/null +++ b/core/util/constants.ts @@ -0,0 +1 @@ +export const NEW_SESSION_TITLE = "New Session"; diff --git a/core/util/history.test.ts b/core/util/history.test.ts index 048087564..dbcf69619 100644 --- a/core/util/history.test.ts +++ b/core/util/history.test.ts @@ -1,6 +1,7 @@ import { v4 as uuidv4 } from "uuid"; import { Session } from ".."; +import { NEW_SESSION_TITLE } from "./constants"; import historyManager from "./history"; import { getSessionFilePath } from "./paths"; @@ -31,7 +32,7 @@ describe("No sessions have been created", () => { const session = historyManager.load(testSessionId); expect(session).toEqual({ history: [], - title: "Failed to load session", + title: NEW_SESSION_TITLE, workspaceDirectory: "", sessionId: testSessionId, }); diff --git a/core/util/history.ts b/core/util/history.ts index 053c23455..622c2c9ce 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -3,8 +3,8 @@ import * as fs from "fs"; import { Session, SessionMetadata } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; +import { NEW_SESSION_TITLE } from "./constants.js"; import { getSessionFilePath, getSessionsListPath } from "./paths.js"; - function safeParseArray( value: string, errorMessage: string = "Error parsing array", @@ -80,7 +80,7 @@ class HistoryManager { console.log(`Error loading session: ${e}`); return { history: [], - title: "Failed to load session", + title: NEW_SESSION_TITLE, workspaceDirectory: "", sessionId: sessionId, }; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 8029c0609..daa12827d 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -231,7 +231,13 @@ export async function getSymbolsForFile( return; } - const tree = parser.parse(contents); + let tree: Parser.Tree; + try { + tree = parser.parse(contents); + } catch (e) { + console.log(`Error parsing file: ${filepath}`); + return; + } // console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 2c7708cac..024786e14 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -444,7 +444,7 @@ Available connection types: ### `@Debugger` -Reference the contents of the local variables in the debugger. +Reference the contents of the local variables in the debugger. Currently only available in VS Code. ```json title="config.json" { diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index 8d46c5ad9..fb88d5ae0 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -46,9 +46,19 @@ We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazo ## Reranking model -Bedrock currently does not offer any reranking models. +We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`. -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. +```json title="~/.continue/config.json" +{ + "reranker": { + "name": "bedrock", + "params": { + "model": "cohere.rerank-v3-5:0", + "region": "us-west-2" + } + } +} +``` ## Authentication diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 0a5c02aad..df3f08e75 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -206,10 +206,11 @@ Configuration for the reranker model used in response ranking. **Properties:** -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`, `bedrock` - `params`: - `model`: Model name - `apiKey`: Api key + - `region`: Region (for Bedrock only) Example diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index be8b0febb..b469e1e23 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=0.0.82 +pluginVersion=0.0.83 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 6dccf7f08..d0f0da761 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -51,6 +51,7 @@ import java.net.NetworkInterface import java.nio.charset.Charset import java.nio.file.Paths import java.util.* +import kotlin.coroutines.resume fun uuid(): String { @@ -106,7 +107,9 @@ class AsyncFileSaveListener(private val ideProtocolClient: IdeProtocolClient) : for (event in events) { if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith( ".continue\\config.json" - ) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith(".continuerc.json") + ) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith( + ".continuerc.json" + ) ) { return object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { @@ -662,18 +665,41 @@ class IdeProtocolClient( var llm = getModelByRole(config, "applyCodeBlock") if (llm == null) { - val models = (config as? Map<*, *>)?.get("models") as? List> - llm = models?.find { model -> model["title"] == curSelectedModelTitle } as Map + llm = try { + suspendCancellableCoroutine { continuation -> + continuePluginService.coreMessenger?.request( + "config/getSerializedProfileInfo", + null, + null + ) { response -> + val models = + ((response as Map)["config"] as Map)["models"] as List> + val foundModel = models.find { it["title"] == curSelectedModelTitle } - if (llm == null) { - showToast("error", "Model '$curSelectedModelTitle' not found in config.") + if (foundModel == null) { + launch { + showToast( + "error", + "Model '$curSelectedModelTitle' not found in config." + ) + } + continuation.resume(null) + } else { + continuation.resume(foundModel) + } + } + } + } catch (e: Exception) { + launch { showToast("error", "Failed to fetch model configuration") } respond(null) return@launch } } + val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: "" + val prompt = "The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code." diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 5db34ff29..2cf51b5de 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -271,12 +271,6 @@ class ContinueExtensionConfigurable : Configurable { * it's a simple integer without dot notation, making it easier to compare. */ private fun shouldRenderOffScreen(): Boolean { - // With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality - // in the browser. Disabling OSR for all non-Mac users for now. - if (!SystemInfo.isMac) { - return false - } - val minBuildNumber = 233 val applicationInfo = ApplicationInfo.getInstance() val currentBuildNumber = applicationInfo.build.baselineVersion diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 23c012927..f922ad032 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -18,8 +18,9 @@ gui/** continue_rc_schema.json - e2e/_output e2e/.test-extensions e2e/storage e2e/vsix +e2e/test-continue/* +!e2e/test-continue/config.json \ No newline at end of file diff --git a/extensions/vscode/.vscodeignore b/extensions/vscode/.vscodeignore index 9d59dbe5c..387be8ba5 100644 --- a/extensions/vscode/.vscodeignore +++ b/extensions/vscode/.vscodeignore @@ -21,6 +21,7 @@ esbuild.js esbuild.test.mjs importMetaUrl.js scripts +e2e server/exe/** !out/node_modules/** diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index b6f5554c3..cced39cdf 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2648,6 +2648,7 @@ "properties": { "name": { "enum": [ + "bedrock", "cohere", "voyage", "llm", @@ -2749,6 +2750,32 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": ["bedrock"] + } + }, + "required": ["name"] + }, + "then": { + "properties": { + "params": { + "type": "object", + "properties": { + "model": { + "enum": [ + "cohere.rerank-v3-5:0", + "amazon.rerank-v1:0" + ] + } + }, + "required": ["model"] + } + } + } + }, { "if": { "properties": { diff --git a/extensions/vscode/e2e/GUI.test.ts b/extensions/vscode/e2e/GUI.test.ts deleted file mode 100644 index 0055df1ba..000000000 --- a/extensions/vscode/e2e/GUI.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - Workbench, - EditorView, - WebView, - By, - WebElement, - WebDriver, - Key, -} from "vscode-extension-tester"; -import { expect } from "chai"; - -const switchToReactIframe = async (driver: WebDriver) => { - const iframes = await driver.findElements(By.css("iframe")); - let continueIFrame: WebElement | undefined = undefined; - for (let i = 0; i < iframes.length; i++) { - const iframe = iframes[i]; - const src = await iframe.getAttribute("src"); - if (src.includes("extensionId=Continue.continue")) { - continueIFrame = iframe; - break; - } - } - - if (!continueIFrame) { - throw new Error("Could not find continue iframe"); - } - - await driver.switchTo().frame(continueIFrame); - - await new Promise((res) => { - setTimeout(res, 500); - }); - - const reactIFrame = await driver.findElement(By.css("iframe")); - - if (!reactIFrame) { - throw new Error("Could not find React iframe"); - } - - await driver.switchTo().frame(reactIFrame); -}; - -describe("GUI Test", () => { - let view: WebView; - let driver: WebDriver; - - before(async function () { - this.timeout(10000); - - await new Workbench().executeCommand("continue.focusContinueInput"); - - view = new WebView(); - driver = view.getDriver(); - - await switchToReactIframe(driver); - }); - - after(async () => { - await view.switchBack(); - await new EditorView().closeAllEditors(); - }); - - it("should display correct panel description", async () => { - const description = await view.findWebElement( - By.xpath("//*[contains(text(), 'Quickly')]"), - ); - - expect(await description.getText()).has.string( - "Quickly get up and running using our API keys.", - ); - }); - - it("should allow typing text in the editor", async () => { - const tiptap = await view.findWebElement(By.className("tiptap")); - - await tiptap.sendKeys("Hello world!"); - - expect(await tiptap.getText()).has.string("Hello world!"); - - // Just to show that we can - await tiptap.sendKeys(Key.ENTER); - await new Promise((res) => { - setTimeout(res, 5000); - }); - }).timeout(6000); -}); diff --git a/extensions/vscode/e2e/TestUtils.ts b/extensions/vscode/e2e/TestUtils.ts new file mode 100644 index 000000000..05e4bc5d1 --- /dev/null +++ b/extensions/vscode/e2e/TestUtils.ts @@ -0,0 +1,27 @@ +import { WebElement } from "vscode-extension-tester"; + +export class TestUtils { + public static async waitForElement( + locatorFn: () => Promise, + timeout: number = 5000, + interval: number = 500, + ): Promise { + const startTime = Date.now(); + + while (Date.now() - startTime < timeout) { + try { + const element = await locatorFn(); + if (element) { + return element; + } + } catch (e) { + if (Date.now() - startTime >= timeout) { + throw new Error(`Element not found after ${timeout}ms timeout`); + } + } + await new Promise((resolve) => setTimeout(resolve, interval)); + } + + throw new Error(`Element not found after ${timeout}ms timeout`); + } +} diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts new file mode 100644 index 000000000..7a6e76c04 --- /dev/null +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -0,0 +1,59 @@ +import { + WebDriver, + WebElement, + WebView, + Workbench, +} from "vscode-extension-tester"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import { TestUtils } from "../TestUtils"; + +export class GUIActions { + public static switchToReactIframe = async (driver: WebDriver) => { + const iframes = await GUISelectors.getAllIframes(driver); + let continueIFrame: WebElement | undefined = undefined; + for (let i = 0; i < iframes.length; i++) { + const iframe = iframes[i]; + const src = await iframe.getAttribute("src"); + if (src.includes("extensionId=Continue.continue")) { + continueIFrame = iframe; + break; + } + } + + if (!continueIFrame) { + throw new Error("Could not find continue iframe"); + } + + await driver.switchTo().frame(continueIFrame); + + await new Promise((res) => { + setTimeout(res, 500); + }); + + const reactIFrame = await GUISelectors.getReactIframe(driver); + + if (!reactIFrame) { + throw new Error("Could not find React iframe"); + } + + await driver.switchTo().frame(reactIFrame); + }; + + public static openGui = async () => { + return new Workbench().executeCommand("continue.focusContinueInput"); + }; + + public static selectModelFromDropdown = async ( + view: WebView, + option: string, + ) => { + const dropdownButton = await GUISelectors.getModelDropdownButton(view); + await dropdownButton.click(); + + const dropdownOption = await TestUtils.waitForElement(() => { + return GUISelectors.getModelDropdownOption(view, option); + }); + + await dropdownOption.click(); + }; +} diff --git a/extensions/vscode/e2e/selectors/GUI.selectors.ts b/extensions/vscode/e2e/selectors/GUI.selectors.ts new file mode 100644 index 000000000..b4c88aacb --- /dev/null +++ b/extensions/vscode/e2e/selectors/GUI.selectors.ts @@ -0,0 +1,40 @@ +import { By, WebDriver, WebView } from "vscode-extension-tester"; +import { SelectorUtils } from "./SelectorUtils"; + +export class GUISelectors { + public static getDescription(view: WebView) { + return view.findWebElement(By.xpath("//*[contains(text(), 'Quickly')]")); + } + + public static getTipTapEditor(view: WebView) { + return view.findWebElement(By.className("tiptap")); + } + + public static getAllIframes(driver: WebDriver) { + return driver.findElements(By.css("iframe")); + } + + public static getReactIframe(driver: WebDriver) { + return driver.findElement(By.css("iframe")); + } + + public static getSubmitInputButton(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "submit-input-button"); + } + + public static getModelDropdownButton(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "model-select-button"); + } + + public static getModelDropdownOption(view: WebView, option: string) { + return view.findWebElement( + By.xpath(`//*[@role="listbox"]//*[contains(text(), "${option}")]`), + ); + } + + public static getThreadMessageByText(view: WebView, text: string) { + return view.findWebElement( + By.xpath(`//*[@class="thread-message"]//*[contains(text(), "${text}")]`), + ); + } +} diff --git a/extensions/vscode/e2e/selectors/SelectorUtils.ts b/extensions/vscode/e2e/selectors/SelectorUtils.ts new file mode 100644 index 000000000..243e1bf44 --- /dev/null +++ b/extensions/vscode/e2e/selectors/SelectorUtils.ts @@ -0,0 +1,16 @@ +import { By, WebElement, WebView } from "vscode-extension-tester"; + +export class SelectorUtils { + /** + * Finds a web element by its data-testid attribute within a WebView. + * @param view - The WebView to search within. + * @param testId - The data-testid value to search for. + * @returns A promise that resolves to the WebElement found. + */ + public static getElementByDataTestId( + view: WebView, + testId: string, + ): Promise { + return view.findWebElement(By.css(`[data-testid='${testId}']`)); + } +} diff --git a/extensions/vscode/e2e/test-continue/config.json b/extensions/vscode/e2e/test-continue/config.json new file mode 100644 index 000000000..6ffeb7465 --- /dev/null +++ b/extensions/vscode/e2e/test-continue/config.json @@ -0,0 +1,44 @@ +{ + "ui": { + "displayRawMarkdown": false + }, + "models": [ + { + "title": "TEST LLM", + "provider": "test", + "model": "this field is not used" + }, + { + "title": "Mock", + "provider": "mock", + "model": "this field is not used" + } + ], + "analytics": { + "provider": "continue-proxy" + }, + "tabAutocompleteModel": { + "title": "Qwen", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "" + }, + "tabAutocompleteOptions": { + "useCache": false + }, + "contextProviders": [ + { + "name": "docs" + }, + { + "name": "diff" + }, + { + "name": "url" + }, + { + "name": "folder" + } + ], + "docs": [] +} diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts new file mode 100644 index 000000000..6a5e820f8 --- /dev/null +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -0,0 +1,59 @@ +import { + EditorView, + WebView, + WebDriver, + VSBrowser, +} from "vscode-extension-tester"; +import { expect } from "chai"; +import { GUIActions } from "../actions/GUI.actions"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import * as path from "path"; +import { TestUtils } from "../TestUtils"; + +describe("GUI Test", () => { + let view: WebView; + let driver: WebDriver; + + before(async function () { + this.timeout(10000000); + + await VSBrowser.instance.openResources(path.join("e2e/test-continue")); + + await GUIActions.openGui(); + + view = new WebView(); + driver = view.getDriver(); + + await GUIActions.switchToReactIframe(driver); + // await new Promise((res) => { + // setTimeout(res, 10000000); + // }); + }); + + after(async () => { + await view.switchBack(); + await new EditorView().closeAllEditors(); + }); + + it("should display correct panel description", async () => { + const description = await GUISelectors.getDescription(view); + + expect(await description.getText()).has.string( + "Quickly get up and running using our API keys.", + ); + }).timeout(20_000); + + it("should allow typing text in the editor", async () => { + await GUIActions.selectModelFromDropdown(view, "Mock"); + await GUIActions.selectModelFromDropdown(view, "TEST LLM"); + + const tiptap = await GUISelectors.getTipTapEditor(view); + + await tiptap.sendKeys("How are you?"); + (await GUISelectors.getSubmitInputButton(view)).click(); + + await TestUtils.waitForElement(() => + GUISelectors.getThreadMessageByText(view, "I'm fine"), + ); + }).timeout(20_000); +}); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 9de97f4ac..ea5966c13 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.243", + "version": "0.9.240", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.243", + "version": "0.9.240", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -115,7 +115,7 @@ "comment-json": "^4.2.3", "dbinfoz": "^0.14.0", "diff": "^7.0.0", - "dotenv": "^16.4.7", + "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index acc5b947b..9cf7db2b1 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.244", + "version": "0.9.241", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -625,9 +625,11 @@ "e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'", "e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh", "e2e:install-vsix": "extest install-vsix -f ./e2e/vsix/continue.vsix --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", - "e2e:test": "extest run-tests './e2e/_output/*.test.js' --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", - "e2e:all": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:test", - "e2e:ci": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:test" + "e2e:test": "extest run-tests './e2e/_output/tests/*.test.js' --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", + "e2e:clean": "rm -rf ./e2e/_output", + "e2e:all": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", + "e2e:quick": "npm run e2e:compile && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", + "e2e:ci": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test" }, "devDependencies": { "@biomejs/biome": "1.6.4", diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 5d6faef3f..f9d397388 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -101,6 +101,10 @@ export class ContinueCompletionProvider return null; } + if (document.uri.scheme === "vscode-scm") { + return null; + } + // If the text at the range isn't a prefix of the intellisense text, // no completion will be displayed, regardless of what we return if ( diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 28f3f6032..486b0df12 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -408,7 +408,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { return await Promise.race([ codeExchangePromise.promise, new Promise((_, reject) => - setTimeout(() => reject("Cancelled"), 60000), + setTimeout(() => reject("Cancelled"), 15 * 60 * 1_000), ), promiseFromEvent( token.onCancellationRequested, diff --git a/gui/package-lock.json b/gui/package-lock.json index af3d5cafa..91410e6df 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -121,7 +121,7 @@ "comment-json": "^4.2.3", "dbinfoz": "^0.14.0", "diff": "^7.0.0", - "dotenv": "^16.4.7", + "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 8117ce734..96321348c 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -31,9 +31,15 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { const sanitizedSVG = DOMPurify.sanitize(svg); return ( -
); } diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 2f97af73b..1e3997930 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -9,11 +9,11 @@ import { getBasename } from "core/util"; import { useContext, useMemo, useState } from "react"; import { AnimatedEllipsis, lightGray, vscBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; +import { selectIsGatheringContext } from "../../redux/slices/sessionSlice"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; import { getIconFromDropdownItem } from "./MentionList"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsGatheringContext } from "../../redux/slices/sessionSlice"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; @@ -172,7 +172,7 @@ function ContextItemsPeek({ {isGatheringContext ? ( <> - Gathering context... + Gathering context ) : ( diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 9348e5262..f83c27d1e 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -208,6 +208,7 @@ function InputToolbar(props: InputToolbarProps) { )} { if (props.onEnter) { props.onEnter({ diff --git a/gui/src/components/mainInput/handleMetaKeyIssues.ts b/gui/src/components/mainInput/handleMetaKeyIssues.ts index 77cbbb4dc..867203a14 100644 --- a/gui/src/components/mainInput/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/handleMetaKeyIssues.ts @@ -1,8 +1,9 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; -import { isWebEnvironment } from "../../util"; +import { getPlatform, isWebEnvironment } from "../../util"; const isWebEnv = isWebEnvironment(); +const platform = getPlatform(); /** * This handles various keypress issues when OSR is enabled @@ -56,15 +57,48 @@ export const handleVSCMetaKeyIssues = async ( } }; +const deleteSingleWord = (editor: Editor) => { + const textContent = + editor.state.doc.resolve(editor.state.selection.from).parent.textContent ?? + ""; + + const cursorPosition = editor.state.selection.from; + const nodeStartPosition = editor.state.doc.resolve(cursorPosition).start(); + + const textBeforeCursor = textContent.slice( + 0, + cursorPosition - nodeStartPosition, + ); + + // Match the last word including any trailing whitespace + const lastWordMatch = textBeforeCursor.match(/\S+\s*$/); + + if (lastWordMatch) { + const lastWordWithSpace = lastWordMatch[0]; + editor.commands.deleteRange({ + from: editor.state.selection.from - lastWordWithSpace.length, + to: editor.state.selection.from, + }); + } +}; + export const handleJetBrainsMetaBackspace = (editor: Editor) => { const { doc } = editor.state; for (let i = doc.content.childCount - 1; i >= 0; i--) { const node = doc.content.child(i); - if (node.type.name !== "codeBlock") { - editor.commands.deleteNode(node.type.name); + if (node.type.name === "codeBlock") { + continue; } + + // For Linux/Windows, only delete the word to the left of the cursor + if (platform !== "mac") { + deleteSingleWord(editor); + break; + } + + editor.commands.deleteNode(node.type.name); } // Add an empty string so the user can keep typing diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index a4d7fe364..c5edb5d7b 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -316,6 +316,7 @@ function ModelSelect() { >
; llmStreamChat( modelTitle: string, cancelToken: AbortSignal | undefined, messages: ChatMessage[], options?: LLMFullCompletionOptions, - ): AsyncGenerator; + ): AsyncGenerator; ide: IDE; } @@ -147,11 +147,20 @@ export class IdeMessenger implements IIdeMessenger { }); } + /** + * Because of weird type stuff, we're actually yielding an array of the things + * that are streamed. For example, if the return type here says + * AsyncGenerator, then it's actually AsyncGenerator. + * This needs to be handled by the caller. + * + * Using unknown for now to make this more explicit + */ async *streamRequest( messageType: T, data: FromWebviewProtocol[T][0], cancelToken?: AbortSignal, - ): FromWebviewProtocol[T][1] { + ): AsyncGenerator { + // ): FromWebviewProtocol[T][1] { const messageId = uuidv4(); this.post(messageType, data, messageId); @@ -181,17 +190,16 @@ export class IdeMessenger implements IIdeMessenger { while (!done) { if (buffer.length > index) { - const chunk = buffer[index]; - index++; - yield chunk; + const chunks = buffer.slice(index); + index = buffer.length; + yield chunks; } await new Promise((resolve) => setTimeout(resolve, 50)); } - while (buffer.length > index) { - const chunk = buffer[index]; - index++; - yield chunk; + if (buffer.length > index) { + const chunks = buffer.slice(index); + yield chunks; } return returnVal; @@ -202,7 +210,7 @@ export class IdeMessenger implements IIdeMessenger { cancelToken: AbortSignal | undefined, messages: ChatMessage[], options: LLMFullCompletionOptions = {}, - ): AsyncGenerator { + ): AsyncGenerator { const gen = this.streamRequest( "llm/streamChat", { diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 4fcb20035..63252d8f1 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,5 +1,6 @@ import { Dispatch } from "@reduxjs/toolkit"; import { Session, SessionMetadata } from "core"; +import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; import { useCallback, useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -65,7 +66,7 @@ function useHistory(dispatch: Dispatch) { } let currentTitle = title; - if (config?.ui?.getChatTitles && currentTitle === "New Session") { + if (config?.ui?.getChatTitles && currentTitle === NEW_SESSION_TITLE) { try { // Check if we have first assistant response let assistantResponse = history @@ -82,7 +83,7 @@ function useHistory(dispatch: Dispatch) { // Fallback if we get an error above or if the user has not set getChatTitles let newTitle = - currentTitle === "New Session" + currentTitle === NEW_SESSION_TITLE ? truncateText( renderChatMessage(history[0].message) .split("\n") diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 309f536db..851a6f13b 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -7,6 +7,7 @@ import { import { Editor, JSONContent } from "@tiptap/react"; import { InputModifiers, RangeInFileWithContents, ToolCallState } from "core"; import { streamResponse } from "core/llm/stream"; +import { stripImages } from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; @@ -19,22 +20,30 @@ import { vscBackground, } from "../../components"; import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; +import CodeToEditCard from "../../components/CodeToEditCard"; +import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; +import resolveEditorContent from "../../components/mainInput/resolveInput"; import { TutorialCard } from "../../components/mainInput/TutorialCard"; import { OnboardingCard, useOnboardingCard, } from "../../components/OnboardingCard"; +import PageHeader from "../../components/PageHeader"; import StepContainer from "../../components/StepContainer"; +import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; +import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { submitEdit } from "../../redux/slices/editModeState"; import { clearLastEmptyResponse, newSession, @@ -42,6 +51,14 @@ import { selectIsSingleRangeEditOrInsertion, setInactive, } from "../../redux/slices/sessionSlice"; +import { + setDialogEntryOn, + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiSlice"; +import { RootState } from "../../redux/store"; +import { cancelStream } from "../../redux/thunks/cancelStream"; +import { exitEditMode } from "../../redux/thunks/exitEditMode"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { getFontSize, @@ -49,29 +66,12 @@ import { isMetaEquivalentKeyPressed, } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; +import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; -import { - setDialogMessage, - setDialogEntryOn, - setShowDialog, -} from "../../redux/slices/uiSlice"; -import { RootState } from "../../redux/store"; -import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; -import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; -import { submitEdit } from "../../redux/slices/editModeState"; -import { stripImages } from "core/util/messageContent"; -import resolveEditorContent from "../../components/mainInput/resolveInput"; -import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; -import CodeToEditCard from "../../components/CodeToEditCard"; -import { exitEditMode } from "../../redux/thunks/exitEditMode"; -import PageHeader from "../../components/PageHeader"; -import Spinner from "../../components/gui/Spinner"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -204,7 +204,7 @@ export function Chat() { isMetaEquivalentKeyPressed(e) && !e.shiftKey ) { - // dispatch(cancelGeneration()); TODO!!! + dispatch(cancelStream()); } }; window.addEventListener("keydown", listener); @@ -342,7 +342,7 @@ export function Chat() { <> {isInEditMode && ( { loadLastSession().catch((e) => console.error(`Failed to load last session: ${e}`), @@ -496,19 +496,23 @@ export function Chat() { }} >
- {history.length === 0 && getLastSessionId() && !isInEditMode && ( - - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ) - } - className="xs:inline flex hidden items-center gap-2" - > - - Last Session - - )} +
+ {history.length === 0 && getLastSessionId() && !isInEditMode && ( +
+ + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ) + } + className="flex items-center gap-2" + > + + Last Session + +
+ )} +
diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 46e9e21f5..871b1e7eb 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -10,21 +10,22 @@ import { ApplyState, ChatHistoryItem, ChatMessage, + CodeToEdit, + ContextItem, ContextItemWithId, FileSymbolMap, - Session, - PromptLog, - CodeToEdit, - ToolCall, - ContextItem, MessageModes, + PromptLog, + Session, + ToolCall, } from "core"; +import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4 } from "uuid"; +import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; import { findCurrentToolCall } from "../util"; -import { RootState } from "../store"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -86,7 +87,7 @@ function getBaseHistoryItem(): ChatHistoryItemWithMessageId { const initialState: SessionState = { history: [], isStreaming: false, - title: "New Session", + title: NEW_SESSION_TITLE, id: uuidv4(), selectedProfileId: "local", curCheckpointIndex: 0, @@ -284,72 +285,74 @@ export const sessionSlice = createSlice({ state.streamAborter.abort(); state.streamAborter = new AbortController(); }, - streamUpdate: (state, action: PayloadAction) => { + streamUpdate: (state, action: PayloadAction) => { if (state.history.length) { - const lastMessage = state.history[state.history.length - 1]; + for (const message of action.payload) { + const lastMessage = state.history[state.history.length - 1]; - if ( - action.payload.role && - (lastMessage.message.role !== action.payload.role || - // This is when a tool call comes after assistant text - (lastMessage.message.content !== "" && - action.payload.role === "assistant" && - action.payload.toolCalls?.length)) - ) { - const baseHistoryItem = getBaseHistoryItem(); - - // Create a new message - const historyItem: ChatHistoryItemWithMessageId = { - ...baseHistoryItem, - message: { ...baseHistoryItem.message, ...action.payload }, - }; - - if (action.payload.role === "assistant" && action.payload.toolCalls) { - const [_, parsedArgs] = incrementalParseJson( - action.payload.toolCalls[0].function.arguments, - ); - historyItem.toolCallState = { - status: "generating", - toolCall: action.payload.toolCalls[0] as ToolCall, - toolCallId: action.payload.toolCalls[0].id, - parsedArgs, - }; - } - - state.history.push(historyItem); - } else { - // Add to the existing message - const msg = state.history[state.history.length - 1].message; - if (action.payload.content) { - msg.content += renderChatMessage(action.payload); - } else if ( - action.payload.role === "assistant" && - action.payload.toolCalls && - msg.role === "assistant" + if ( + message.role && + (lastMessage.message.role !== message.role || + // This is when a tool call comes after assistant text + (lastMessage.message.content !== "" && + message.role === "assistant" && + message.toolCalls?.length)) ) { - if (!msg.toolCalls) { - msg.toolCalls = []; + const baseHistoryItem = getBaseHistoryItem(); + + // Create a new message + const historyItem: ChatHistoryItemWithMessageId = { + ...baseHistoryItem, + message: { ...baseHistoryItem.message, ...message }, + }; + + if (message.role === "assistant" && message.toolCalls) { + const [_, parsedArgs] = incrementalParseJson( + message.toolCalls[0].function.arguments, + ); + historyItem.toolCallState = { + status: "generating", + toolCall: message.toolCalls[0] as ToolCall, + toolCallId: message.toolCalls[0].id, + parsedArgs, + }; } - action.payload.toolCalls.forEach((toolCall, i) => { - if (msg.toolCalls.length <= i) { - msg.toolCalls.push(toolCall); - } else { - msg.toolCalls[i].function.arguments += - toolCall.function.arguments; - const [_, parsedArgs] = incrementalParseJson( - msg.toolCalls[i].function.arguments, - ); - - state.history[ - state.history.length - 1 - ].toolCallState.parsedArgs = parsedArgs; - state.history[ - state.history.length - 1 - ].toolCallState.toolCall.function.arguments += - toolCall.function.arguments; + state.history.push(historyItem); + } else { + // Add to the existing message + const msg = state.history[state.history.length - 1].message; + if (message.content) { + msg.content += renderChatMessage(message); + } else if ( + message.role === "assistant" && + message.toolCalls && + msg.role === "assistant" + ) { + if (!msg.toolCalls) { + msg.toolCalls = []; } - }); + message.toolCalls.forEach((toolCall, i) => { + if (msg.toolCalls.length <= i) { + msg.toolCalls.push(toolCall); + } else { + msg.toolCalls[i].function.arguments += + toolCall.function.arguments; + + const [_, parsedArgs] = incrementalParseJson( + msg.toolCalls[i].function.arguments, + ); + + state.history[ + state.history.length - 1 + ].toolCallState.parsedArgs = parsedArgs; + state.history[ + state.history.length - 1 + ].toolCallState.toolCall.function.arguments += + toolCall.function.arguments; + } + }); + } } } } diff --git a/gui/src/redux/thunks/cancelStream.ts b/gui/src/redux/thunks/cancelStream.ts new file mode 100644 index 000000000..dc23c04a6 --- /dev/null +++ b/gui/src/redux/thunks/cancelStream.ts @@ -0,0 +1,15 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { abortStream, setInactive } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; + +export const cancelStream = createAsyncThunk( + "chat/cancelStream", + async (messages, { dispatch, extra, getState }) => { + dispatch(setInactive()); + dispatch(abortStream()); + + // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box + // TODO: Waiting until next release + // dispatch(clearLastEmptyResponse()); + }, +); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 3c3c49222..5a22a36b5 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,6 +1,7 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatMessage, PromptLog } from "core"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { selectDefaultModel } from "../slices/configSlice"; import { abortStream, addPromptCompletionPair, @@ -10,7 +11,6 @@ import { } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { callTool } from "./callTool"; -import { selectDefaultModel } from "../slices/configSlice"; export const streamNormalInput = createAsyncThunk< void, @@ -56,14 +56,9 @@ export const streamNormalInput = createAsyncThunk< break; } - const update = next.value as ChatMessage; - dispatch(streamUpdate(update)); + const updates = next.value as ChatMessage[]; + dispatch(streamUpdate(updates)); next = await gen.next(); - - // There has been lag when streaming tool calls. This is a temporary solution - if (update.role === "assistant" && update.toolCalls) { - await new Promise((resolve) => setTimeout(resolve, 10)); - } } // Attach prompt log diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 0fe588f56..52b15c13f 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -2,6 +2,7 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatMessage, ContextItem } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; +import { selectDefaultModel } from "../slices/configSlice"; import { addContextItemsAtIndex, setActive, @@ -11,7 +12,6 @@ import { ThunkApiType } from "../store"; import { handleErrors } from "./handleErrors"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; -import { selectDefaultModel } from "../slices/configSlice"; export const streamResponseAfterToolCall = createAsyncThunk< void, @@ -39,7 +39,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< toolCallId, }; - dispatch(streamUpdate(newMessage)); + dispatch(streamUpdate([newMessage])); dispatch( addContextItemsAtIndex({ index: initialHistory.length, diff --git a/gui/src/redux/thunks/streamSlashCommand.ts b/gui/src/redux/thunks/streamSlashCommand.ts index 314b5cc53..79336bb3d 100644 --- a/gui/src/redux/thunks/streamSlashCommand.ts +++ b/gui/src/redux/thunks/streamSlashCommand.ts @@ -5,9 +5,9 @@ import { RangeInFile, SlashCommandDescription, } from "core"; -import { ThunkApiType } from "../store"; -import { abortStream, streamUpdate } from "../slices/sessionSlice"; import { selectDefaultModel } from "../slices/configSlice"; +import { abortStream, streamUpdate } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; export const streamSlashCommand = createAsyncThunk< void, @@ -62,8 +62,17 @@ export const streamSlashCommand = createAsyncThunk< dispatch(abortStream()); break; } - if (typeof update === "string") { - dispatch(streamUpdate(update)); + for (const item of update) { + if (typeof item === "string") { + dispatch( + streamUpdate([ + { + role: "assistant", + content: item, + }, + ]), + ); + } } } clearInterval(checkActiveInterval);