From 2483abdc7b498d02d6c0405662f7c70890a4f33b Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Fri, 14 Feb 2025 09:43:32 -0500 Subject: [PATCH 001/324] Reliably trigger VSCode extension rebuild The code to trigger a rebuild on missing extension.js added in https://github.com/continuedev/continue/pull/3276 turns out not to be entirely reliable because esbuild sometimes falls back to full-contents comparison rather than using the modtime. To fix this, include a buildTimestamp file in the input, and rewrite that when we want to trigger a rebuild. --- extensions/vscode/.gitignore | 1 + extensions/vscode/scripts/esbuild.js | 11 +++++++---- extensions/vscode/scripts/prepackage.js | 5 ++++- extensions/vscode/scripts/utils.js | 15 +++++++++++++++ extensions/vscode/src/extension.ts | 1 + 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 29ad0b023..aa99f752c 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -3,6 +3,7 @@ node_modules/ out/ .vscode-test/ data/ +src/.buildTimestamp.ts src/client .continue diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index e44fc60af..c46efc427 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -1,5 +1,6 @@ const esbuild = require("esbuild"); const fs = require("fs"); +const { writeBuildTimestamp } = require("./utils"); const flags = process.argv.slice(2); @@ -48,6 +49,8 @@ const esbuildConfig = { }; (async () => { + // Create .buildTimestamp.js before starting the first build + writeBuildTimestamp(); // Bundles the extension into one file if (flags.includes("--watch")) { const ctx = await esbuild.context(esbuildConfig); @@ -59,9 +62,9 @@ const esbuildConfig = { // The watcher automatically notices changes to source files // so the only thing it needs to be notified about is if the // output file gets removed. - if (fs.existsSync (outFile)) { - console.log("VS Code Extension esbuild up to date"); - return; + if (fs.existsSync(outFile)) { + console.log("VS Code Extension esbuild up to date"); + return; } fs.watchFile(outFile, (current, previous) => { @@ -73,7 +76,7 @@ const esbuildConfig = { }); console.log("Triggering VS Code Extension esbuild rebuild..."); - fs.utimesSync(inFile, new Date(), new Date()); + writeBuildTimestamp(); } else { await esbuild.build(esbuildConfig); } diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index aeab677ca..fbec94f6c 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,7 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema } = require("./utils"); +const { copyConfigSchema, writeBuildTimestamp } = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -71,6 +71,9 @@ const isMacTarget = target?.startsWith("darwin"); process.chdir("extensions/vscode"); } + // Make sure we have an initial timestamp file + writeBuildTimestamp(); + // Install node_modules // execCmdSync("npm install"); console.log("[info] npm install in extensions/vscode completed"); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index c4d392cfa..8a144731f 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -511,6 +511,20 @@ async function copyScripts() { console.log("[info] Copied script files"); } +// We can't simply touch one of our files to trigger a rebuild, because +// esbuild doesn't always use modifications times to detect changes - +// for example, if it finds a file changed within the last 3 seconds, +// it will fall back to full-contents-comparison for that file +// +// So to facilitate development workflows, we always include a timestamp string +// in the build +function writeBuildTimestamp() { + fs.writeFileSync( + "src/.buildTimestamp.ts", + `export default "${new Date().toISOString()}";\n`, + ); +} + module.exports = { copyConfigSchema, installNodeModules, @@ -526,4 +540,5 @@ module.exports = { downloadRipgrepBinary, copyTokenizers, copyScripts, + writeBuildTimestamp, }; diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index f1aa3f3e4..be2b12487 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -8,6 +8,7 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; +export { default as buildTimestamp } from "./.buildTimestamp"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { await setupCa(); From 36673464768720d42854e4eb04b159c0f144a81f Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Mon, 24 Feb 2025 18:20:27 -0500 Subject: [PATCH 002/324] pr_checks: write build timestamp before running tsc --- .github/workflows/pr_checks.yaml | 1 + extensions/vscode/package.json | 1 + extensions/vscode/scripts/write-build-timestamp.js | 3 +++ 3 files changed, 5 insertions(+) create mode 100644 extensions/vscode/scripts/write-build-timestamp.js diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7c005de7b..b0c1da5bd 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -250,6 +250,7 @@ jobs: - name: Type check and lint run: | cd extensions/vscode + npm run write-build-timestamp npx tsc --noEmit npm run lint diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index a25aecbd5..4a3cf4272 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -589,6 +589,7 @@ "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", "package": "node scripts/package.js", "package-all": "node scripts/package-all.js", diff --git a/extensions/vscode/scripts/write-build-timestamp.js b/extensions/vscode/scripts/write-build-timestamp.js new file mode 100644 index 000000000..a26f9b8d3 --- /dev/null +++ b/extensions/vscode/scripts/write-build-timestamp.js @@ -0,0 +1,3 @@ +const { writeBuildTimestamp } = require("./utils"); + +writeBuildTimestamp(); From defb963cfc9ac3213f841afe3d29d393efd9c2ff Mon Sep 17 00:00:00 2001 From: ferenci84 Date: Fri, 21 Mar 2025 15:19:56 +0100 Subject: [PATCH 003/324] update last file save timestamp and implement caching in diff calculation --- .../ContinuePluginStartupActivity.kt | 3 ++ .../continue/IdeProtocolClient.kt | 9 +++++ .../continue/IntelliJIde.kt | 33 ++++++++++++++++++- .../services/ContinuePluginService.kt | 4 +++ .../continueintellijextension/types.kt | 4 +++ 5 files changed, 52 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 9d48705df..e1da218c5 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -1,4 +1,5 @@ package com.github.continuedev.continueintellijextension.activities +import IntelliJIDE import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService @@ -185,6 +186,8 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { // Notify core of content changes if (changedURIs.isNotEmpty()) { + continuePluginService.updateLastFileSaveTimestamp() + val data = mapOf("uris" to changedURIs) continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> } } 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 268a7674f..6a01d697f 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 @@ -45,6 +45,10 @@ class IdeProtocolClient( ) } + fun updateLastFileSaveTimestamp() { + (ide as IntelliJIDE).updateLastFileSaveTimestamp() + } + fun handleMessage(msg: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val message = Gson().fromJson(msg, Message::class.java) @@ -202,6 +206,11 @@ class IdeProtocolClient( respond(null) } + "updateLastFileSaveTimestamp" -> { + (ide as IntelliJIDE).updateLastFileSaveTimestamp() + respond(null) + } + "showVirtualFile" -> { val params = Gson().fromJson( dataElement.toString(), diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index e903e1238..9819a4afe 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -51,8 +51,19 @@ import java.nio.file.Paths class IntelliJIDE( private val project: Project, private val continuePluginService: ContinuePluginService, + private var lastFileSaveTimestamp: Long = System.currentTimeMillis() + +) : IDE { + + // Add a simple cache for diff results + private data class DiffCache( + val timestamp: Long, + val diffs: List + ) + + // Cache the last diff result + private var diffCache: DiffCache? = null - ) : IDE { private val ripgrep: String init { @@ -66,6 +77,14 @@ class IntelliJIDE( Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString() } + /** + * Updates the timestamp when a file is saved + */ + override fun updateLastFileSaveTimestamp() { + println("Updating last file save timestamp") + lastFileSaveTimestamp = System.currentTimeMillis() + } + override suspend fun getIdeInfo(): IdeInfo { val applicationInfo = ApplicationInfo.getInstance() val ideName: String = applicationInfo.fullApplicationName @@ -110,6 +129,16 @@ class IntelliJIDE( } override suspend fun getDiff(includeUnstaged: Boolean): List { + println("Getting diff, cache timestamp: ${diffCache?.timestamp}, current timestamp: $lastFileSaveTimestamp") + + // Check if we have a valid cache entry + if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) { + println("Using cached diff") + return diffCache!!.diffs + } + + // If no cache hit, compute the diff + println("Computing fresh diff") val workspaceDirs = workspaceDirectories() val diffs = mutableListOf() @@ -144,6 +173,8 @@ class IntelliJIDE( diffs.add(output.toString()) } + // Cache the result + diffCache = DiffCache(lastFileSaveTimestamp, diffs) return diffs } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index cf1005596..d3b8ea68a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -41,4 +41,8 @@ class ContinuePluginService : Disposable, DumbAware { ) { continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId) } + + fun updateLastFileSaveTimestamp() { + ideProtocolClient?.updateLastFileSaveTimestamp() + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 7dfa83da4..5d340ede0 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -192,6 +192,10 @@ interface IDE { // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) + + fun updateLastFileSaveTimestamp() { + // Default implementation does nothing + } } data class GetGhTokenArgs( From af26eae4047ce4b7b125f97e6dee69a155da6f8a Mon Sep 17 00:00:00 2001 From: ferenci84 Date: Sat, 22 Mar 2025 07:02:34 +0100 Subject: [PATCH 004/324] Refactor IntelliJIDE to use GitService for diff and timestamp updates, and fix minor issues --- .../continue/IdeProtocolClient.kt | 5 -- .../continue/IntelliJIde.kt | 89 ++----------------- manual-testing-sandbox/test.kt | 3 +- 3 files changed, 10 insertions(+), 87 deletions(-) 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 6a01d697f..95270f26b 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 @@ -206,11 +206,6 @@ class IdeProtocolClient( respond(null) } - "updateLastFileSaveTimestamp" -> { - (ide as IntelliJIDE).updateLastFileSaveTimestamp() - respond(null) - } - "showVirtualFile" -> { val params = Gson().fromJson( dataElement.toString(), diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 9819a4afe..6f0538159 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -1,13 +1,9 @@ import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.`continue`.GitService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.OS -import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID -import com.github.continuedev.continueintellijextension.utils.getOS -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.Desktop -import com.google.gson.Gson +import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil @@ -31,12 +27,7 @@ import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile -import com.intellij.util.containers.toArray import kotlinx.coroutines.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.RequestBody.Companion.toRequestBody import java.awt.Toolkit import java.awt.datatransfer.DataFlavor import java.io.BufferedReader @@ -44,25 +35,17 @@ import java.io.File import java.io.FileInputStream import java.io.InputStreamReader import java.net.URI -import java.net.URL import java.nio.charset.Charset import java.nio.file.Paths class IntelliJIDE( private val project: Project, private val continuePluginService: ContinuePluginService, - private var lastFileSaveTimestamp: Long = System.currentTimeMillis() ) : IDE { - // Add a simple cache for diff results - private data class DiffCache( - val timestamp: Long, - val diffs: List - ) + private val gitService = GitService(project, continuePluginService) - // Cache the last diff result - private var diffCache: DiffCache? = null private val ripgrep: String @@ -81,8 +64,7 @@ class IntelliJIDE( * Updates the timestamp when a file is saved */ override fun updateLastFileSaveTimestamp() { - println("Updating last file save timestamp") - lastFileSaveTimestamp = System.currentTimeMillis() + gitService.updateLastFileSaveTimestamp() } override suspend fun getIdeInfo(): IdeInfo { @@ -129,53 +111,7 @@ class IntelliJIDE( } override suspend fun getDiff(includeUnstaged: Boolean): List { - println("Getting diff, cache timestamp: ${diffCache?.timestamp}, current timestamp: $lastFileSaveTimestamp") - - // Check if we have a valid cache entry - if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) { - println("Using cached diff") - return diffCache!!.diffs - } - - // If no cache hit, compute the diff - println("Computing fresh diff") - val workspaceDirs = workspaceDirectories() - val diffs = mutableListOf() - - for (workspaceDir in workspaceDirs) { - val output = StringBuilder() - val builder = if (includeUnstaged) { - ProcessBuilder("git", "diff") - } else { - ProcessBuilder("git", "diff", "--cached") - } - builder.directory(File(URI(workspaceDir))) - val process = withContext(Dispatchers.IO) { - builder.start() - } - - val reader = BufferedReader(InputStreamReader(process.inputStream)) - var line: String? = withContext(Dispatchers.IO) { - reader.readLine() - } - while (line != null) { - output.append(line) - output.append("\n") - line = withContext(Dispatchers.IO) { - reader.readLine() - } - } - - withContext(Dispatchers.IO) { - process.waitFor() - } - - diffs.add(output.toString()) - } - - // Cache the result - diffCache = DiffCache(lastFileSaveTimestamp, diffs) - return diffs + return gitService.getDiff(includeUnstaged) } override suspend fun getClipboardContent(): Map { @@ -212,11 +148,11 @@ class IntelliJIDE( } override suspend fun getWorkspaceDirs(): List { - return workspaceDirectories().toList() + return gitService.workspaceDirectories().toList() } override suspend fun getWorkspaceConfigs(): List { - val workspaceDirs = workspaceDirectories() + val workspaceDirs = gitService.workspaceDirectories() val configs = mutableListOf() @@ -465,7 +401,7 @@ class IntelliJIDE( } override suspend fun getTags(artifactId: String): List { - val workspaceDirs = workspaceDirectories() + val workspaceDirs = gitService.workspaceDirectories() // Collect branches concurrently using Kotlin coroutines val branches = withContext(Dispatchers.IO) { @@ -599,13 +535,4 @@ class IntelliJIDE( } } - private fun workspaceDirectories(): Array { - val dirs = this.continuePluginService.workspacePaths - - if (dirs?.isNotEmpty() == true) { - return dirs - } - - return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() - } } \ No newline at end of file diff --git a/manual-testing-sandbox/test.kt b/manual-testing-sandbox/test.kt index 683993e81..847019508 100644 --- a/manual-testing-sandbox/test.kt +++ b/manual-testing-sandbox/test.kt @@ -3,7 +3,8 @@ class Test { fun add(number: Double): Test { result += number - return this + + return } fun subtract(number: Double): Test { From 57818c335acf81e484032805b2251b2a723c3c4b Mon Sep 17 00:00:00 2001 From: ferenci84 Date: Sat, 22 Mar 2025 08:16:09 +0100 Subject: [PATCH 005/324] revert --- manual-testing-sandbox/test.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/manual-testing-sandbox/test.kt b/manual-testing-sandbox/test.kt index 847019508..683993e81 100644 --- a/manual-testing-sandbox/test.kt +++ b/manual-testing-sandbox/test.kt @@ -3,8 +3,7 @@ class Test { fun add(number: Double): Test { result += number - - return + return this } fun subtract(number: Double): Test { From 19d6246fc7088e222adff3458b259fdd06040993 Mon Sep 17 00:00:00 2001 From: ferenci84 Date: Sat, 22 Mar 2025 17:27:28 +0100 Subject: [PATCH 006/324] git service --- .../continue/GitService.kt | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt new file mode 100644 index 000000000..45132dbf9 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt @@ -0,0 +1,94 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.toUriOrNull +import com.intellij.openapi.project.Project +import com.intellij.openapi.project.guessProjectDir +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.BufferedReader +import java.io.File +import java.io.InputStreamReader +import java.net.URI + +class GitService( + private val project: Project, + private val continuePluginService: ContinuePluginService +) { + // Add a simple cache for diff results + private data class DiffCache( + val timestamp: Long, + val diffs: List + ) + + // Cache the last diff result + private var diffCache: DiffCache? = null + private var lastFileSaveTimestamp: Long = System.currentTimeMillis() + + /** + * Updates the timestamp when a file is saved + */ + fun updateLastFileSaveTimestamp() { + lastFileSaveTimestamp = System.currentTimeMillis() + } + + /** + * Returns the git diff for all workspace directories + */ + suspend fun getDiff(includeUnstaged: Boolean): List { + // Check if we have a valid cache entry + if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) { + return diffCache!!.diffs + } + + // If no cache hit, compute the diff + val workspaceDirs = workspaceDirectories() + val diffs = mutableListOf() + + for (workspaceDir in workspaceDirs) { + val output = StringBuilder() + val builder = if (includeUnstaged) { + ProcessBuilder("git", "diff") + } else { + ProcessBuilder("git", "diff", "--cached") + } + builder.directory(File(URI(workspaceDir))) + val process = withContext(Dispatchers.IO) { + builder.start() + } + + val reader = BufferedReader(InputStreamReader(process.inputStream)) + var line: String? = withContext(Dispatchers.IO) { + reader.readLine() + } + while (line != null) { + output.append(line) + output.append("\n") + line = withContext(Dispatchers.IO) { + reader.readLine() + } + } + + withContext(Dispatchers.IO) { + process.waitFor() + } + + diffs.add(output.toString()) + } + + // Cache the result + diffCache = DiffCache(lastFileSaveTimestamp, diffs) + return diffs + } + + fun workspaceDirectories(): Array { + val dirs = this.continuePluginService.workspacePaths + + if (dirs?.isNotEmpty() == true) { + return dirs + } + + return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() + } + +} \ No newline at end of file From cd9be776c25b9625298a4501d62ee551818acd8d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Mar 2025 09:45:15 +0000 Subject: [PATCH 007/324] Bump apple-actions/import-codesign-certs from 3 to 5 Bumps [apple-actions/import-codesign-certs](https://github.com/apple-actions/import-codesign-certs) from 3 to 5. - [Release notes](https://github.com/apple-actions/import-codesign-certs/releases) - [Commits](https://github.com/apple-actions/import-codesign-certs/compare/v3...v5) --- updated-dependencies: - dependency-name: apple-actions/import-codesign-certs dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index bf2fa74a6..a968dcc19 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -54,7 +54,7 @@ jobs: ref: ${{ github.event.release.tag_name }} - name: Import Apple certificate - uses: apple-actions/import-codesign-certs@v3 + uses: apple-actions/import-codesign-certs@v5 with: keychain: ${{ github.run_id }} keychain-password: ${{ github.run_id }} From ce7d98291e30658b387dd5d7de96e0f3577065ab Mon Sep 17 00:00:00 2001 From: Usama Nasar Date: Mon, 24 Mar 2025 21:08:04 +0500 Subject: [PATCH 008/324] feat: create stream complete reducer --- gui/src/redux/slices/sessionSlice.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index ba6ff25e1..54470b4b3 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -432,6 +432,13 @@ export const sessionSlice = createSlice({ } } }, + streamComplete: (state) => { + const lastItem = state.history[state.history.length - 1]; + if (lastItem.reasoning?.active) { + lastItem.reasoning.active = false; + lastItem.reasoning.endAt = Date.now(); + } + }, newSession: (state, { payload }: PayloadAction) => { state.lastSessionId = state.id; @@ -723,6 +730,7 @@ export const { addContextItemsAtIndex, setInactive, streamUpdate, + streamComplete, newSession, updateSessionTitle, addHighlightedCode, From 51096858ab1ddc2bee534c1ea848be2b4bdcfb3f Mon Sep 17 00:00:00 2001 From: Usama Nasar Date: Mon, 24 Mar 2025 21:36:01 +0500 Subject: [PATCH 009/324] fix: end thinking for reasoning models when request is complete --- gui/src/redux/slices/sessionSlice.ts | 14 ++++++-------- gui/src/redux/thunks/streamNormalInput.ts | 4 ++-- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 54470b4b3..5aa714acc 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -111,6 +111,12 @@ export const sessionSlice = createSlice({ lastMessage.promptLogs = lastMessage.promptLogs ? lastMessage.promptLogs.concat(payload) : payload; + + // Inactive thinking for reasoning models when '' tag is not received on request completion + if (lastMessage.reasoning?.active) { + lastMessage.reasoning.active = false; + lastMessage.reasoning.endAt = Date.now(); + } }, setActive: (state) => { state.isStreaming = true; @@ -432,13 +438,6 @@ export const sessionSlice = createSlice({ } } }, - streamComplete: (state) => { - const lastItem = state.history[state.history.length - 1]; - if (lastItem.reasoning?.active) { - lastItem.reasoning.active = false; - lastItem.reasoning.endAt = Date.now(); - } - }, newSession: (state, { payload }: PayloadAction) => { state.lastSessionId = state.id; @@ -730,7 +729,6 @@ export const { addContextItemsAtIndex, setInactive, streamUpdate, - streamComplete, newSession, updateSessionTitle, addHighlightedCode, diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 41d7a9587..d27633a05 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -9,7 +9,7 @@ import { addPromptCompletionPair, selectUseTools, setToolGenerated, - streamUpdate, + streamUpdate } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { callTool } from "./callTool"; @@ -71,7 +71,7 @@ export const streamNormalInput = createAsyncThunk< next = await gen.next(); } - // Attach prompt log + // Attach prompt log and end thinking for reasoning models if (next.done && next.value) { dispatch(addPromptCompletionPair([next.value])); From 075b785e192a9f992b14533908c6bade6fa540a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Dywicki?= Date: Tue, 25 Mar 2025 21:33:53 +0400 Subject: [PATCH 010/324] Use fetchwithRequestOptions for all calls in WatsonX. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Łukasz Dywicki --- core/llm/llms/WatsonX.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 561f4f2d9..7f1fe2e0c 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -21,7 +21,7 @@ class WatsonX extends BaseLLM { if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS const wxToken = await ( - await fetch( + await this.fetch( `https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", @@ -48,7 +48,7 @@ class WatsonX extends BaseLLM { // Using username/password auth const userPass = this.apiKey?.split(":"); const wxToken = await ( - await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, { + await this.fetch(`${this.apiBase}/icp4d-api/v1/authorize`, { method: "POST", headers: { "Content-Type": "application/json", @@ -61,7 +61,7 @@ class WatsonX extends BaseLLM { }) ).json(); const wxTokenExpiry = await ( - await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, { + await this.fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, { method: "GET", headers: { Accept: "application/json", From c12bc10b8d81c05304b3eb28968aa92c2340d7fa Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 26 Mar 2025 17:11:19 -0700 Subject: [PATCH 011/324] tweaks --- core/llm/llms/Anthropic.ts | 62 ++++++++++++------- .../definitions/readCurrentlyOpenFile.ts | 2 +- core/tools/definitions/readFile.ts | 2 +- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 2 +- .../openai-adapters/src/apis/Anthropic.ts | 1 - 5 files changed, 41 insertions(+), 28 deletions(-) diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index cd48ef41b..b9e51fd28 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,15 +30,17 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), - thinking: options.reasoning ? { - type: "enabled", - budget_tokens: options.reasoningBudgetTokens, - } : undefined, + thinking: options.reasoning + ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } + : undefined, tool_choice: options.toolChoice ? { - type: "tool", - name: options.toolChoice.function.name, - } + type: "tool", + name: options.toolChoice.function.name, + } : undefined, }; @@ -70,19 +72,23 @@ class Anthropic extends BaseLLM { } else if (message.role === "thinking" && !message.redactedThinking) { return { role: "assistant", - content: [{ - type: "thinking", - thinking: message.content, - signature: message.signature - }] + content: [ + { + type: "thinking", + thinking: message.content, + signature: message.signature, + }, + ], }; } else if (message.role === "thinking" && message.redactedThinking) { return { role: "assistant", - content: [{ - type: "redacted_thinking", - data: message.redactedThinking - }] + content: [ + { + type: "redacted_thinking", + data: message.redactedThinking, + }, + ], }; } @@ -195,12 +201,12 @@ class Anthropic extends BaseLLM { messages: msgs, system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), signal, @@ -240,7 +246,11 @@ class Anthropic extends BaseLLM { // handle redacted thinking if (value.content_block.type === "redacted_thinking") { console.log("redacted thinking", value.content_block.data); - yield { role: "thinking", content: "", redactedThinking: value.content_block.data }; + yield { + role: "thinking", + content: "", + redactedThinking: value.content_block.data, + }; } break; case "content_block_delta": @@ -253,7 +263,11 @@ class Anthropic extends BaseLLM { yield { role: "thinking", content: value.delta.thinking }; break; case "signature_delta": - yield { role: "thinking", content: "", signature: value.delta.signature }; + yield { + role: "thinking", + content: "", + signature: value.delta.signature, + }; break; case "input_json_delta": if (!lastToolUseId || !lastToolUseName) { diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index f4df8e1e5..eacaab70d 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = { displayTitle: "Read Currently Open File", wouldLikeTo: "read the current file", isCurrently: "reading the current file", - hasAlready: "read the current file", + hasAlready: "viewed the current file", readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 0133b54b0..ff5d58a31 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -6,7 +6,7 @@ export const readFileTool: Tool = { displayTitle: "Read File", wouldLikeTo: "read {{{ filepath }}}", isCurrently: "reading {{{ filepath }}}", - hasAlready: "read {{{ filepath }}}", + hasAlready: "viewed {{{ filepath }}}", readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 47868cfc8..24a131440 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -54,7 +54,7 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) { Mustache.render(tool.isCurrently, props.toolCallState.parsedArgs) ) : ( <> - using the {defaultToolDescription} + calling the {defaultToolDescription} ); } else if (props.toolCallState.status === "done") { diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 04b0fbce9..36c33e550 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -175,7 +175,6 @@ export class AnthropicApi implements BaseLlmApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - body.messages; const response = await customFetch(this.config.requestOptions)( new URL("messages", this.apiBase), { From debeca96d244b9bf90e995d7797be8f95c7521d3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 26 Mar 2025 21:09:47 -0700 Subject: [PATCH 012/324] prune both tool calls --- core/llm/countTokens.ts | 29 +++++++++++++------ core/llm/index.ts | 15 +++++----- core/llm/llms/Anthropic.ts | 6 ++++ .../components/mainInput/Lump/LumpToolbar.tsx | 8 ++--- gui/src/redux/thunks/streamNormalInput.ts | 10 +++++-- packages/openai-adapters/src/apis/OpenAI.ts | 3 +- 6 files changed, 43 insertions(+), 28 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index a05889c52..16ac82100 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -27,9 +27,9 @@ class LlamaEncoding implements Encoding { } class NonWorkerAsyncEncoder implements AsyncEncoder { - constructor(private readonly encoding: Encoding) { } + constructor(private readonly encoding: Encoding) {} - async close(): Promise { } + async close(): Promise {} async encode(text: string): Promise { return this.encoding.encode(text); @@ -313,8 +313,21 @@ function pruneChatHistory( // 4. Remove entire messages in the last 5, except last 1 while (totalTokens > contextLength && chatHistory.length > 1) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + // If tool call/response detected prune both (can't have response with no call) + // TODO prune lines from tool response before pruning both messages + if ( + chatHistory.length > 2 && + messageHasToolCalls(chatHistory[0]) && + chatHistory[1].role === "tool" + ) { + const firstMessage = chatHistory.shift()!; + const secondMessage = chatHistory.shift()!; + totalTokens -= countTokens(firstMessage.content, modelName); + totalTokens -= countTokens(secondMessage.content, modelName); + } else { + const message = chatHistory.shift()!; + totalTokens -= countTokens(message.content, modelName); + } } // 5. Truncate last message @@ -328,7 +341,6 @@ function pruneChatHistory( ); totalTokens = contextLength; } - return chatHistory; } @@ -384,8 +396,8 @@ function compileChatMessages( ): ChatMessage[] { let msgsCopy = msgs ? msgs - .map((msg) => ({ ...msg })) - .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") + .map((msg) => ({ ...msg })) + .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") : []; msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); @@ -470,6 +482,5 @@ export { pruneLinesFromTop, pruneRawPromptFromTop, pruneStringFromBottom, - pruneStringFromTop + pruneStringFromTop, }; - diff --git a/core/llm/index.ts b/core/llm/index.ts index dda2e7a87..d4c53b895 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -195,11 +195,11 @@ export abstract class BaseLLM implements ILLM { options.completionOptions?.maxTokens ?? (llmInfo?.maxCompletionTokens ? Math.min( - llmInfo.maxCompletionTokens, - // Even if the model has a large maxTokens, we don't want to use that every time, - // because it takes away from the context length - this.contextLength / 4, - ) + llmInfo.maxCompletionTokens, + // Even if the model has a large maxTokens, we don't want to use that every time, + // because it takes away from the context length + this.contextLength / 4, + ) : DEFAULT_MAX_TOKENS), }; this.requestOptions = options.requestOptions; @@ -840,7 +840,6 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { - if (chunk.role === "assistant") { completion += chunk.content; yield chunk; @@ -948,7 +947,7 @@ export abstract class BaseLLM implements ILLM { ); } - protected async * _streamComplete( + protected async *_streamComplete( prompt: string, signal: AbortSignal, options: CompletionOptions, @@ -956,7 +955,7 @@ export abstract class BaseLLM implements ILLM { throw new Error("Not implemented"); } - protected async * _streamChat( + protected async *_streamChat( messages: ChatMessage[], signal: AbortSignal, options: CompletionOptions, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index b9e51fd28..6d1628f2a 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,6 +1,7 @@ import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; +import { LlmApiRequestType } from "../openaiTypeConverters.js"; import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { @@ -15,6 +16,11 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ + "streamChat", + "chat", + ]; + public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI const finalOptions = { diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index cca7885d3..e93746726 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -2,10 +2,7 @@ import { useContext } from "react"; import styled from "styled-components"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { - clearLastEmptyResponse, - setInactive, -} from "../../../redux/slices/sessionSlice"; +import { cancelStream } from "../../../redux/thunks/cancelStream"; import { getFontSize, getMetaKeyLabel } from "../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; @@ -54,8 +51,7 @@ export function LumpToolbar(props: TopToolbarProps) { { - dispatch(setInactive()); - dispatch(clearLastEmptyResponse()); + dispatch(cancelStream()); }} > {getMetaKeyLabel()} ⌫ Cancel diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 41d7a9587..509a03f7b 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -37,7 +37,7 @@ export const streamNormalInput = createAsyncThunk< if (!defaultModel) { throw new Error("Default model not defined"); } - + // debugger; const includeTools = useTools && modelSupportsTools(defaultModel); // Send request @@ -76,7 +76,7 @@ export const streamNormalInput = createAsyncThunk< dispatch(addPromptCompletionPair([next.value])); try { - if (state.session.mode === "chat") { + if (state.session.mode === "chat" || state.session.mode === "agent") { extra.ideMessenger.post("devdata/log", { name: "chatInteraction", data: { @@ -103,7 +103,11 @@ export const streamNormalInput = createAsyncThunk< console.error("Failed to send dev data interaction log", e); } } - + // await new Promise((resolve) => + // setTimeout(() => { + // resolve(undefined); + // }, 200), + // ); // If it's a tool call that is automatically accepted, we should call it const toolCallState = selectCurrentToolCall(getState()); if (toolCallState) { diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 358f52dca..45e9bc293 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -1,5 +1,4 @@ import { streamSse } from "@continuedev/fetch"; -import fetch from "node-fetch"; import { OpenAI } from "openai/index"; import { ChatCompletion, @@ -14,7 +13,7 @@ import { } from "openai/resources/index"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; -import { customFetch, maybeCustomFetch } from "../util.js"; +import { customFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, From 52ef5777d72b407d419fca4920d50f7d0cc5e04f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 26 Mar 2025 21:11:47 -0700 Subject: [PATCH 013/324] cleanup --- core/llm/index.ts | 15 ++--- core/llm/llms/Anthropic.ts | 68 ++++++++--------------- gui/src/redux/thunks/streamNormalInput.ts | 7 +-- 3 files changed, 33 insertions(+), 57 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index d4c53b895..dda2e7a87 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -195,11 +195,11 @@ export abstract class BaseLLM implements ILLM { options.completionOptions?.maxTokens ?? (llmInfo?.maxCompletionTokens ? Math.min( - llmInfo.maxCompletionTokens, - // Even if the model has a large maxTokens, we don't want to use that every time, - // because it takes away from the context length - this.contextLength / 4, - ) + llmInfo.maxCompletionTokens, + // Even if the model has a large maxTokens, we don't want to use that every time, + // because it takes away from the context length + this.contextLength / 4, + ) : DEFAULT_MAX_TOKENS), }; this.requestOptions = options.requestOptions; @@ -840,6 +840,7 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { + if (chunk.role === "assistant") { completion += chunk.content; yield chunk; @@ -947,7 +948,7 @@ export abstract class BaseLLM implements ILLM { ); } - protected async *_streamComplete( + protected async * _streamComplete( prompt: string, signal: AbortSignal, options: CompletionOptions, @@ -955,7 +956,7 @@ export abstract class BaseLLM implements ILLM { throw new Error("Not implemented"); } - protected async *_streamChat( + protected async * _streamChat( messages: ChatMessage[], signal: AbortSignal, options: CompletionOptions, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 6d1628f2a..cd48ef41b 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,7 +1,6 @@ import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { LlmApiRequestType } from "../openaiTypeConverters.js"; import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { @@ -16,11 +15,6 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; - protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ - "streamChat", - "chat", - ]; - public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI const finalOptions = { @@ -36,17 +30,15 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), - thinking: options.reasoning - ? { - type: "enabled", - budget_tokens: options.reasoningBudgetTokens, - } - : undefined, + thinking: options.reasoning ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } : undefined, tool_choice: options.toolChoice ? { - type: "tool", - name: options.toolChoice.function.name, - } + type: "tool", + name: options.toolChoice.function.name, + } : undefined, }; @@ -78,23 +70,19 @@ class Anthropic extends BaseLLM { } else if (message.role === "thinking" && !message.redactedThinking) { return { role: "assistant", - content: [ - { - type: "thinking", - thinking: message.content, - signature: message.signature, - }, - ], + content: [{ + type: "thinking", + thinking: message.content, + signature: message.signature + }] }; } else if (message.role === "thinking" && message.redactedThinking) { return { role: "assistant", - content: [ - { - type: "redacted_thinking", - data: message.redactedThinking, - }, - ], + content: [{ + type: "redacted_thinking", + data: message.redactedThinking + }] }; } @@ -207,12 +195,12 @@ class Anthropic extends BaseLLM { messages: msgs, system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), signal, @@ -252,11 +240,7 @@ class Anthropic extends BaseLLM { // handle redacted thinking if (value.content_block.type === "redacted_thinking") { console.log("redacted thinking", value.content_block.data); - yield { - role: "thinking", - content: "", - redactedThinking: value.content_block.data, - }; + yield { role: "thinking", content: "", redactedThinking: value.content_block.data }; } break; case "content_block_delta": @@ -269,11 +253,7 @@ class Anthropic extends BaseLLM { yield { role: "thinking", content: value.delta.thinking }; break; case "signature_delta": - yield { - role: "thinking", - content: "", - signature: value.delta.signature, - }; + yield { role: "thinking", content: "", signature: value.delta.signature }; break; case "input_json_delta": if (!lastToolUseId || !lastToolUseName) { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 509a03f7b..94b96946d 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -37,7 +37,6 @@ export const streamNormalInput = createAsyncThunk< if (!defaultModel) { throw new Error("Default model not defined"); } - // debugger; const includeTools = useTools && modelSupportsTools(defaultModel); // Send request @@ -103,11 +102,7 @@ export const streamNormalInput = createAsyncThunk< console.error("Failed to send dev data interaction log", e); } } - // await new Promise((resolve) => - // setTimeout(() => { - // resolve(undefined); - // }, 200), - // ); + // If it's a tool call that is automatically accepted, we should call it const toolCallState = selectCurrentToolCall(getState()); if (toolCallState) { From 452a4a32ba6d5349e0e9f2c2b6e011b856c0e1db Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 26 Mar 2025 21:13:40 -0700 Subject: [PATCH 014/324] reversions --- packages/openai-adapters/src/apis/Anthropic.ts | 1 + packages/openai-adapters/src/apis/OpenAI.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 36c33e550..04b0fbce9 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -175,6 +175,7 @@ export class AnthropicApi implements BaseLlmApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { + body.messages; const response = await customFetch(this.config.requestOptions)( new URL("messages", this.apiBase), { diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 45e9bc293..358f52dca 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -1,4 +1,5 @@ import { streamSse } from "@continuedev/fetch"; +import fetch from "node-fetch"; import { OpenAI } from "openai/index"; import { ChatCompletion, @@ -13,7 +14,7 @@ import { } from "openai/resources/index"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; -import { customFetch } from "../util.js"; +import { customFetch, maybeCustomFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, From 4e5461b3b6586776708e1041ee6b81a8c5114fe6 Mon Sep 17 00:00:00 2001 From: Michael Elder Date: Thu, 27 Mar 2025 09:27:58 -0400 Subject: [PATCH 015/324] Fix #4723/#4774: Add error handling for system prompt + Ensure that Claude models on VertexAI send correct prompts, even if the systemMessage is undefined. Signed-off-by: "Michael Elder" @mdelder --- core/llm/llms/Gemini.ts | 79 +++++++++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 14 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index e6b1c5c70..696e6df3a 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -4,6 +4,7 @@ import { CompletionOptions, LLMOptions, MessagePart, + TextMessagePart, ToolCallDelta, } from "../../index.js"; import { findLast } from "../../util/findLast.js"; @@ -69,22 +70,72 @@ class Gemini extends BaseLLM { } } - public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] { - // should be public for use within VertexAI - const msgs = [...messages]; - - if (msgs[0]?.role === "system") { - const sysMsg = msgs.shift()?.content; - // @ts-ignore - if (msgs[0]?.role === "user") { - // @ts-ignore - msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; - } - } - - return msgs; +/** + * Removes the system message and merges it with the next user message if present. + * @param messages Array of chat messages + * @returns Modified array with system message merged into user message if applicable + */ +public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] { + // If no messages or first message isn't system, return copy of original messages + if (messages.length === 0 || messages[0]?.role !== "system") { + return [...messages]; } + // Extract system message + const systemMessage : ChatMessage = messages[0]; + + // Extract system content based on its type + let systemContent = ""; + if (typeof systemMessage.content === "string") { + systemContent = systemMessage.content; + } else if (Array.isArray(systemMessage.content)) { + const contentArray : Array = systemMessage.content as Array; + const concatenatedText = contentArray + .filter(part => part.type === "text") + .map(part => part.text) + .join(" "); + systemContent = concatenatedText ? concatenatedText : ""; + } else if (systemMessage.content && typeof systemMessage.content === "object") { + const typedContent = systemMessage.content as TextMessagePart; + systemContent = typedContent?.text || ""; + } + + // Create new array without the system message + const remainingMessages : ChatMessage[] = messages.slice(1); + + // Check if there's a user message to merge with + if (remainingMessages.length > 0 && remainingMessages[0].role === "user") { + const userMessage : ChatMessage = remainingMessages[0]; + const prefix = `System message - follow these instructions in every response: ${systemContent}\n\n---\n\n`; + + // Merge based on user content type + if (typeof userMessage.content === "string") { + userMessage.content = prefix + userMessage.content; + } else if (Array.isArray(userMessage.content)) { + const contentArray : Array = userMessage.content as Array; + const textPart = contentArray.find(part => part.type === "text") as TextMessagePart | undefined; + + if (textPart) { + textPart.text = prefix + textPart.text; + } else { + userMessage.content.push({ + type: "text", + text: prefix + } as TextMessagePart); + } + } else if (userMessage.content && typeof userMessage.content === "object") { + const typedContent = userMessage.content as TextMessagePart; + userMessage.content = [{ + type: "text", + text: prefix + (typedContent.text || "") + } as TextMessagePart]; + } + } + + return remainingMessages; +} + + protected async *_streamChat( messages: ChatMessage[], signal: AbortSignal, From d448b5f4d8bb27cb1f3b00ec1fba808a4805ed2f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Mar 2025 11:40:43 -0700 Subject: [PATCH 016/324] fix slash command triggering --- core/commands/index.ts | 2 +- .../mainInput/tiptap/editorConfig.ts | 31 +++++++++---------- .../tiptap/extensions/FillerExtension.tsx | 20 ------------ .../mainInput/tiptap/getSuggestion.ts | 4 +-- gui/src/redux/selectors/index.ts | 2 +- 5 files changed, 18 insertions(+), 41 deletions(-) delete mode 100644 gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx diff --git a/core/commands/index.ts b/core/commands/index.ts index 486eaccf2..ba5c3403c 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -19,7 +19,7 @@ export function slashFromCustomCommand( .slice(customCommand.name.length + 1, userInput.length) .trimStart(); } - + debugger; // Render prompt template let promptUserInput: string; if (customCommand.prompt.includes("{{{ input }}}")) { diff --git a/gui/src/components/mainInput/tiptap/editorConfig.ts b/gui/src/components/mainInput/tiptap/editorConfig.ts index d79981d39..985cadc64 100644 --- a/gui/src/components/mainInput/tiptap/editorConfig.ts +++ b/gui/src/components/mainInput/tiptap/editorConfig.ts @@ -30,7 +30,6 @@ import { getFontSize } from "../../../util"; import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; import { SlashCommand } from "./extensions/CommandsExtension"; -import { MockExtension } from "./extensions/FillerExtension"; import { Mention } from "./extensions/MentionExtension"; import { getContextProviderDropdownOptions, @@ -352,22 +351,20 @@ export function createEditorConfig(options: { }, }, }), - props.availableSlashCommands.length - ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) - : MockExtension, + SlashCommand.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }), CodeBlockExtension, ], editorProps: { diff --git a/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx b/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx deleted file mode 100644 index 9b8baac86..000000000 --- a/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { Node } from "@tiptap/core"; - -export const MockExtension = Node.create({ - name: "mockExtension", - - addOptions() { - return { - enabled: false, - }; - }, - addCommands() { - return {}; - }, - addKeyboardShortcuts() { - return {}; - }, - addProseMirrorPlugins() { - return []; - }, -}); diff --git a/gui/src/components/mainInput/tiptap/getSuggestion.ts b/gui/src/components/mainInput/tiptap/getSuggestion.ts index 264258dd5..f9faad863 100644 --- a/gui/src/components/mainInput/tiptap/getSuggestion.ts +++ b/gui/src/components/mainInput/tiptap/getSuggestion.ts @@ -203,7 +203,7 @@ export function getSlashCommandDropdownOptions( const filteredCommands = query.length > 0 ? options.filter((slashCommand) => { - const sc = slashCommand.title.substring(1).toLowerCase(); + const sc = slashCommand.title.toLowerCase(); const iv = query.toLowerCase(); return sc.startsWith(iv); }) @@ -219,7 +219,7 @@ export function getSlashCommandDropdownOptions( action: provider.action, })); - if (query.length === 0 && commandItems.length > 0) { + if (query.length === 0 && commandItems.length === 0) { commandItems.push({ title: "Explore prompts", type: "action", diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index 3d46bf9ea..bb7850dd5 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -8,7 +8,7 @@ export const selectSlashCommandComboBoxInputs = createSelector( return ( slashCommands?.map((cmd) => { return { - title: `${cmd.name}`, + title: cmd.name, description: cmd.description, type: "slashCommand" as ComboBoxItemType, }; From ca085d71d59ac12d5110cf26f08e9e3e6c98238b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Mar 2025 13:33:33 -0700 Subject: [PATCH 017/324] slash command progress --- core/commands/index.ts | 24 ++-- extensions/vscode/package-lock.json | 4 +- .../mainInput/tiptap/resolveInput.ts | 119 +++++++++++------- gui/src/redux/thunks/gatherContext.ts | 17 ++- gui/src/redux/thunks/streamResponse.ts | 46 ++----- 5 files changed, 110 insertions(+), 100 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index ba5c3403c..b6f233485 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -7,19 +7,21 @@ import SlashCommands from "./slash"; export function slashFromCustomCommand( customCommand: CustomCommand, ): SlashCommand { + const commandName = customCommand.name.startsWith("/") + ? customCommand.name.substring(1) + : customCommand.name; return { - name: customCommand.name, + name: commandName, description: customCommand.description ?? "", prompt: customCommand.prompt, run: async function* ({ input, llm, history, ide, completionOptions }) { + console.log("SLASH COMMAND RUN", input, prompt, commandName); // Remove slash command prefix from input let userInput = input; - if (userInput.startsWith(`/${customCommand.name}`)) { - userInput = userInput - .slice(customCommand.name.length + 1, userInput.length) - .trimStart(); + if (userInput.startsWith(commandName)) { + userInput = userInput.substring(commandName.length).trimStart(); } - debugger; + // Render prompt template let promptUserInput: string; if (customCommand.prompt.includes("{{{ input }}}")) { @@ -44,17 +46,13 @@ export function slashFromCustomCommand( if ( Array.isArray(content) && content.some( - (part) => - "text" in part && part.text?.startsWith(`/${customCommand.name}`), + (part) => "text" in part && part.text?.startsWith(commandName), ) ) { messages[i] = { ...message, content: content.map((part) => { - if ( - "text" in part && - part.text.startsWith(`/${customCommand.name}`) - ) { + if ("text" in part && part.text.startsWith(commandName)) { return { type: "text", text: promptUserInput }; } return part; @@ -63,7 +61,7 @@ export function slashFromCustomCommand( break; } else if ( typeof content === "string" && - content.startsWith(`/${customCommand.name}`) + content.startsWith(commandName) ) { messages[i] = { ...message, content: promptUserInput }; break; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 678794d02..1170be786 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.16", + "version": "1.1.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.16", + "version": "1.1.17", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/components/mainInput/tiptap/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts index d9eb47b6c..427edead1 100644 --- a/gui/src/components/mainInput/tiptap/resolveInput.ts +++ b/gui/src/components/mainInput/tiptap/resolveInput.ts @@ -7,6 +7,7 @@ import { MessageContent, MessagePart, RangeInFile, + SlashCommandDescription, TextMessagePart, } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; @@ -27,6 +28,7 @@ interface ResolveEditorContentInput { modifiers: InputModifiers; ideMessenger: IIdeMessenger; defaultContextProviders: DefaultContextProvider[]; + availableSlashCommands: SlashCommandDescription[]; selectedModelTitle: string; dispatch: Dispatch; } @@ -40,22 +42,36 @@ async function resolveEditorContent({ modifiers, ideMessenger, defaultContextProviders, + availableSlashCommands, selectedModelTitle, dispatch, }: ResolveEditorContentInput): Promise< - [ContextItemWithId[], RangeInFile[], MessageContent] + [ + ContextItemWithId[], + RangeInFile[], + MessageContent, + ( + | { + name: string; + input: string; + } + | undefined + ), + ] > { let parts: MessagePart[] = []; let contextItemAttrs: MentionAttrs[] = []; const selectedCode: RangeInFile[] = []; - let slashCommand: string | undefined = undefined; + let slashCommandName: string | undefined = undefined; + let slashCommandWithInput: { name: string; input: string } | undefined = + undefined; if (editorState?.content) { for (const p of editorState.content) { if (p.type === "paragraph") { const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - // Only take the first slash command\ - if (foundSlashCommand && typeof slashCommand === "undefined") { - slashCommand = foundSlashCommand; + // Only take the first slash command + if (foundSlashCommand && typeof slashCommandName === "undefined") { + slashCommandName = foundSlashCommand; } contextItemAttrs.push(...ctxItems); @@ -113,7 +129,60 @@ async function resolveEditorContent({ } } - const shouldGatherContext = modifiers.useCodebase || slashCommand; + // Add slash command text back in (this could be removed) + if (slashCommandName) { + const command = availableSlashCommands.find( + (c) => c.name === slashCommandWithName, + ); + if (command) { + slashCommandWithInput = { + name: command.name, + input: "TODO INPUT", + }; + } + } + const getSlashCommandForInput = ( + input: MessageContent, + slashCommands: SlashCommandDescription[], + ): [SlashCommandDescription, string] | undefined => { + let slashCommand: SlashCommandDescription | undefined; + let slashCommandName: string | undefined; + + let lastText = + typeof input === "string" + ? input + : ( + input.filter((part) => part.type === "text").slice(-1)[0] as + | TextMessagePart + | undefined + )?.text || ""; + + if (lastText.startsWith("/")) { + slashCommandName = lastText.split(" ")[0].substring(1); + slashCommand = slashCommands.find((command) => + lastText.startsWith(command), + ); + } + if (!slashCommand || !slashCommandName) { + return undefined; + } + + // Convert to actual slash command object with runnable function + return [slashCommand, renderChatMessage({ role: "user", content: input })]; + }; + + if (slashCommand) { + let lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); + const lastTextPart = parts[lastTextIndex] as TextMessagePart; + const lastPart = `/${slashCommand} ${lastTextPart?.text || ""}`; + if (parts.length > 0) { + lastTextPart.text = lastPart; + } else { + parts = [{ type: "text", text: lastPart }]; + } + } + + const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput; if (shouldGatherContext) { dispatch(setIsGatheringContext(true)); } @@ -179,21 +248,11 @@ async function resolveEditorContent({ contextItemsText += "\n"; } - if (slashCommand) { - let lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); - const lastTextPart = parts[lastTextIndex] as TextMessagePart; - const lastPart = `${slashCommand} ${lastTextPart?.text || ""}`; - if (parts.length > 0) { - lastTextPart.text = lastPart; - } else { - parts = [{ type: "text", text: lastPart }]; - } - } if (shouldGatherContext) { dispatch(setIsGatheringContext(false)); } - return [contextItems, selectedCode, parts]; + return [contextItems, selectedCode, parts, slashCommandWithInput]; } function findLastIndex( @@ -236,30 +295,4 @@ function resolveParagraph( return [text, contextItems, slashCommand]; } -export function hasSlashCommandOrContextProvider( - editorState: JSONContent, -): boolean { - if (!editorState?.content) { - return false; - } - - for (const p of editorState.content) { - if (p.type === "paragraph" && p.content) { - for (const child of p.content) { - if (child.type === "slashcommand") { - return true; - } - if ( - child.type === "mention" && - child.attrs?.itemType === "contextProvider" - ) { - return true; - } - } - } - } - - return false; -} - export default resolveEditorContent; diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index ebd50e644..5386881f7 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -16,6 +16,12 @@ export const gatherContext = createAsyncThunk< selectedContextItems: ContextItemWithId[]; selectedCode: RangeInFile[]; content: MessageContent; + slashCommandWithInput: + | { + name: string; + input: string; + } + | undefined; }, { editorState: JSONContent; @@ -42,12 +48,13 @@ export const gatherContext = createAsyncThunk< } // Resolve context providers and construct new history - let [selectedContextItems, selectedCode, content] = + let [selectedContextItems, selectedCode, content, slashCommandWithInput] = await resolveEditorContent({ editorState, modifiers, ideMessenger: extra.ideMessenger, defaultContextProviders, + availableSlashCommands: state.config.config.slashCommands, dispatch, selectedModelTitle: defaultModel.title, }); @@ -107,7 +114,11 @@ export const gatherContext = createAsyncThunk< } } - // dispatch(addContextItems(contextItems)); - return { selectedContextItems, selectedCode, content }; + return { + selectedContextItems, + selectedCode, + content, + slashCommandWithInput, + }; }, ); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 84e2edbe5..cfdb5a9d2 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,13 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { - InputModifiers, - MessageContent, - SlashCommandDescription, - TextMessagePart, -} from "core"; +import { InputModifiers } from "core"; import { constructMessages } from "core/llm/constructMessages"; -import { renderChatMessage } from "core/util/messageContent"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; import { selectDefaultModel } from "../slices/configSlice"; @@ -22,36 +16,6 @@ import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; import { updateFileSymbolsFromFiles } from "./updateFileSymbols"; -const getSlashCommandForInput = ( - input: MessageContent, - slashCommands: SlashCommandDescription[], -): [SlashCommandDescription, string] | undefined => { - let slashCommand: SlashCommandDescription | undefined; - let slashCommandName: string | undefined; - - let lastText = - typeof input === "string" - ? input - : ( - input.filter((part) => part.type === "text").slice(-1)[0] as - | TextMessagePart - | undefined - )?.text || ""; - - if (lastText.startsWith("/")) { - slashCommandName = lastText.split(" ")[0].substring(1); - slashCommand = slashCommands.find((command) => - lastText.startsWith(`/${command.name} `), - ); - } - if (!slashCommand || !slashCommandName) { - return undefined; - } - - // Convert to actual slash command object with runnable function - return [slashCommand, renderChatMessage({ role: "user", content: input })]; -}; - export const streamResponseThunk = createAsyncThunk< void, { @@ -90,8 +54,12 @@ export const streamResponseThunk = createAsyncThunk< promptPreamble, }), ); - const unwrapped = unwrapResult(result); - const { selectedContextItems, selectedCode, content } = unwrapped; + const { + selectedContextItems, + selectedCode, + content, + slashCommandWithInput, + } = unwrapResult(result); // symbols for both context items AND selected codeblocks const filesForSymbols = [ From e14163cda2ff1de2e90621f1de2341fd90b136d2 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 27 Mar 2025 14:37:03 -0700 Subject: [PATCH 018/324] feat: add animated ellipsis to lump --- extensions/vscode/package-lock.json | 4 ++-- gui/src/components/mainInput/Lump/LumpToolbar.tsx | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 678794d02..1170be786 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.16", + "version": "1.1.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.16", + "version": "1.1.17", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index cca7885d3..c4565cb95 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -1,5 +1,6 @@ import { useContext } from "react"; import styled from "styled-components"; +import { AnimatedEllipsis } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { @@ -11,7 +12,8 @@ import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; const Container = styled.div` display: flex; - justify-content: flex-end; + justify-content: space-between; + align-items: center; width: 100%; `; @@ -27,6 +29,15 @@ interface TopToolbarProps { setSelectedSection: (value: string | null) => void; } +function GeneratingIndicator() { + return ( +
+ Generating + +
+ ); +} + export function LumpToolbar(props: TopToolbarProps) { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); @@ -36,6 +47,7 @@ export function LumpToolbar(props: TopToolbarProps) { if (ttsActive) { return ( + { @@ -51,6 +63,7 @@ export function LumpToolbar(props: TopToolbarProps) { if (isStreaming) { return ( + { From 7d5eb828f059fbccf47340eb30eab95674a66478 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Mar 2025 15:09:34 -0700 Subject: [PATCH 019/324] slash command fixes --- core/commands/index.ts | 57 ++++----------- core/commands/slash/http.ts | 4 +- .../v1/slashCommandFromPromptFile.ts | 4 +- core/promptFiles/v1/updateChatHistory.ts | 2 +- .../CodeToEditCard/CodeToEditCard.tsx | 12 +-- .../mainInput/tiptap/resolveInput.ts | 73 +++++++------------ gui/src/pages/gui/Chat.tsx | 4 +- gui/src/redux/thunks/gatherContext.ts | 3 +- gui/src/redux/thunks/streamResponse.ts | 45 +++++------- 9 files changed, 74 insertions(+), 130 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index b6f233485..7115d22be 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,5 +1,6 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; +import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -15,58 +16,26 @@ export function slashFromCustomCommand( description: customCommand.description ?? "", prompt: customCommand.prompt, run: async function* ({ input, llm, history, ide, completionOptions }) { - console.log("SLASH COMMAND RUN", input, prompt, commandName); - // Remove slash command prefix from input - let userInput = input; - if (userInput.startsWith(commandName)) { - userInput = userInput.substring(commandName.length).trimStart(); - } - // Render prompt template - let promptUserInput: string; + let renderedPrompt: string; if (customCommand.prompt.includes("{{{ input }}}")) { - promptUserInput = await renderTemplatedString( + renderedPrompt = await renderTemplatedString( customCommand.prompt, ide.readFile.bind(ide), - { input: userInput }, + { input }, ); } else { - promptUserInput = customCommand.prompt + "\n\n" + userInput; + renderedPrompt = customCommand.prompt + "\n\n" + input; } - const messages = [...history]; - // Find the last chat message with this slash command and replace it with the user input - for (let i = messages.length - 1; i >= 0; i--) { - const message = messages[i]; - const { role, content } = message; - if (role !== "user") { - continue; - } - - if ( - Array.isArray(content) && - content.some( - (part) => "text" in part && part.text?.startsWith(commandName), - ) - ) { - messages[i] = { - ...message, - content: content.map((part) => { - if ("text" in part && part.text.startsWith(commandName)) { - return { type: "text", text: promptUserInput }; - } - return part; - }), - }; - break; - } else if ( - typeof content === "string" && - content.startsWith(commandName) - ) { - messages[i] = { ...message, content: promptUserInput }; - break; - } - } + // Replaces slash command messages with the rendered prompt + // which INCLUDES the input + const messages = replaceSlashCommandWithPromptInChatHistory( + history, + commandName, + renderedPrompt, + undefined, + ); for await (const chunk of llm.streamChat( messages, diff --git a/core/commands/slash/http.ts b/core/commands/slash/http.ts index 7a662561c..1c0d38626 100644 --- a/core/commands/slash/http.ts +++ b/core/commands/slash/http.ts @@ -1,11 +1,11 @@ import { SlashCommand } from "../../index.js"; -import { removeQuotesAndEscapes } from "../../util/index.js"; import { streamResponse } from "../../llm/stream.js"; +import { removeQuotesAndEscapes } from "../../util/index.js"; const HttpSlashCommand: SlashCommand = { name: "http", description: "Call an HTTP endpoint to serve response", - run: async function* ({ ide, llm, input, params, fetch }) { + run: async function* ({ input, params, fetch }) { const url = params?.url; if (!url) { throw new Error("URL is not defined in params"); diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index b9d4e88c8..6abd4927f 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -5,7 +5,7 @@ import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; -import { updateChatHistory } from "./updateChatHistory"; +import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory"; export function extractName(preamble: { name?: string }, path: string): string { return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; @@ -68,7 +68,7 @@ export function slashCommandFromPromptFileV1( const userInput = extractUserInput(context.input, name); const renderedPrompt = await renderPromptV1(prompt, context, userInput); - const messages = updateChatHistory( + const messages = replaceSlashCommandWithPromptInChatHistory( context.history, name, renderedPrompt, diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts index 8ebc6f038..04cbcd91b 100644 --- a/core/promptFiles/v1/updateChatHistory.ts +++ b/core/promptFiles/v1/updateChatHistory.ts @@ -1,4 +1,4 @@ -export function updateChatHistory( +export function replaceSlashCommandWithPromptInChatHistory( history: any[], commandName: string, renderedPrompt: string, diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 99149ba5f..772777337 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -1,16 +1,16 @@ +import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import type { CodeToEdit } from "core"; import { useContext, useState } from "react"; import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import CodeToEditListItem from "./CodeToEditListItem"; -import type { CodeToEdit } from "core"; -import AddFileButton from "./AddFileButton"; -import AddFileCombobox from "./AddFileCombobox"; -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { addCodeToEdit, removeCodeToEdit, } from "../../redux/slices/sessionSlice"; +import AddFileButton from "./AddFileButton"; +import AddFileCombobox from "./AddFileCombobox"; +import CodeToEditListItem from "./CodeToEditListItem"; export default function CodeToEditCard() { const dispatch = useDispatch(); @@ -56,7 +56,7 @@ export default function CodeToEditCard() { return (
-
+
{title} setShowAddFileCombobox(true)} />
diff --git a/gui/src/components/mainInput/tiptap/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts index 427edead1..76a868115 100644 --- a/gui/src/components/mainInput/tiptap/resolveInput.ts +++ b/gui/src/components/mainInput/tiptap/resolveInput.ts @@ -11,7 +11,7 @@ import { TextMessagePart, } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; -import { stripImages } from "core/util/messageContent"; +import { renderChatMessage, stripImages } from "core/util/messageContent"; import { getUriFileExtension } from "core/util/uri"; import { IIdeMessenger } from "../../../context/IdeMessenger"; import { setIsGatheringContext } from "../../../redux/slices/sessionSlice"; @@ -52,7 +52,7 @@ async function resolveEditorContent({ MessageContent, ( | { - name: string; + command: SlashCommandDescription; input: string; } | undefined @@ -63,8 +63,9 @@ async function resolveEditorContent({ let contextItemAttrs: MentionAttrs[] = []; const selectedCode: RangeInFile[] = []; let slashCommandName: string | undefined = undefined; - let slashCommandWithInput: { name: string; input: string } | undefined = - undefined; + let slashCommandWithInput: + | { command: SlashCommandDescription; input: string } + | undefined = undefined; if (editorState?.content) { for (const p of editorState.content) { if (p.type === "paragraph") { @@ -129,56 +130,34 @@ async function resolveEditorContent({ } } - // Add slash command text back in (this could be removed) if (slashCommandName) { const command = availableSlashCommands.find( - (c) => c.name === slashCommandWithName, + (c) => c.name === slashCommandName, ); if (command) { - slashCommandWithInput = { - name: command.name, - input: "TODO INPUT", - }; - } - } - const getSlashCommandForInput = ( - input: MessageContent, - slashCommands: SlashCommandDescription[], - ): [SlashCommandDescription, string] | undefined => { - let slashCommand: SlashCommandDescription | undefined; - let slashCommandName: string | undefined; - - let lastText = - typeof input === "string" - ? input - : ( - input.filter((part) => part.type === "text").slice(-1)[0] as - | TextMessagePart - | undefined - )?.text || ""; - - if (lastText.startsWith("/")) { - slashCommandName = lastText.split(" ")[0].substring(1); - slashCommand = slashCommands.find((command) => - lastText.startsWith(command), + const lastTextIndex = findLastIndex( + parts, + (part) => part.type === "text", ); - } - if (!slashCommand || !slashCommandName) { - return undefined; - } + const lastTextPart = parts[lastTextIndex] as TextMessagePart; - // Convert to actual slash command object with runnable function - return [slashCommand, renderChatMessage({ role: "user", content: input })]; - }; + let input: string; + // Get input and add text of last slash command text back in to last text node + if (lastTextPart) { + input = renderChatMessage({ + role: "user", + content: lastTextPart.text, + }).trimStart(); + lastTextPart.text = `/${command.name} ${lastTextPart.text}`; + } else { + input = ""; + parts.push({ type: "text", text: `/${command.name}` }); + } - if (slashCommand) { - let lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); - const lastTextPart = parts[lastTextIndex] as TextMessagePart; - const lastPart = `/${slashCommand} ${lastTextPart?.text || ""}`; - if (parts.length > 0) { - lastTextPart.text = lastPart; - } else { - parts = [{ type: "text", text: lastPart }]; + slashCommandWithInput = { + command, + input, + }; } } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 05c1f2c47..aea4bdadb 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -235,7 +235,8 @@ export function Chat() { console.error("No selected chat model"); return; } - const [contextItems, __, userInstructions] = await resolveEditorContent({ + + const [contextItems, __, userInstructions, _] = await resolveEditorContent({ editorState, modifiers: { noContext: true, @@ -243,6 +244,7 @@ export function Chat() { }, ideMessenger, defaultContextProviders: [], + availableSlashCommands: [], dispatch, selectedModelTitle: defaultModel.title, }); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 5386881f7..1c38e965b 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -5,6 +5,7 @@ import { InputModifiers, MessageContent, RangeInFile, + SlashCommandDescription, } from "core"; import * as URI from "uri-js"; import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; @@ -18,7 +19,7 @@ export const gatherContext = createAsyncThunk< content: MessageContent; slashCommandWithInput: | { - name: string; + command: SlashCommandDescription; input: string; } | undefined; diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index cfdb5a9d2..9b802ffbb 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -94,36 +94,29 @@ export const streamResponseThunk = createAsyncThunk< }); posthog.capture("userInput", {}); - // Determine if the input is a slash command - let commandAndInput = getSlashCommandForInput(content, slashCommands); - - if (!commandAndInput) { - unwrapResult(await dispatch(streamNormalInput({ messages }))); - } else { - const [slashCommand, commandInput] = commandAndInput; - + if (slashCommandWithInput) { posthog.capture("step run", { - step_name: slashCommand.name, + step_name: slashCommandWithInput.command.name, params: {}, }); - - // TODO - handle non-legacy slash commands, update messages if relevant - // Pass around isFromConfigTs - unwrapResult( - await dispatch( - streamNormalInput({ - messages, - legacySlashCommandData: { - command: slashCommand, - contextItems: selectedContextItems, - historyIndex: inputIndex, - input: commandInput, - selectedCode, - }, - }), - ), - ); } + + unwrapResult( + await dispatch( + streamNormalInput({ + messages, + legacySlashCommandData: slashCommandWithInput + ? { + command: slashCommandWithInput.command, + contextItems: selectedContextItems, + historyIndex: inputIndex, + input: slashCommandWithInput.input, + selectedCode, + } + : undefined, + }), + ), + ); }), ); }, From 043402afc2b3644efff9c79fc6ffbe25570a6372 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Mar 2025 15:14:23 -0700 Subject: [PATCH 020/324] reduce file changes --- core/commands/slash/http.ts | 4 ++-- gui/src/components/CodeToEditCard/CodeToEditCard.tsx | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/core/commands/slash/http.ts b/core/commands/slash/http.ts index 1c0d38626..7a662561c 100644 --- a/core/commands/slash/http.ts +++ b/core/commands/slash/http.ts @@ -1,11 +1,11 @@ import { SlashCommand } from "../../index.js"; -import { streamResponse } from "../../llm/stream.js"; import { removeQuotesAndEscapes } from "../../util/index.js"; +import { streamResponse } from "../../llm/stream.js"; const HttpSlashCommand: SlashCommand = { name: "http", description: "Call an HTTP endpoint to serve response", - run: async function* ({ input, params, fetch }) { + run: async function* ({ ide, llm, input, params, fetch }) { const url = params?.url; if (!url) { throw new Error("URL is not defined in params"); diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 772777337..99149ba5f 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -1,16 +1,16 @@ -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import type { CodeToEdit } from "core"; import { useContext, useState } from "react"; import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import CodeToEditListItem from "./CodeToEditListItem"; +import type { CodeToEdit } from "core"; +import AddFileButton from "./AddFileButton"; +import AddFileCombobox from "./AddFileCombobox"; +import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { addCodeToEdit, removeCodeToEdit, } from "../../redux/slices/sessionSlice"; -import AddFileButton from "./AddFileButton"; -import AddFileCombobox from "./AddFileCombobox"; -import CodeToEditListItem from "./CodeToEditListItem"; export default function CodeToEditCard() { const dispatch = useDispatch(); @@ -56,7 +56,7 @@ export default function CodeToEditCard() { return (
-
+
{title} setShowAddFileCombobox(true)} />
From c110fd8cdf44f826eee0f64b913272d6b9f570a8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Mar 2025 16:44:29 -0700 Subject: [PATCH 021/324] flex direction for chat page --- gui/src/pages/gui/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/pages/gui/index.tsx b/gui/src/pages/gui/index.tsx index 788d88b23..0550d27f2 100644 --- a/gui/src/pages/gui/index.tsx +++ b/gui/src/pages/gui/index.tsx @@ -3,8 +3,8 @@ import { Chat } from "./Chat"; export default function GUI() { return ( -
-