From c309bfb1bebbac47cc2b21ecb2d3ba53c6d3a2a6 Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Wed, 17 Sep 2025 13:43:03 -0700 Subject: [PATCH 01/20] feat: revamp efficient file search and support fuzzy matching --- extensions/cli/package-lock.json | 135 +++---- extensions/cli/package.json | 4 +- .../src/e2e/home-directory-warning.test.ts | 256 ------------- .../cli/src/services/FileIndexService.test.ts | 55 ++- .../cli/src/services/FileIndexService.ts | 339 ++++++++---------- extensions/cli/src/ui/FileSearchUI.tsx | 195 ++++++---- extensions/cli/src/ui/IntroMessage.tsx | 15 - extensions/cli/src/ui/UserInput.tsx | 100 +++--- .../__tests__/UserInput.missingFile.test.tsx | 36 ++ 9 files changed, 470 insertions(+), 665 deletions(-) delete mode 100644 extensions/cli/src/e2e/home-directory-warning.test.ts create mode 100644 extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 6f7b8795c..729edf086 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -9,7 +9,9 @@ "version": "0.0.0-dev", "license": "Apache-2.0", "dependencies": { - "@sentry/profiling-node": "^9.43.0" + "@sentry/profiling-node": "^9.43.0", + "fdir": "^6.4.2", + "fzf": "^0.5.2" }, "bin": { "cn": "dist/cn.js" @@ -236,11 +238,11 @@ }, "../../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.96", + "version": "1.14.0", "dev": true, "license": "Apache-2.0", "dependencies": { - "@continuedev/config-types": "file:../config-types", + "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", "zod": "^3.24.2" }, @@ -264,15 +266,15 @@ }, "../../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.5.1", + "version": "1.14.0", "dev": true, "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", - "@continuedev/config-yaml": "^1.8.0", - "@continuedev/fetch": "^1.0.16", + "@continuedev/config-yaml": "^1.14.0", + "@continuedev/fetch": "^1.1.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", @@ -9478,6 +9480,23 @@ "reusify": "^1.0.4" } }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/fecha": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", @@ -9906,6 +9925,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/fzf": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fzf/-/fzf-0.5.2.tgz", + "integrity": "sha512-Tt4kuxLXFKHy8KT40zwsUPUkg1CrsgY25FxA2U/j/0WgEDCk3ddc/zLTCCcbSHX9FcKtLuVaDGtGE/STWC+j3Q==", + "license": "BSD-3-Clause" + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -12061,6 +12086,19 @@ "node": ">=8.6" } }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/mime": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/mime/-/mime-4.0.7.tgz", @@ -15737,13 +15775,13 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "devOptional": true, "license": "MIT", "engines": { - "node": ">=8.6" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" @@ -18106,37 +18144,6 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, - "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/tinyglobby/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/tinygradient": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz", @@ -18847,37 +18854,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/vite/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/vite/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/vitest": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", @@ -18951,19 +18927,6 @@ } } }, - "node_modules/vitest/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/w3c-xmlserializer": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 7f212fab6..61da44989 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -44,7 +44,9 @@ }, "homepage": "https://continue.dev", "dependencies": { - "@sentry/profiling-node": "^9.43.0" + "@sentry/profiling-node": "^9.43.0", + "fdir": "^6.4.2", + "fzf": "^0.5.2" }, "devDependencies": { "@continuedev/config-yaml": "file:../../packages/config-yaml", diff --git a/extensions/cli/src/e2e/home-directory-warning.test.ts b/extensions/cli/src/e2e/home-directory-warning.test.ts deleted file mode 100644 index a5caf9d52..000000000 --- a/extensions/cli/src/e2e/home-directory-warning.test.ts +++ /dev/null @@ -1,256 +0,0 @@ -import * as fs from "node:fs"; -import * as path from "node:path"; - -import { afterEach, beforeEach, describe, expect, it } from "vitest"; - -import { - cleanupTestContext, - createTestConfig, - createTestContext, - runCLI, - type CLITestContext, -} from "../test-helpers/cli-helpers.js"; -import { HOME_DIRECTORY_WARNING } from "../ui/IntroMessage.js"; - -describe("E2E: Home Directory Warning", () => { - let context: CLITestContext; - - const testConfig = `name: Test Assistant -version: 1.0.0 -schema: v1 -models: - - model: gpt-4 - provider: openai - apiKey: test-key - roles: - - chat`; - - beforeEach(async () => { - context = await createTestContext(); - }); - - afterEach(async () => { - await cleanupTestContext(context); - }); - - describe("home directory detection", () => { - it("should NOT show warning in headless mode even when running from home directory", async () => { - await createTestConfig(context, testConfig); - - // Simulate running from home directory using the isolated test dir - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - // Ensure home vars point to the isolated test dir - HOME: context.testDir, - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 5000, - expectError: true, - }); - - // Should NOT contain the home directory warning in headless mode - const output = result.stdout + result.stderr; - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - }); - - it("should show warning when running from home directory in TUI mode", async () => { - await createTestConfig(context, testConfig); - - // Test TUI mode (without -p flag) from an isolated "home" directory - const result = await runCLI(context, { - args: ["--config", context.configPath!], - env: { - OPENAI_API_KEY: "test-key", - HOME: context.testDir, - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 3000, - expectError: true, - }); - - // In TUI mode, if we get any meaningful output, check for warning - const output = result.stdout + result.stderr; - if ( - output.includes("Continue") || - output.includes("Agent") || - output.includes("Model") - ) { - expect(output).toContain(HOME_DIRECTORY_WARNING); - } else { - // TUI mode likely failed to start in test environment, which is expected - // The important thing is that it attempted TUI mode, not headless mode - expect(result.exitCode).toBeDefined(); - } - }); - - it("should NOT show warning in headless mode regardless of platform", async () => { - await createTestConfig(context, testConfig); - - // Test with different platform-specific environment variables - const platformEnvs: Record[] = [ - // Unix-style - { - HOME: context.testDir, - OPENAI_API_KEY: "test-key", - }, - // Windows-style - { - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - OPENAI_API_KEY: "test-key", - }, - ]; - - for (const env of platformEnvs) { - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - ...env, - }, - timeout: 5000, - expectError: true, - }); - - // Should NOT contain warning in headless mode regardless of platform - const output = result.stdout + result.stderr; - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - } - }); - - it("should NOT show warning in headless mode with symlinked home directories", async () => { - await createTestConfig(context, testConfig); - - // Create a symlink to the isolated home directory to simulate symlinked home paths - const realHome = fs.realpathSync(context.testDir); - const linkPath = path.join( - path.dirname(realHome), - `${path.basename(realHome)}-link`, - ); - try { - if (!fs.existsSync(linkPath)) { - fs.symlinkSync(realHome, linkPath, "dir"); - } - } catch { - // If symlink creation fails (e.g., on Windows without privileges), skip this specific scenario - } - - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - // Point HOME to the symlink while cwd remains the real path - HOME: fs.existsSync(linkPath) ? linkPath : realHome, - USERPROFILE: fs.existsSync(linkPath) ? linkPath : realHome, - HOMEDRIVE: path.parse(realHome).root, - HOMEPATH: path.relative(path.parse(realHome).root, realHome), - CONTINUE_GLOBAL_DIR: path.join(realHome, ".continue-global"), - }, - timeout: 5000, - expectError: true, - }); - - // Should NOT detect home directory warning in headless mode even with resolved paths - const output = result.stdout + result.stderr; - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - }); - - it("should work in TUI mode (when available)", async () => { - await createTestConfig(context, testConfig); - - // Test TUI mode behavior (though it may fail in test environment) - const result = await runCLI(context, { - args: ["--config", context.configPath!], - env: { - OPENAI_API_KEY: "test-key", - HOME: context.testDir, - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 3000, - expectError: true, - }); - - // Even if TUI fails to start properly in test environment, - // the warning should still be present in any output - const output = result.stdout + result.stderr; - if (output.includes("Continue")) { - // If we got any meaningful output, check for warning - expect(output).toContain(HOME_DIRECTORY_WARNING); - } - }); - }); - - describe("edge cases", () => { - it("should handle case where home directory cannot be determined", async () => { - await createTestConfig(context, testConfig); - - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - // Mask home directory environment variables so os.homedir() cannot derive a value - HOME: "", - USERPROFILE: "", - HOMEDRIVE: "", - HOMEPATH: "", - }, - timeout: 5000, - expectError: true, - }); - - // Should not crash when home directory cannot be determined - expect(result.exitCode).toBeDefined(); - const output = result.stdout + result.stderr; - // Should not show warning if home cannot be determined (and we're in headless mode anyway) - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - }); - - it("should handle relative vs absolute path comparisons", async () => { - await createTestConfig(context, testConfig); - - // Use a HOME that is equivalent but not identical (e.g., with './') - const altHome = path.join(context.testDir, "."); - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - HOME: altHome, - USERPROFILE: altHome, - HOMEDRIVE: path.parse(altHome).root, - HOMEPATH: path.relative(path.parse(altHome).root, altHome), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 5000, - expectError: true, - }); - - // Should handle path resolution correctly (no crash) - expect(result.exitCode).toBeDefined(); - }); - }); -}); diff --git a/extensions/cli/src/services/FileIndexService.test.ts b/extensions/cli/src/services/FileIndexService.test.ts index 9d5afb23a..193ca8b15 100644 --- a/extensions/cli/src/services/FileIndexService.test.ts +++ b/extensions/cli/src/services/FileIndexService.test.ts @@ -59,24 +59,25 @@ describe("FileIndexService", () => { expect(filePaths).toContain("README.md"); }); - it("should filter files correctly", async () => { + it("should filter files correctly with fzf", async () => { // Create test files fs.writeFileSync("component.tsx", "export default () =>
"); fs.writeFileSync("utils.ts", "export const util = () => {}"); - fs.writeFileSync("styles.css", ".test { color: red; }"); + fs.writeFileSync("readme.md", "# Documentation"); await service.initialize(); - // Test filtering by extension - const tsFiles = service.filterFiles("ts"); - expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true); - expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true); - expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false); + // Test filtering with more specific terms that won't fuzzy match + const tsxFiles = await service.filterFiles("tsx"); + expect(tsxFiles.some((f) => f.path === "component.tsx")).toBe(true); + expect(tsxFiles.some((f) => f.path === "utils.ts")).toBe(false); + expect(tsxFiles.some((f) => f.path === "readme.md")).toBe(false); // Test filtering by name - const componentFiles = service.filterFiles("component"); + const componentFiles = await service.filterFiles("component"); expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true); expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false); + expect(componentFiles.some((f) => f.path === "readme.md")).toBe(false); }); it("should handle empty directory", async () => { @@ -123,7 +124,7 @@ describe("FileIndexService", () => { await service.initialize(); - const files = service.filterFiles(""); + const files = await service.filterFiles(""); expect(files[0].path).toBe("alpha.js"); expect(files[1].path).toBe("beta.js"); expect(files[2].path).toBe("zebra.js"); @@ -137,7 +138,7 @@ describe("FileIndexService", () => { await service.initialize(); - const filtered = service.filterFiles("test"); + const filtered = await service.filterFiles("test"); // Should include both files that match the filter expect(filtered.length).toBeGreaterThanOrEqual(2); @@ -155,7 +156,7 @@ describe("FileIndexService", () => { await service.initialize(); - const files = service.filterFiles("", 5); + const files = await service.filterFiles("", 5); expect(files.length).toBe(5); }); @@ -173,4 +174,36 @@ describe("FileIndexService", () => { await service.refreshIndex(); expect(service.getFiles().length).toBe(2); }); + + it("should handle fuzzy search with AsyncFzf", async () => { + // Create test files for fuzzy matching + fs.writeFileSync("user-service.ts", "export class UserService {}"); + fs.writeFileSync("user-model.ts", "export interface User {}"); + fs.writeFileSync("config.json", "{}"); + + await service.initialize(); + + // Test fuzzy search (should match both user files) + const userFiles = await service.filterFiles("usmo"); // us(er) mo(del) + expect(userFiles.length).equal(1); + expect(userFiles.some((f) => f.path === "user-model.ts")).toBe(true); + }); + + it("should find files with @ symbols when searched with @ pattern", async () => { + // Create test file with @ symbols in the name + fs.writeFileSync("test@123.txt", "test content"); + fs.writeFileSync("regular-file.js", "normal file"); + fs.writeFileSync("other@456.md", "other content"); + + await service.initialize(); + + // Search for "test@123" - should match "test@123.txt" + const results = await service.filterFiles("test@123"); + + expect(results.length).equal(1); + expect(results.some((f) => f.path === "test@123.txt")).toBe(true); + + // Should not match files that don't contain the @ pattern + expect(results.some((f) => f.path === "regular-file.js")).toBe(false); + }); }); diff --git a/extensions/cli/src/services/FileIndexService.ts b/extensions/cli/src/services/FileIndexService.ts index 3ef74c021..518ffe9c4 100644 --- a/extensions/cli/src/services/FileIndexService.ts +++ b/extensions/cli/src/services/FileIndexService.ts @@ -1,9 +1,7 @@ -import { glob, GlobOptionsWithFileTypesFalse } from "glob"; +import { fdir } from "fdir"; +import { AsyncFzf, FzfResultItem } from "fzf"; -import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js"; -import { getFileWatcher } from "../util/fileWatcher.js"; -import { isGitRepo } from "../util/git.js"; -import { isInHomeDirectory } from "../util/isInHomeDirectory.js"; +import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; @@ -12,6 +10,7 @@ import { serviceContainer } from "./ServiceContainer.js"; export interface FileItem { path: string; displayName: string; + positions?: Set; } export interface FileIndexServiceState { @@ -21,9 +20,79 @@ export interface FileIndexServiceState { } export class FileIndexService extends BaseService { - private fileSet = new Set(); - private fileWatcherInitialized = false; - private fileWatcherUnsubscribe: (() => void) | null = null; + private fzf: AsyncFzf | null = null; + + // Helper to check if a file should be included based on FILE_PATTERNS + private shouldIncludeFile(filePath: string): boolean { + const fileName = filePath.split("/").pop()?.toLowerCase() || ""; + const ext = fileName.split(".").pop(); + + // Check if file matches any of the original FILE_PATTERNS + const supportedExtensions = [ + "ts", + "tsx", + "js", + "jsx", + "py", + "java", + "cpp", + "c", + "h", + "hpp", + "cs", + "go", + "rs", + "rb", + "php", + "swift", + "kt", + "scala", + "md", + "json", + "yaml", + "yml", + "xml", + "html", + "css", + "scss", + "sass", + "less", + "sql", + "sh", + "dockerfile", + "makefile", + "cmake", + "gradle", + "toml", + "ini", + "env", + "txt", + "log", + ]; + + // Check extension match + if (ext && supportedExtensions.includes(ext)) { + return true; + } + + // Check special file patterns + if ( + fileName.startsWith("readme") || + fileName.startsWith("license") || + fileName.startsWith("changelog") || + fileName === "package.json" || + fileName === "cargo.toml" || + fileName === "pyproject.toml" || + fileName === "composer.json" || + fileName === "gemfile" || + fileName === ".gitignore" || + fileName.startsWith(".env") + ) { + return true; + } + + return false; + } constructor() { super("FileIndexService", { @@ -35,23 +104,11 @@ export class FileIndexService extends BaseService { async doInitialize(): Promise { await this.performFullIndex(); - this.setupFileWatcher(); return this.getState(); } async cleanup(): Promise { - if (this.fileWatcherUnsubscribe) { - this.fileWatcherUnsubscribe(); - this.fileWatcherUnsubscribe = null; - } - - // Stop the file watcher to prevent resource leaks - if (this.fileWatcherInitialized) { - const watcher = getFileWatcher(); - watcher.stopWatching(); - } - - this.fileWatcherInitialized = false; + // No cleanup needed - no file watchers or subscriptions } /** @@ -65,37 +122,74 @@ export class FileIndexService extends BaseService { serviceContainer.set("fileIndex", currentState); } - private async performFullIndex(): Promise { + private async performFullIndex( + bypassTimeout: boolean = false, + ): Promise { this.setState({ isIndexing: true, error: null }); try { - const inGitRepo = isGitRepo(); + const currentDir = process.cwd(); + logger.debug(`Starting file index in directory: ${currentDir}`); - if (isInHomeDirectory()) { - this.setState({ - isIndexing: false, - error: "Skipping full index as in home directory", + // Create file indexing promise + const fileIndexPromise = new fdir() + .withFullPaths() + .withRelativePaths() + .filter((path) => { + // Use the helper function that implements original FILE_PATTERNS logic + return this.shouldIncludeFile(path); + }) + .exclude((dirName) => { + // Exclude directories based on FILE_IGNORE_PATTERNS + for (const pattern of FILE_IGNORE_PATTERNS) { + if (pattern.startsWith("**/") && pattern.endsWith("/**")) { + const excludeDirName = pattern.slice(3, -3); + if (dirName === excludeDirName) { + return true; + } + } + } + return false; + }) + .crawl(currentDir) + .withPromise(); + + let allFiles: string[]; + + if (bypassTimeout) { + // Manual refresh - wait for completion regardless of time + allFiles = await fileIndexPromise; + } else { + // Automatic indexing - race against 1-second timeout + const timeoutPromise = new Promise<"timeout">((resolve) => { + setTimeout(() => { + resolve("timeout"); + }, 1000); }); - return; + + const result = await Promise.race([fileIndexPromise, timeoutPromise]); + + if (result === "timeout") { + this.setState({ + files: [], + isIndexing: false, + error: "directory-too-large", + }); + return; + } + + allFiles = result as string[]; } - const allMatches = await this.throttledGlob(FILE_PATTERNS, { - maxDepth: inGitRepo ? 15 : 3, - ignore: FILE_IGNORE_PATTERNS, - dot: true, - absolute: false, - }); - - const uniqueFiles = [...new Set(allMatches)]; - this.fileSet.clear(); - uniqueFiles.forEach((file) => this.fileSet.add(file)); - - const files = uniqueFiles.map((path) => ({ + const fileItems = allFiles.map((path) => ({ path, displayName: path, })); - this.setState({ files, isIndexing: false }); + this.rebuildFzf(fileItems); + this.setState({ files: fileItems, isIndexing: false }); + + logger.debug(`Indexed ${fileItems.length} files`); } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); @@ -104,116 +198,10 @@ export class FileIndexService extends BaseService { } } - private setupFileWatcher(): void { - if (this.fileWatcherInitialized) { - return; - } - - // Only enable file watching in git repositories - // Outside git repos (like home directory), file watching causes performance issues - // and provides little value since files change less predictably - const inGitRepo = isGitRepo(); - if (!inGitRepo) { - logger.debug("Skipping file watcher: not in a git repository"); - return; - } - - this.fileWatcherInitialized = true; - const watcher = getFileWatcher(); - - // Start watching the current directory - watcher.startWatching(); - - // Set up callback for incremental updates - this.fileWatcherUnsubscribe = watcher.onChange(() => { - this.handleFileSystemChange(); - }); - } - - private async handleFileSystemChange(): Promise { - try { - // Get current files from file system - const inGitRepo = isGitRepo(); - const allMatches = await this.throttledGlob(FILE_PATTERNS, { - maxDepth: inGitRepo ? 15 : 3, - ignore: FILE_IGNORE_PATTERNS, - dot: true, - absolute: false, - }); - - const currentFiles = new Set(allMatches); - const previousFiles = this.fileSet; - - // Find added and removed files - const addedFiles = [...currentFiles].filter( - (file) => !previousFiles.has(file), - ); - const removedFiles = [...previousFiles].filter( - (file) => !currentFiles.has(file), - ); - - // Only update if there are actual changes - if (addedFiles.length > 0 || removedFiles.length > 0) { - // Update internal file set - this.fileSet = currentFiles; - - // Create new files array - const files = [...currentFiles].map((path) => ({ - path, - displayName: path, - })); - - this.setState({ files }); - } - } catch (error) { - logger.error("Error handling file system change:", error); - const errorMessage = - error instanceof Error ? error.message : String(error); - this.setState({ error: errorMessage }); - } - } - - private async throttledGlob( - patterns: string[], - options: GlobOptionsWithFileTypesFalse, - batchSize = 100, - delay = 20, - ): Promise { - return new Promise((resolve, reject) => { - const allMatches: string[] = []; - let processed = 0; - let streamEnded = false; - - const globStream = glob.stream(patterns, options); - - globStream.on("data", (file: string) => { - allMatches.push(file); - processed++; - - if (processed % batchSize === 0) { - if (streamEnded) { - return; - } - globStream.pause(); - - setTimeout(() => { - if (streamEnded) { - return; - } - globStream.resume(); - }, delay); - } - }); - - globStream.on("end", () => { - streamEnded = true; - resolve(allMatches); - }); - - globStream.on("error", (err) => { - streamEnded = true; - reject(err); - }); + private rebuildFzf(files: FileItem[]): void { + this.fzf = new AsyncFzf(files, { + selector: (item: FileItem) => item.path, + casing: "case-insensitive", }); } @@ -230,11 +218,14 @@ export class FileIndexService extends BaseService { return this.getState().error; } - public async refreshIndex(): Promise { - await this.performFullIndex(); + public async refreshIndex(bypassTimeout: boolean = false): Promise { + await this.performFullIndex(bypassTimeout); } - public filterFiles(filterText: string, limit: number = 10): FileItem[] { + public async filterFiles( + filterText: string, + limit: number = 10, + ): Promise { const files = this.getFiles(); if (filterText.length === 0) { @@ -248,36 +239,16 @@ export class FileIndexService extends BaseService { .slice(0, limit); } - const lowerFilter = filterText.toLowerCase(); + // Use fzf for fuzzy search + if (!this.fzf) { + this.rebuildFzf(files); + } - return files - .filter((file) => { - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }) - .sort((a, b) => { - const aFileName = a.path.split("/").pop() || a.path; - const bFileName = b.path.split("/").pop() || b.path; - - // Prioritize exact matches in file name - const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); - const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); - - if (aNameMatch && !bNameMatch) return -1; - if (!aNameMatch && bNameMatch) return 1; - - // Then prioritize files that start with the filter - const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); - const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); - - if (aStartsWith && !bStartsWith) return -1; - if (!aStartsWith && bStartsWith) return 1; - - // Finally, sort by file name - return aFileName.localeCompare(bFileName); - }) - .slice(0, limit); + const results = await this.fzf!.find(filterText); + return results.slice(0, limit).map((entry: FzfResultItem) => ({ + path: entry.item.path, + displayName: entry.item.displayName, + positions: entry.positions, + })); } } diff --git a/extensions/cli/src/ui/FileSearchUI.tsx b/extensions/cli/src/ui/FileSearchUI.tsx index 6c4d2c266..866c0af17 100644 --- a/extensions/cli/src/ui/FileSearchUI.tsx +++ b/extensions/cli/src/ui/FileSearchUI.tsx @@ -1,8 +1,12 @@ -import { Box, Text } from "ink"; +import { Box, Text, useInput } from "ink"; import React, { useEffect, useState } from "react"; import { useServices } from "../hooks/useService.js"; -import { FileIndexServiceState } from "../services/FileIndexService.js"; +import { + FileIndexServiceState, + FileItem, +} from "../services/FileIndexService.js"; +import { services } from "../services/index.js"; interface FileSearchUIProps { filter: string; @@ -11,10 +15,45 @@ interface FileSearchUIProps { onFilesUpdated?: (files: FileItem[]) => void; } -interface FileItem { - path: string; - displayName: string; -} +// Highlighting component for matched characters +const HighlightedText: React.FC<{ text: string; positions?: Set }> = ({ + text, + positions, +}) => { + if (!positions || positions.size === 0) { + return <>{text}; + } + + const chars = text.split(""); + const elements: React.ReactNode[] = []; + + chars.forEach((char, index) => { + if (positions.has(index)) { + elements.push( + + {char} + , + ); + } else { + elements.push(char); + } + }); + + return <>{elements}; +}; + +// Reusable container for consistent layout +const FileSearchContainer: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => ( + + {children} + +); + +// Keyboard navigation shortcuts help text +const KEYBOARD_SHORTCUTS = + "↑/↓ to navigate, Enter to select, Tab to complete, Ctrl+r to refresh list"; const FileSearchUI: React.FC = ({ filter, @@ -23,89 +62,97 @@ const FileSearchUI: React.FC = ({ }) => { const [files, setFiles] = useState([]); - // Get file index service - const { services } = useServices<{ + // Get file index service state for reactive updates + const { services: serviceStates } = useServices<{ fileIndex: FileIndexServiceState; }>(["fileIndex"]); - const fileIndexService = services.fileIndex; + const fileIndexServiceState = serviceStates.fileIndex; useEffect(() => { - if (!fileIndexService) { + if (!fileIndexServiceState) { return; } - // Get filtered files from the service - const filteredFiles = fileIndexService.files - .filter((file) => { - if (filter.length === 0) { - return true; + // Use the FileIndexService's filterFiles method which includes fzf fuzzy matching + const fetchFilteredFiles = async () => { + try { + // console.log(`FileSearchUI: Filtering files with "${filter}", total files in state:`, fileIndexServiceState?.files?.length); + const filteredFiles = await services.fileIndex.filterFiles(filter, 10); + // console.log(`FileSearchUI: Filtered to ${filteredFiles.length} files`); + setFiles(filteredFiles); + + if (onFilesUpdated) { + onFilesUpdated(filteredFiles); } - const lowerFilter = filter.toLowerCase(); - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }) - .sort((a, b) => { - if (filter.length === 0) { - // Sort alphabetically when no filter - const aFileName = a.path.split("/").pop() || a.path; - const bFileName = b.path.split("/").pop() || b.path; - return aFileName.localeCompare(bFileName); + } catch (error) { + // Suppress expected "search cancelled" errors from AsyncFzf when typing fast + const errorMessage = + error instanceof Error ? error.message : String(error); + if (!errorMessage.includes("search cancelled")) { + console.error("Error filtering files:", error); } + setFiles([]); + } + }; - const lowerFilter = filter.toLowerCase(); - const aFileName = a.path.split("/").pop() || a.path; - const bFileName = b.path.split("/").pop() || b.path; + fetchFilteredFiles(); + }, [fileIndexServiceState?.files, filter, onFilesUpdated]); - // Prioritize exact matches in file name - const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); - const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); - - if (aNameMatch && !bNameMatch) return -1; - if (!aNameMatch && bNameMatch) return 1; - - // Then prioritize files that start with the filter - const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); - const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); - - if (aStartsWith && !bStartsWith) return -1; - if (!aStartsWith && bStartsWith) return 1; - - // Finally, sort by file name - return aFileName.localeCompare(bFileName); - }) - .slice(0, 10); - - setFiles(filteredFiles); - - if (onFilesUpdated) { - onFilesUpdated(filteredFiles); + // Handle Ctrl+R to refresh file index + useInput((input, key) => { + if (key.ctrl && input === "r") { + services.fileIndex.refreshIndex(true); // Bypass timeout for manual refresh } - }, [fileIndexService?.files, filter, onFilesUpdated]); + }); - if (fileIndexService?.isIndexing) { + if (fileIndexServiceState?.error) { + // Special handling for directory too large error + if (fileIndexServiceState.error === "directory-too-large") { + return ( + + + Ctrl+r to refresh list (this may take several seconds) + + + ); + } + + // Other errors return ( - - Indexing files... - + + + Error indexing files: {fileIndexServiceState.error} + + ); } - if (fileIndexService?.error) { - return ( - - Error indexing files: {fileIndexService.error} - - ); - } + if (files.length === 0 && !fileIndexServiceState?.isIndexing) { + // Only show "No matching files found" if: + // 1. There are files in the index (so it's not a system issue) + // 2. There's actually a search filter (not just "@") + if ( + fileIndexServiceState?.files && + fileIndexServiceState.files.length > 0 && + filter.length > 0 + ) { + return ( + + + No matching files found + + + ); + } - if (files.length === 0) { + // Show keyboard navigation hints return ( - - No matching files found - + + + {KEYBOARD_SHORTCUTS} + + ); } @@ -118,7 +165,13 @@ const FileSearchUI: React.FC = ({ {" "} - @{file.displayName} + + @ + + ); @@ -126,7 +179,7 @@ const FileSearchUI: React.FC = ({ - ↑/↓ to navigate, Enter to select, Tab to complete + {KEYBOARD_SHORTCUTS} diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index 3adfc6a5a..1102c4717 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -4,16 +4,11 @@ import React, { useMemo } from "react"; import { getDisplayableAsciiArt } from "../asciiArt.js"; import { MCPService } from "../services/MCPService.js"; -import { isInHomeDirectory } from "../util/isInHomeDirectory.js"; import { isModelCapable } from "../utils/modelCapability.js"; import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js"; import { TipsDisplay, shouldShowTip } from "./TipsDisplay.js"; -// Export the warning message for testing -export const HOME_DIRECTORY_WARNING = - "Run cn in a project directory for the best experience (currently in home directory)"; - interface IntroMessageProps { config?: AssistantUnrolled; model?: ModelConfig; @@ -27,8 +22,6 @@ const extractRuleNames = (rules: any[] = []): string[] => { ); }; -const userInHomeDirectory = isInHomeDirectory(); - const IntroMessage: React.FC = ({ config, model, @@ -139,14 +132,6 @@ const IntroMessage: React.FC = ({ {renderMcpPrompts()} {renderRules()} {renderMcpServers()} - - {/* Home directory warning */} - {userInHomeDirectory && ( - <> - {HOME_DIRECTORY_WARNING} - - - )} ); }; diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 199e18fb2..238e06d49 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -167,8 +167,8 @@ const UserInput: React.FC = ({ >([]); const { exit } = useApp(); - // Get file index service - const { services } = useServices<{ + // Get file index service state for reactive updates (unused but needed for service initialization) + useServices<{ fileIndex: FileIndexServiceState; }>(["fileIndex"]); @@ -297,45 +297,39 @@ const UserInput: React.FC = ({ // Check if we're in a file search context const beforeCursor = text.slice(0, cursor); - const lastAtIndex = beforeCursor.lastIndexOf("@"); - if (lastAtIndex === -1) { - setShowFileSearch(false); - } else { - // Check if there's any whitespace between the last @ and cursor - const afterAt = beforeCursor.slice(lastAtIndex + 1); - - if (afterAt.includes(" ") || afterAt.includes("\n")) { - setShowFileSearch(false); - } else { - // We're in a file search context - check if there are matching files - const fileIndexService = services.fileIndex; - if (fileIndexService) { - const filteredFiles = fileIndexService.files.filter((file) => { - if (afterAt.length === 0) { - return true; - } - const lowerFilter = afterAt.toLowerCase(); - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }); - - // If no files match, hide the dropdown to allow normal Enter behavior - if (filteredFiles.length === 0 && afterAt.length > 0) { - setShowFileSearch(false); - return; + // Find the first @ symbol that starts a file search context + // We need to find the last @ that has no space before it (or is at word boundary) + let firstAtIndex = -1; + for (let i = beforeCursor.length - 1; i >= 0; i--) { + if (beforeCursor[i] === "@") { + // Check if this @ is at the start of a word (preceded by space/newline or start of string) + const beforeAt = beforeCursor.slice(0, i); + const lastChar = beforeAt[beforeAt.length - 1]; + if (i === 0 || lastChar === " " || lastChar === "\n") { + // Check if there's any space/newline between this @ and cursor + const afterThis = beforeCursor.slice(i + 1); + if (!afterThis.includes(" ") && !afterThis.includes("\n")) { + firstAtIndex = i; + break; } } - - setShowFileSearch(true); - setFileSearchFilter(afterAt); - setSelectedFileIndex(0); - setShowSlashCommands(false); - setShowBashMode(false); } } + + if (firstAtIndex === -1) { + setShowFileSearch(false); + } else { + // Get ALL text after the @ symbol (including subsequent @ symbols) + const afterAt = beforeCursor.slice(firstAtIndex + 1); + + // We're in a file search context + setShowFileSearch(true); + setFileSearchFilter(afterAt); + setSelectedFileIndex(0); + setShowSlashCommands(false); + setShowBashMode(false); + } }; // Get filtered commands for navigation - using the same sorting logic as SlashCommandUI @@ -385,15 +379,32 @@ const UserInput: React.FC = ({ // Handle file selection const selectFile = async (filePath: string) => { const beforeCursor = inputText.slice(0, cursorPosition); - const lastAtIndex = beforeCursor.lastIndexOf("@"); - if (lastAtIndex !== -1) { - const beforeAt = inputText.slice(0, lastAtIndex); + // Find the first @ symbol that starts a file search context (same logic as updateFileSearchState) + let firstAtIndex = -1; + for (let i = beforeCursor.length - 1; i >= 0; i--) { + if (beforeCursor[i] === "@") { + // Check if this @ is at the start of a word (preceded by space/newline or start of string) + const beforeAt = beforeCursor.slice(0, i); + const lastChar = beforeAt[beforeAt.length - 1]; + if (i === 0 || lastChar === " " || lastChar === "\n") { + // Check if there's any space/newline between this @ and cursor + const afterThis = beforeCursor.slice(i + 1); + if (!afterThis.includes(" ") && !afterThis.includes("\n")) { + firstAtIndex = i; + break; + } + } + } + } + + if (firstAtIndex !== -1) { + const beforeAt = inputText.slice(0, firstAtIndex); const afterCursor = inputText.slice(cursorPosition); // Replace the partial file reference with the full file path const newText = beforeAt + "@" + filePath + " " + afterCursor; - const newCursorPos = lastAtIndex + 1 + filePath.length + 1; + const newCursorPos = firstAtIndex + 1 + filePath.length + 1; textBuffer.setText(newText); textBuffer.setCursor(newCursorPos); @@ -410,7 +421,14 @@ const UserInput: React.FC = ({ const content = await fs.readFile(absolutePath, "utf-8"); onFileAttached(absolutePath, content); } catch (error) { - console.error(`Error reading file ${filePath}:`, error); + // If file doesn't exist, just attach the filename without content + if (error instanceof Error && (error as any).code === "ENOENT") { + const path = await import("path"); + const absolutePath = path.resolve(filePath); + onFileAttached(absolutePath, filePath); + } else { + console.error(`Error reading file ${filePath}:`, error); + } } } } diff --git a/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx b/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx new file mode 100644 index 000000000..a0f6c41c6 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx @@ -0,0 +1,36 @@ +import * as path from "path"; + +import { describe, expect, it, vi } from "vitest"; + +// Test the missing file handling logic directly +describe("UserInput - Missing File Handling", () => { + it("should handle selecting non-existent files gracefully", async () => { + const mockOnFileAttached = vi.fn(); + + // Simulate the selectFile logic for a missing file + const filePath = "missing-file.txt"; + + try { + const fs = await import("fs/promises"); + const path = await import("path"); + const absolutePath = path.resolve(filePath); + const content = await fs.readFile(absolutePath, "utf-8"); + mockOnFileAttached(absolutePath, content); + } catch (error) { + // If file doesn't exist, just attach the filename without content + if (error instanceof Error && (error as any).code === "ENOENT") { + const path = await import("path"); + const absolutePath = path.resolve(filePath); + mockOnFileAttached(absolutePath, filePath); // Just the filename for missing file + } else { + console.error(`Error reading file ${filePath}:`, error); + } + } + + // Should have called onFileAttached with filename as content + expect(mockOnFileAttached).toHaveBeenCalledWith( + path.resolve(filePath), + filePath, + ); + }); +}); From e98ccbb28de644bea42efc2baa4fc2cd15525f82 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 18 Sep 2025 09:48:08 +0530 Subject: [PATCH 02/20] feat: display shortcuts for accept reject diff buttons --- gui/src/components/AcceptRejectDiffButtons.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index 6abdded6e..aa84101b2 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -67,6 +67,9 @@ export default function AcceptRejectAllButtons({
Reject + + {rejectShortcut} +
@@ -80,6 +83,9 @@ export default function AcceptRejectAllButtons({
Accept + + {acceptShortcut} +
From a67956b9e928b51ff3ce5e8a44370a57e2ea7e1e Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 18 Sep 2025 11:21:32 +0530 Subject: [PATCH 03/20] chore: remove unused (old) mcp section --- gui/src/pages/config/sections/McpSection.tsx | 379 ------------------- 1 file changed, 379 deletions(-) delete mode 100644 gui/src/pages/config/sections/McpSection.tsx diff --git a/gui/src/pages/config/sections/McpSection.tsx b/gui/src/pages/config/sections/McpSection.tsx deleted file mode 100644 index c24a9dbf4..000000000 --- a/gui/src/pages/config/sections/McpSection.tsx +++ /dev/null @@ -1,379 +0,0 @@ -import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml"; -import { - ArrowPathIcon, - ChevronDownIcon, - CircleStackIcon, - CommandLineIcon, - GlobeAltIcon, - UserCircleIcon, - WrenchScrewdriverIcon, -} from "@heroicons/react/24/outline"; -import { MCPServerStatus } from "core"; -import { useContext, useMemo, useState } from "react"; -import { ToolTip } from "../../../components/gui/Tooltip"; -import EditBlockButton from "../../../components/mainInput/Lump/EditBlockButton"; -import { Button, Card } from "../../../components/ui"; -import { useAuth } from "../../../context/Auth"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { updateConfig } from "../../../redux/slices/configSlice"; -import { selectCurrentOrg } from "../../../redux/slices/profilesSlice"; -import { ConfigHeader } from "../components/ConfigHeader"; - -interface MCPServerStatusProps { - server: MCPServerStatus; - serverFromYaml?: NonNullable[number]; -} -function MCPServerCard({ server, serverFromYaml }: MCPServerStatusProps) { - const [isExpanded, setIsExpanded] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const config = useAppSelector((store) => store.config.config); - const dispatch = useAppDispatch(); - - const updateMCPServerStatus = (status: MCPServerStatus["status"]) => { - // optimistic config update - dispatch( - updateConfig({ - ...config, - mcpServerStatuses: config.mcpServerStatuses.map((s) => - s.id === server.id - ? { - ...s, - status, - } - : s, - ), - }), - ); - }; - - const onAuthenticate = async () => { - updateMCPServerStatus("authenticating"); - await ideMessenger.request("mcp/startAuthentication", server); - }; - - const onRemoveAuth = async () => { - updateMCPServerStatus("authenticating"); - await ideMessenger.request("mcp/removeAuthentication", server); - }; - - const onRefresh = async () => { - updateMCPServerStatus("connecting"); - ideMessenger.post("mcp/reloadServer", { - id: server.id, - }); - }; - - const handleToggleExpanded = (e: React.MouseEvent) => { - // Don't expand if clicking on buttons - if ((e.target as HTMLElement).closest("button")) { - return; - } - setIsExpanded(!isExpanded); - }; - - return ( -
-
-
- -
-

0 ? "text-error" : ""}`} - > - {server.name} -

-
-
- -
- {server.isProtectedResource && ( - - - - )} - - - - - - - -
-
-
- - {isExpanded && server.status === "connected" && ( -
- {/* Tools, Prompts, Resources with counts */} -
- - {server.tools.map((tool, idx) => ( -
-
- {tool.name} - {tool.description && ( - - {tool.description} - - )} - {tool.inputSchema?.properties && - Object.keys(tool.inputSchema.properties).length > - 0 && ( -
- - Args: - -
- {Object.entries( - tool.inputSchema.properties, - ).map(([paramName, paramSchema], paramIdx) => ( -
- - {paramName} - - {paramSchema && - typeof paramSchema === "object" && - "type" in paramSchema && ( - - ({paramSchema.type}) - - )} -
- ))} -
-
- )} -
- {idx < server.tools.length - 1 && ( -
- )} -
- ))} - {server.tools.length === 0 && ( - No tools - )} - - } - > -
- - Tools: {server.tools.length} -
-
- - - {server.prompts.map((prompt, idx) => ( - {prompt.name} - ))} - {server.prompts.length === 0 && ( - No prompts - )} - - } - > -
- - - Prompts: {server.prompts.length} - -
-
- - - {[...server.resources, ...server.resourceTemplates].map( - (resource, idx) => ( - {resource.name} - ), - )} - {server.resources.length === 0 && ( - No resources - )} - - } - > -
- - - Resources:{" "} - {server.resources.length + server.resourceTemplates.length} - -
-
-
-
- )} - - {/* Error display below expandable section */} - {server.errors && server.errors.length > 0 && ( -
- {server.errors.map((error, errorIndex) => ( -
-
- - {error.length > 150 ? error.substring(0, 150) + "..." : error} - - {error.length > 150 && ( - - )} -
-
- ))} -
- )} -
- ); -} - -function McpSection() { - const currentOrg = useAppSelector(selectCurrentOrg); - const servers = useAppSelector( - (store) => store.config.config.mcpServerStatuses, - ); - const { selectedProfile } = useAuth(); - const ideMessenger = useContext(IdeMessengerContext); - const disableMcp = currentOrg?.policy?.allowMcpServers === false; - const isLocal = selectedProfile?.profileType === "local"; - - const mergedBlocks = useMemo(() => { - const parsed = selectedProfile?.rawYaml - ? parseConfigYaml(selectedProfile?.rawYaml ?? "") - : undefined; - return (servers ?? []).map((doc, index) => ({ - block: doc, - blockFromYaml: parsed?.mcpServers?.[index], - })); - }, [servers, selectedProfile]); - - const handleAddMcpServer = () => { - if (isLocal) { - void ideMessenger.request("config/addLocalWorkspaceBlock", { - blockType: "mcpServers", - }); - } else { - void ideMessenger.request("controlPlane/openUrl", { - path: "new?type=block&blockType=mcpServers", - orgSlug: undefined, - }); - } - }; - - if (disableMcp) { - return ( -
- - MCP servers are disabled in your organization - -
- ); - } - - return ( -
- - -
- {mergedBlocks && mergedBlocks.length > 0 ? ( - mergedBlocks.map(({ block, blockFromYaml }, index) => ( -
- - - - {index < mergedBlocks.length - 1 &&
} -
- )) - ) : ( - -
- - No MCP servers configured. Click the + button to add your first - server. - -
-
- )} -
-
- ); -} - -export { McpSection }; From 34f7492516c5542e263b9d81e9be51d3751fa7e7 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 18 Sep 2025 11:38:17 +0530 Subject: [PATCH 04/20] feat: add installation guides for mcp commands --- core/context/mcp/MCPConnection.ts | 13 +++++++++++ core/index.d.ts | 1 + .../pages/config/sections/ToolsSection.tsx | 22 ++++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 320a3e0e5..bdd3279a0 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -52,6 +52,7 @@ class MCPConnection { public status: MCPConnectionStatus = "not-connected"; public isProtectedResource = false; public errors: string[] = []; + public infos: string[] = []; public prompts: MCPPrompt[] = []; public tools: MCPTool[] = []; public resources: MCPResource[] = []; @@ -93,6 +94,7 @@ class MCPConnection { return { ...this.options, errors: this.errors, + infos: this.infos, prompts: this.prompts, resources: this.resources, resourceTemplates: this.resourceTemplates, @@ -122,6 +124,7 @@ class MCPConnection { this.resources = []; this.resourceTemplates = []; this.errors = []; + this.infos = []; this.stdioOutput = { stdout: "", stderr: "" }; this.abortController.abort(); @@ -280,6 +283,16 @@ class MCPConnection { if (msg.includes("spawn") && msg.includes("enoent")) { const command = msg.split(" ")[1]; errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`; + if (["uv", "uvx"].includes(command)) { + this.infos.push( + 'Please install uv by following the installation guide: https://docs.astral.sh/uv/getting-started/installation/', + ); + } + if (["node", "npx"].includes(command)) { + this.infos.push( + 'Please install npx by following the installation guide: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm', + ); + } } else { errorMessage += "Error: " + error.message; } diff --git a/core/index.d.ts b/core/index.d.ts index 6b0844d02..86008cec8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1333,6 +1333,7 @@ export interface MCPTool { export interface MCPServerStatus extends MCPOptions { status: MCPConnectionStatus; errors: string[]; + infos: string[]; isProtectedResource: boolean; prompts: MCPPrompt[]; diff --git a/gui/src/pages/config/sections/ToolsSection.tsx b/gui/src/pages/config/sections/ToolsSection.tsx index 101a7e9e5..c94c97a9e 100644 --- a/gui/src/pages/config/sections/ToolsSection.tsx +++ b/gui/src/pages/config/sections/ToolsSection.tsx @@ -5,7 +5,6 @@ import { CircleStackIcon, CommandLineIcon, GlobeAltIcon, - PlusIcon, UserCircleIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; @@ -268,6 +267,27 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { ))}
)} + + {server.infos && server.infos.length > 0 && ( +
+ {server.infos.map((info, infoIndex) => ( + + void ideMessenger.ide.showVirtualFile(server.name, info) + } + > + + + ))} +
+ )}
); } From 2411d6feae9d329c62235bc4f6794e2e92b37bf3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 18 Sep 2025 11:44:40 +0530 Subject: [PATCH 05/20] fix tests --- core/tools/mcpToolName.vitest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts index ad3815a9a..6a7042d8f 100644 --- a/core/tools/mcpToolName.vitest.ts +++ b/core/tools/mcpToolName.vitest.ts @@ -5,6 +5,7 @@ import { getMCPToolName } from "./mcpToolName"; const createMcpServer = (name: string): MCPServerStatus => ({ name, errors: [], + infos: [], prompts: [], tools: [], resources: [], From cb29cee0a194139da978edc3e287faad3e14543a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 18 Sep 2025 12:02:44 +0530 Subject: [PATCH 06/20] fix tests --- core/context/mcp/MCPConnection.vitest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts index 3f69d8f23..873805052 100644 --- a/core/context/mcp/MCPConnection.vitest.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -142,6 +142,7 @@ describe("MCPConnection", () => { expect(status).toEqual({ ...options, errors: [], + infos: [], isProtectedResource: false, prompts: [], resources: [], From a1801117899265b33277380f3881aa29ef8a056a Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Thu, 18 Sep 2025 10:31:24 -0700 Subject: [PATCH 07/20] fix: continue review indentation --- actions/general-review/action.yml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index dd18c447a..45bd6e7e0 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -213,15 +213,15 @@ EOF # Write prompt to temp file for better handling PROMPT_FILE="/tmp/continue-prompt-$.txt" cp review_prompt.txt "$PROMPT_FILE" - - # Use timeout to prevent hanging (240 seconds = 4 minutes) - if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then - echo "Error: Continue CLI command failed" - echo "CLI error log:" - cat cli_error.log - - # Create fallback review - cat > code_review.md << 'EOF' + + # Use timeout to prevent hanging (240 seconds = 4 minutes) + if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then + echo "Error: Continue CLI command failed" + echo "CLI error log:" + cat cli_error.log + + # Create fallback review + cat > code_review.md << 'EOF' ## Code Review Summary ⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration. @@ -231,9 +231,9 @@ EOF - Check that the organization and config path are valid - Ensure the Continue service is accessible EOF - else - echo "Review generated successfully" - fi + else + echo "Review generated successfully" + fi fi - name: Upload Review Results From a64eb6dc42e54f5b45d251c1407891df328bd097 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20B=C5=82ach?= Date: Thu, 18 Sep 2025 21:30:38 +0200 Subject: [PATCH 08/20] fix: send highlighted code with Ctrl+Shift+J action (#7835) Related to #7747 --- .../actions/ContinuePluginActions.kt | 32 +++++++++---------- .../editor/ToolTipComponent.kt | 4 +-- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index 05aa69bb6..d28d8258a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -61,26 +61,13 @@ class RejectDiffAction : AnAction() { class FocusContinueInputWithoutClearAction : ContinueToolbarAction() { override fun toolbarActionPerformed(project: Project) { - project.getBrowser()?.sendToWebview("focusContinueInputWithoutClear") - project.getBrowser()?.focusOnInput() + FocusActionUtil.sendHighlightedCodeWithMessageToWebview(project, "focusContinueInputWithoutClear") } } class FocusContinueInputAction : ContinueToolbarAction() { - override fun toolbarActionPerformed(project: Project) = - focusContinueInput(project) - - companion object { - fun focusContinueInput(project: Project?) { - val browser = project?.getBrowser() - ?: return - browser.sendToWebview("focusContinueInputWithNewSession") - browser.focusOnInput() - val rif = EditorUtils.getEditor(project)?.getHighlightedRIF() - ?: return - val code = HighlightedCodePayload(RangeInFileWithContents(rif.filepath, rif.range, rif.contents)) - browser.sendToWebview("highlightedCode", code) - } + override fun toolbarActionPerformed(project: Project) { + FocusActionUtil.sendHighlightedCodeWithMessageToWebview(project, "focusContinueInputWithNewSession") } } @@ -115,5 +102,16 @@ class OpenLogsAction : AnAction() { } } - +object FocusActionUtil { + fun sendHighlightedCodeWithMessageToWebview(project: Project?, messageType: String) { + val browser = project?.getBrowser() + ?: return + browser.sendToWebview(messageType) + browser.focusOnInput() + val rif = EditorUtils.getEditor(project)?.getHighlightedRIF() + ?: return + val code = HighlightedCodePayload(RangeInFileWithContents(rif.filepath, rif.range, rif.contents)) + browser.sendToWebview("highlightedCode", code) + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt index 902d522f4..6ac0b0a6b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt @@ -1,4 +1,4 @@ -import com.github.continuedev.continueintellijextension.actions.FocusContinueInputAction +import com.github.continuedev.continueintellijextension.actions.FocusActionUtil import com.github.continuedev.continueintellijextension.editor.openInlineEdit import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColorsManager @@ -92,7 +92,7 @@ class ToolTipComponent(editor: Editor, x: Int, y: Int) : editButton = StyledButton("Edit (${cmdCtrlChar}+I)") addToChatButton.addActionListener { e: ActionEvent? -> - FocusContinueInputAction.focusContinueInput(editor.project) + FocusActionUtil.sendHighlightedCodeWithMessageToWebview(editor.project, "focusContinueInputWithNewSession") editor.contentComponent.remove(this) } editButton.addActionListener { e: ActionEvent? -> From e4ce400cf9f69e35dd499fa4a922fb7e913b6b28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20B=C5=82ach?= Date: Thu, 18 Sep 2025 21:30:51 +0200 Subject: [PATCH 09/20] fix: avoid NPE when failing to create missing dirs on writeFile (#7833) Related to #7829 We have test coverage for this case (the directory is created automatically if missing), but apparently there's a scenario where it can't be created. This change makes the code handle such situations gracefully: instead of throwing an error, the file simply won't be created. Added extra logging to help debug this issue further. --- .../continue/file/FileUtils.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt index ba351ab02..ea7accbb7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.FileStats import com.github.continuedev.continueintellijextension.FileType import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction +import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project @@ -24,10 +25,11 @@ class FileUtils( fun writeFile(fileUri: String, content: String) { val path = VfsUtilCore.urlToPath(fileUri) val pathDirectory = VfsUtil.getParentDir(path) - ?: return + ?: return LOG.warn("Parent directory is null for $path") val vfsDirectory = VfsUtil.createDirectories(pathDirectory) + ?: return LOG.warn("Could not create directories for $path") val pathFilename = VfsUtil.extractFileName(path) - ?: return + ?: return LOG.warn("Could not get filename for $path") runWriteAction { val newFile = vfsDirectory.createChildData(this, pathFilename) VfsUtil.saveText(newFile, content) @@ -107,4 +109,8 @@ class FileUtils( } return fileUri } + + private companion object { + private val LOG = Logger.getInstance(FileUtils::class.java) + } } \ No newline at end of file From 95ba13e70bd99b4607b30723bf485e68b8348408 Mon Sep 17 00:00:00 2001 From: Ting-Wai <40179554+tingwai@users.noreply.github.com> Date: Thu, 18 Sep 2025 14:20:15 -0700 Subject: [PATCH 10/20] fix: point Continue review hash to latest main (#7841) --- .github/workflows/continue-detailed-review.yaml | 2 +- .github/workflows/continue-general-review.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml index 4ec1ba510..45154075c 100644 --- a/.github/workflows/continue-detailed-review.yaml +++ b/.github/workflows/continue-detailed-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Detailed PR Review - uses: continuedev/continue/actions/detailed-review@3ebd8232440080aa8891909753f69d75a87b2c86 + uses: continuedev/continue/actions/detailed-review@e3ed0b6218e5d339e2fb265d06a267e98e7c7585 with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: continuedev diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 57bc76c85..299797379 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Continue PR Review Action - uses: continuedev/continue/actions/general-review@3ebd8232440080aa8891909753f69d75a87b2c86 + uses: continuedev/continue/actions/general-review@e3ed0b6218e5d339e2fb265d06a267e98e7c7585 with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" From 02465b65284d96906507178f275ef7c23bed80c9 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Thu, 18 Sep 2025 15:34:52 -0700 Subject: [PATCH 11/20] fix: make config-yaml compatible with browser (#7842) --- .../config-yaml/src/interfaces/slugs.test.ts | 58 +++++++++++++++++++ packages/config-yaml/src/interfaces/slugs.ts | 49 +++++++++++++++- 2 files changed, 105 insertions(+), 2 deletions(-) diff --git a/packages/config-yaml/src/interfaces/slugs.test.ts b/packages/config-yaml/src/interfaces/slugs.test.ts index 423694dc6..b7dc89752 100644 --- a/packages/config-yaml/src/interfaces/slugs.test.ts +++ b/packages/config-yaml/src/interfaces/slugs.test.ts @@ -158,4 +158,62 @@ describe("PackageIdentifier", () => { "Unknown URI type: invalid", ); }); + + it("should expand leading tilde when HOME is available", () => { + const originalHome = process.env.HOME; + const originalUserProfile = process.env.USERPROFILE; + + try { + process.env.HOME = "/tmp/test-home"; + delete process.env.USERPROFILE; + + const decoded = decodePackageIdentifier("~/package.yaml"); + + expect(decoded).toEqual({ + uriType: "file" as const, + fileUri: "/tmp/test-home/package.yaml", + }); + } finally { + if (originalHome === undefined) { + delete process.env.HOME; + } else { + process.env.HOME = originalHome; + } + + if (originalUserProfile === undefined) { + delete process.env.USERPROFILE; + } else { + process.env.USERPROFILE = originalUserProfile; + } + } + }); + + it("should leave leading tilde when no home directory is available", () => { + const originalHome = process.env.HOME; + const originalUserProfile = process.env.USERPROFILE; + + try { + delete process.env.HOME; + delete process.env.USERPROFILE; + + const decoded = decodePackageIdentifier("~/package.yaml"); + + expect(decoded).toEqual({ + uriType: "file" as const, + fileUri: "~/package.yaml", + }); + } finally { + if (originalHome === undefined) { + delete process.env.HOME; + } else { + process.env.HOME = originalHome; + } + + if (originalUserProfile === undefined) { + delete process.env.USERPROFILE; + } else { + process.env.USERPROFILE = originalUserProfile; + } + } + }); }); diff --git a/packages/config-yaml/src/interfaces/slugs.ts b/packages/config-yaml/src/interfaces/slugs.ts index 18b168577..30197d059 100644 --- a/packages/config-yaml/src/interfaces/slugs.ts +++ b/packages/config-yaml/src/interfaces/slugs.ts @@ -1,4 +1,49 @@ -import os from "node:os"; +type ProcessWithEnv = { + env?: Record; +}; + +function getProcessEnv(): Record | undefined { + if ( + typeof process !== "undefined" && + process && + typeof process === "object" + ) { + return (process as ProcessWithEnv).env; + } + + if (typeof globalThis !== "undefined") { + const maybeProcess = (globalThis as { process?: ProcessWithEnv }).process; + return maybeProcess?.env; + } + + return undefined; +} + +function getHomeDirectory(): string | undefined { + const env = getProcessEnv(); + + const fromHome = env?.HOME?.trim(); + if (fromHome) { + return fromHome; + } + + const fromUserProfile = env?.USERPROFILE?.trim(); + if (fromUserProfile) { + return fromUserProfile; + } + + return undefined; +} + +function expandLeadingTilde(identifier: string): string { + const homeDirectory = getHomeDirectory(); + if (!homeDirectory) { + return identifier; + } + + // Only replace a leading ~ so relative paths like ../~file stay untouched + return homeDirectory + identifier.slice(1); +} export interface PackageSlug { ownerSlug: string; @@ -67,7 +112,7 @@ export function decodePackageIdentifier(identifier: string): PackageIdentifier { else if (identifier.startsWith("~")) { return { uriType: "file", - fileUri: identifier.replace("~", os.homedir()), + fileUri: expandLeadingTilde(identifier), }; } // Otherwise, it's a slug From 961892fd86f0e3d7c55640378a867809250003e5 Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Thu, 18 Sep 2025 20:59:40 -0700 Subject: [PATCH 12/20] feat: split large blocks of chat history to reduce flickering --- .../cli/src/ui/components/MemoizedMessage.tsx | 10 +- .../src/ui/components/StaticChatContent.tsx | 38 ++-- .../cli/src/ui/hooks/useMessageRenderer.tsx | 42 +++-- .../cli/src/ui/utils/historySplitting.test.ts | 58 ++++++ .../cli/src/ui/utils/historySplitting.ts | 170 ++++++++++++++++++ .../cli/src/ui/utils/messageSplitting.test.ts | 54 ++++++ .../cli/src/ui/utils/messageSplitting.ts | 128 +++++++++++++ 7 files changed, 469 insertions(+), 31 deletions(-) create mode 100644 extensions/cli/src/ui/utils/historySplitting.test.ts create mode 100644 extensions/cli/src/ui/utils/historySplitting.ts create mode 100644 extensions/cli/src/ui/utils/messageSplitting.test.ts create mode 100644 extensions/cli/src/ui/utils/messageSplitting.ts diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index ebec26450..8a38778bf 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -44,10 +44,11 @@ function formatMessageContentForDisplay( interface MemoizedMessageProps { item: ChatHistoryItem; index: number; + hideBullet?: boolean; } export const MemoizedMessage = memo( - ({ item, index }) => { + ({ item, index, hideBullet = false }) => { const { message, toolCallStates, conversationSummary } = item; const isUser = message.role === "user"; const isSystem = message.role === "system"; @@ -93,7 +94,7 @@ export const MemoizedMessage = memo( {/* Render assistant message content if any */} {message.content && ( - ● + {hideBullet ? " " : "●"} ( return ( - ● + {hideBullet ? " " : "●"} {isUser ? ( @@ -195,7 +196,8 @@ export const MemoizedMessage = memo( JSON.stringify(prevToolStates) === JSON.stringify(nextToolStates) && prevProps.item.conversationSummary === nextProps.item.conversationSummary && - prevProps.index === nextProps.index + prevProps.index === nextProps.index && + prevProps.hideBullet === nextProps.hideBullet ); }, ); diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 59effa0d2..3dcf80490 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -7,6 +7,7 @@ import type { MCPService } from "../../services/MCPService.js"; import type { QueuedMessage } from "../../stream/messageQueue.js"; import { useTerminalSize } from "../hooks/useTerminalSize.js"; import { IntroMessage } from "../IntroMessage.js"; +import { splitChatHistory } from "../utils/historySplitting.js"; interface StaticChatContentProps { showIntroMessage: boolean; @@ -15,8 +16,12 @@ interface StaticChatContentProps { mcpService?: MCPService; chatHistory: ChatHistoryItem[]; queuedMessages?: QueuedMessage[]; - renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement; - refreshTrigger?: number; // Add a prop to trigger refresh from parent + renderMessage: ( + item: ChatHistoryItem, + index: number, + allMessages?: ChatHistoryItem[], + ) => React.ReactElement; + refreshTrigger?: number; } export const StaticChatContent: React.FC = ({ @@ -32,7 +37,7 @@ export const StaticChatContent: React.FC = ({ const { columns, rows } = useTerminalSize(); const { stdout } = useStdout(); - // State for managing static refresh with key-based remounting (gemini-cli approach) + // State for managing static refresh with key-based remounting const [staticKey, setStaticKey] = useState(0); const isInitialMount = useRef(true); @@ -69,15 +74,18 @@ export const StaticChatContent: React.FC = ({ } }, [refreshTrigger, refreshStatic]); - // Filter out system messages without content - const filteredChatHistory = React.useMemo(() => { - return chatHistory.filter( + // Filter out system messages without content and split large messages + const processedChatHistory = React.useMemo(() => { + const filtered = chatHistory.filter( (item) => item.message.role !== "system" || item.message.content, ); - }, [chatHistory]); + + // Split large messages into multiple history items + return splitChatHistory(filtered, columns); + }, [chatHistory, columns]); // Split chat history into stable and pending items - // The last two items may have pending tool calls + // Keep more items static now that we've split large messages const { staticItems, pendingItems } = React.useMemo(() => { // Add intro message as first item if it should be shown const staticItems: React.ReactElement[] = []; @@ -92,22 +100,24 @@ export const StaticChatContent: React.FC = ({ ); } + // Since messages are now split into reasonably-sized chunks, + // we can keep more items static (only last 1-2 items dynamic) const PENDING_ITEMS_COUNT = 1; const stableCount = Math.max( 0, - filteredChatHistory.length - PENDING_ITEMS_COUNT, + processedChatHistory.length - PENDING_ITEMS_COUNT, ); - const stableHistory = filteredChatHistory.slice(0, stableCount); - const pendingHistory = filteredChatHistory.slice(stableCount); + const stableHistory = processedChatHistory.slice(0, stableCount); + const pendingHistory = processedChatHistory.slice(stableCount); // Add stable messages to static items stableHistory.forEach((item, index) => { - staticItems.push(renderMessage(item, index)); + staticItems.push(renderMessage(item, index, processedChatHistory)); }); // Pending items will be rendered dynamically outside Static const pendingItems = pendingHistory.map((item, index) => - renderMessage(item, stableCount + index), + renderMessage(item, stableCount + index, processedChatHistory), ); return { @@ -119,7 +129,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, - filteredChatHistory, + processedChatHistory, renderMessage, ]); diff --git a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx index 06caf3fc9..3f48d16a5 100644 --- a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx +++ b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx @@ -4,22 +4,38 @@ import type { ChatHistoryItem } from "../../../../../core/index.js"; import { MemoizedMessage } from "../components/MemoizedMessage.js"; export function useMessageRenderer() { - const renderMessage = useCallback((item: ChatHistoryItem, index: number) => { - // Generate a unique key by combining message role, content hash, and timestamp - // This provides a stable identifier that won't change during re-renders - const messageContent = - typeof item.message.content === "string" - ? item.message.content - : JSON.stringify(item.message.content); + const renderMessage = useCallback( + (item: ChatHistoryItem, index: number, allMessages?: ChatHistoryItem[]) => { + // Generate a unique key by combining message role, content hash, and timestamp + // This provides a stable identifier that won't change during re-renders + const messageContent = + typeof item.message.content === "string" + ? item.message.content + : JSON.stringify(item.message.content); - const toolCallsKey = item.toolCallStates - ? item.toolCallStates.map((tc) => tc.toolCallId).join("-") - : ""; + const toolCallsKey = item.toolCallStates + ? item.toolCallStates.map((tc) => tc.toolCallId).join("-") + : ""; - const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`; + // Check if this is a continuation of the previous message (same role) + const previousMessage = + allMessages && index > 0 ? allMessages[index - 1] : null; + const isContinuation = + previousMessage?.message.role === item.message.role; - return ; - }, []); + const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`; + + return ( + + ); + }, + [], + ); return { renderMessage }; } diff --git a/extensions/cli/src/ui/utils/historySplitting.test.ts b/extensions/cli/src/ui/utils/historySplitting.test.ts new file mode 100644 index 000000000..f4f860b1c --- /dev/null +++ b/extensions/cli/src/ui/utils/historySplitting.test.ts @@ -0,0 +1,58 @@ +import type { ChatHistoryItem } from "core"; +import { describe, expect, it } from "vitest"; + +import { splitChatHistory } from "./historySplitting.js"; + +// Helper to create a mock chat history item +function createMockChatHistoryItem( + content: string, + role: "user" | "assistant" = "assistant", +): ChatHistoryItem { + return { + message: { + role, + content, + }, + } as ChatHistoryItem; +} + +describe("messageHistorySplitting", () => { + describe("splitChatHistory", () => { + it("should split multiple large messages in chat history", () => { + const chatHistory = [ + createMockChatHistoryItem("Short message 1"), + createMockChatHistoryItem( + Array(30).fill("Long message 1").join("\n\n"), + ), + createMockChatHistoryItem("Short message 2"), + createMockChatHistoryItem( + Array(25).fill("Long message 2").join("\n\n"), + ), + ]; + + const result = splitChatHistory(chatHistory, 80); + + // Should have more items than the original (due to splits) + expect(result.length).toBeGreaterThan(chatHistory.length); + + // First and third messages should remain unchanged + expect(result[0].message.content).toBe("Short message 1"); + }); + + it("should maintain order after splitting", () => { + const chatHistory = [ + createMockChatHistoryItem("First"), + createMockChatHistoryItem(Array(30).fill("Long middle").join("\n\n")), + createMockChatHistoryItem("Last"), + ]; + + const result = splitChatHistory(chatHistory, 80); + + // First message should still be first + expect(result[0].message.content).toBe("First"); + + // Last message should still be last + expect(result[result.length - 1].message.content).toBe("Last"); + }); + }); +}); diff --git a/extensions/cli/src/ui/utils/historySplitting.ts b/extensions/cli/src/ui/utils/historySplitting.ts new file mode 100644 index 000000000..c5854746e --- /dev/null +++ b/extensions/cli/src/ui/utils/historySplitting.ts @@ -0,0 +1,170 @@ +import type { ChatHistoryItem } from "core"; + +import { findLastSafeSplitPoint } from "./messageSplitting.js"; + +const MAX_HEIGHT_BEFORE_SPLIT = 20; + +/** + * Splits a chat history item into multiple items if its content is too large. + * + * This function prevents UI flickering by breaking large messages into manageable chunks. + * It only splits at safe markdown boundaries (paragraph breaks: \n\n) to preserve formatting. + * + * Splitting behavior: + * - User messages: Split only when they have natural paragraph breaks (\n\n) + * - Assistant messages: Split when content exceeds height threshold + * - System messages: Never split + * - Messages with tool calls: Never split + * + * Common use cases: + * - User pastes multiple paragraphs of text -> Split at paragraph boundaries + * - User writes one long paragraph -> Keep as single message + * - Assistant generates long response -> Split at paragraph breaks (\n\n) + */ +function splitChatHistoryItem( + item: ChatHistoryItem, + terminalWidth: number, +): ChatHistoryItem[] { + // Don't split non-text messages or messages with tool calls + if (item.toolCallStates?.length || typeof item.message.content !== "string") { + return [item]; + } + + // Don't split system messages + if (item.message.role === "system") { + return [item]; + } + + const content = item.message.content; + + if (!shouldSplitContent(content, terminalWidth)) { + return [item]; + } + + return splitContentIntoHistoryItems(item, content, terminalWidth); +} + +/** + * Splits content into multiple chat history items at safe markdown boundaries. + */ +function splitContentIntoHistoryItems( + originalItem: ChatHistoryItem, + content: string, + terminalWidth: number, +): ChatHistoryItem[] { + const items: ChatHistoryItem[] = []; + let remainingContent = content; + let itemIndex = 0; + + while (remainingContent.length > 0) { + if (!shouldSplitContent(remainingContent, terminalWidth)) { + // Remaining content is small enough, add it as the final item + if (remainingContent.trim()) { + items.push({ + ...originalItem, + message: { + ...originalItem.message, + content: remainingContent, + }, + }); + } + break; + } + + // Find safe split point + const splitPoint = findLastSafeSplitPoint(remainingContent); + + if (splitPoint === remainingContent.length) { + // No safe split point found, add as single large item + if (remainingContent.trim()) { + items.push({ + ...originalItem, + message: { + ...originalItem.message, + content: remainingContent, + }, + }); + } + break; + } + + // Split at the safe point + const beforeText = remainingContent.slice(0, splitPoint).trim(); + remainingContent = remainingContent.slice(splitPoint).trim(); + + if (beforeText) { + items.push({ + ...originalItem, + message: { + ...originalItem.message, + content: beforeText, + }, + }); + } + + itemIndex++; + + // Prevent infinite loops + if (itemIndex > 50) { + console.warn("Message splitting exceeded maximum iterations, stopping"); + if (remainingContent.trim()) { + items.push({ + ...originalItem, + message: { + ...originalItem.message, + content: remainingContent, + }, + }); + } + break; + } + } + + return items; +} + +/** + * Processes an entire chat history array, splitting large items into multiple items. + */ +export function splitChatHistory( + chatHistory: ChatHistoryItem[], + terminalWidth: number, +): ChatHistoryItem[] { + const result: ChatHistoryItem[] = []; + + for (const item of chatHistory) { + const splitItems = splitChatHistoryItem(item, terminalWidth); + result.push(...splitItems); + } + + return result; +} + +/** + * Estimates the height in terminal rows that content will take when rendered. + */ +function estimateContentHeight(content: string, terminalWidth: number): number { + if (!content) return 0; + + const lines = content.split("\n"); + let totalHeight = 0; + + for (const line of lines) { + if (line.length === 0) { + totalHeight += 1; // Empty line + } else { + // Account for line wrapping + totalHeight += Math.ceil(line.length / Math.max(terminalWidth - 2, 40)); + } + } + + return totalHeight; +} + +/** + * Determines if content should be split based on its estimated height. + */ +function shouldSplitContent(content: string, terminalWidth: number): boolean { + const estimatedHeight = estimateContentHeight(content, terminalWidth); + return estimatedHeight > MAX_HEIGHT_BEFORE_SPLIT; +} diff --git a/extensions/cli/src/ui/utils/messageSplitting.test.ts b/extensions/cli/src/ui/utils/messageSplitting.test.ts new file mode 100644 index 000000000..b98a549de --- /dev/null +++ b/extensions/cli/src/ui/utils/messageSplitting.test.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * NOTICE: This file has been modified from the original Gemini CLI source + * for integration with Continue CLI (cn) + */ + +import { describe, expect, it } from "vitest"; + +import { findLastSafeSplitPoint } from "./messageSplitting.js"; + +describe("markdownUtilities", () => { + describe("findLastSafeSplitPoint", () => { + it("should split at the last double newline if not in a code block", () => { + const content = "paragraph1\n\nparagraph2\n\nparagraph3"; + expect(findLastSafeSplitPoint(content)).toBe(24); // After the second \n\n + }); + + it("should return content.length if no safe split point is found", () => { + const content = "longstringwithoutanysafesplitpoint"; + expect(findLastSafeSplitPoint(content)).toBe(content.length); + }); + + it("should prioritize splitting at \n\n over being at the very end of the string if the end is not in a code block", () => { + const content = "Some text here.\n\nAnd more text here."; + expect(findLastSafeSplitPoint(content)).toBe(17); // after the \n\n + }); + + it("should return content.length if the only \n\n is inside a code block and the end of content is not", () => { + const content = "```\nignore this\n\nnewline\n```KeepThis"; + expect(findLastSafeSplitPoint(content)).toBe(content.length); + }); + + it("should correctly identify the last \n\n even if it is followed by text not in a code block", () => { + const content = + "First part.\n\nSecond part.\n\nThird part, then some more text."; + // Split should be after "Second part.\n\n" + // "First part.\n\n" is 13 chars. "Second part.\n\n" is 14 chars. Total 27. + expect(findLastSafeSplitPoint(content)).toBe(27); + }); + + it("should return content.length if content is empty", () => { + const content = ""; + expect(findLastSafeSplitPoint(content)).toBe(0); + }); + + it("should return content.length if content has no newlines and no code blocks", () => { + const content = "Single line of text"; + expect(findLastSafeSplitPoint(content)).toBe(content.length); + }); + }); +}); diff --git a/extensions/cli/src/ui/utils/messageSplitting.ts b/extensions/cli/src/ui/utils/messageSplitting.ts new file mode 100644 index 000000000..73cdb26c3 --- /dev/null +++ b/extensions/cli/src/ui/utils/messageSplitting.ts @@ -0,0 +1,128 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * NOTICE: This file has been modified from the original Gemini CLI source + * for integration with Continue CLI (cn) + */ + +/* +**Background & Purpose:** + +The `findSafeSplitPoint` function is designed to address the challenge of displaying or processing large, potentially streaming, pieces of Markdown text. When content (e.g., from an LLM like Gemini) arrives in chunks or grows too large for a single display unit (like a message bubble), it needs to be split. A naive split (e.g., just at a character limit) can break Markdown formatting, especially critical for multi-line elements like code blocks, lists, or blockquotes, leading to incorrect rendering. + +This function aims to find an *intelligent* or "safe" index within the provided `content` string at which to make such a split, prioritizing the preservation of Markdown integrity. + +**Key Expectations & Behavior (Prioritized):** + +1. **No Split if Short Enough:** + * If `content.length` is less than or equal to `idealMaxLength`, the function should return `content.length` (indicating no split is necessary for length reasons). + +2. **Code Block Integrity (Highest Priority for Safety):** + * The function must try to avoid splitting *inside* a fenced code block (i.e., between ` ``` ` and ` ``` `). + * If `idealMaxLength` falls within a code block: + * The function will attempt to return an index that splits the content *before* the start of that code block. + * If a code block starts at the very beginning of the `content` and `idealMaxLength` falls within it (meaning the block itself is too long for the first chunk), the function might return `0`. This effectively makes the first chunk empty, pushing the entire oversized code block to the second part of the split. + * When considering splits near code blocks, the function prefers to keep the entire code block intact in one of the resulting chunks. + +3. **Markdown-Aware Newline Splitting (If Not Governed by Code Block Logic):** + * If `idealMaxLength` does not fall within a code block (or after code block considerations have been made), the function will look for natural break points by scanning backwards from `idealMaxLength`: + * **Paragraph Breaks:** It prioritizes splitting after a double newline (`\n\n`), as this typically signifies the end of a paragraph or a block-level element. + * **Single Line Breaks:** If no double newline is found in a suitable range, it will look for a single newline (`\n`). + * Any newline chosen as a split point must also not be inside a code block. + +4. **Fall back to `idealMaxLength`:** + * If no "safer" split point (respecting code blocks or finding suitable newlines) is identified before or at `idealMaxLength`, and `idealMaxLength` itself is not determined to be an unsafe split point (e.g., inside a code block), the function may return a length larger than `idealMaxLength`, again it CANNOT break markdown formatting. This could happen with very long lines of text without Markdown block structures or newlines. + +**In essence, `findSafeSplitPoint` tries to be a good Markdown citizen when forced to divide content, preferring structural boundaries over arbitrary character limits, with a strong emphasis on not corrupting code blocks.** +*/ + +/** + * Checks if a given character index within a string is inside a fenced (```) code block. + * @param content The full string content. + * @param indexToTest The character index to test. + * @returns True if the index is inside a code block's content, false otherwise. + */ +const isIndexInsideCodeBlock = ( + content: string, + indexToTest: number, +): boolean => { + let fenceCount = 0; + let searchPos = 0; + while (searchPos < content.length) { + const nextFence = content.indexOf("```", searchPos); + if (nextFence === -1 || nextFence >= indexToTest) { + break; + } + fenceCount++; + searchPos = nextFence + 3; + } + return fenceCount % 2 === 1; +}; + +/** + * Finds the starting index of the code block that encloses the given index. + * Returns -1 if the index is not inside a code block. + * @param content The markdown content. + * @param index The index to check. + * @returns Start index of the enclosing code block or -1. + */ +const findEnclosingCodeBlockStart = ( + content: string, + index: number, +): number => { + if (!isIndexInsideCodeBlock(content, index)) { + return -1; + } + let currentSearchPos = 0; + while (currentSearchPos < index) { + const blockStartIndex = content.indexOf("```", currentSearchPos); + if (blockStartIndex === -1 || blockStartIndex >= index) { + break; + } + const blockEndIndex = content.indexOf("```", blockStartIndex + 3); + if (blockStartIndex < index) { + if (blockEndIndex === -1 || index < blockEndIndex + 3) { + return blockStartIndex; + } + } + if (blockEndIndex === -1) break; + currentSearchPos = blockEndIndex + 3; + } + return -1; +}; + +export const findLastSafeSplitPoint = (content: string): number => { + const enclosingBlockStart = findEnclosingCodeBlockStart( + content, + content.length, + ); + if (enclosingBlockStart !== -1) { + // The end of the content is contained in a code block. Split right before. + return enclosingBlockStart; + } + + // Search for the last double newline (\n\n) not in a code block. + let searchStartIndex = content.length; + while (searchStartIndex >= 0) { + const dnlIndex = content.lastIndexOf("\n\n", searchStartIndex); + if (dnlIndex === -1) { + // No more double newlines found. + break; + } + + const potentialSplitPoint = dnlIndex + 2; + if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) { + return potentialSplitPoint; + } + + // If potentialSplitPoint was inside a code block, + // the next search should start *before* the \n\n we just found to ensure progress. + searchStartIndex = dnlIndex - 1; + } + + // If no safe double newline is found, return content.length + // to keep the entire content as one piece. + return content.length; +}; From d78fc99087ab80cddcaa5f7bdc74ee45d3fc9f9d Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Thu, 18 Sep 2025 23:44:25 -0700 Subject: [PATCH 13/20] feat: add Mercury Apply endpoint support to Inception LLM (#7827) * feat: add Mercury Apply endpoint support to Inception LLM * refactor: begin to clean up the apply / streamDiff code * fix: undo commenting out of instant apply * fix: use underlyingProviderName --- core/core.ts | 19 +- core/edit/constants.ts | 2 + core/edit/recursiveStream.ts | 54 +++++- core/edit/streamDiffLines.ts | 58 +++--- core/index.d.ts | 17 +- core/llm/llms/Inception.ts | 99 +++++++---- core/llm/templates/edit/gpt.ts | 7 + .../continue/ApplyToFileHandler.kt | 5 +- .../editor/DiffStreamHandler.kt | 6 +- .../editor/InlineEditPanel.kt | 2 +- .../continueintellijextension/types.kt | 3 +- extensions/vscode/src/apply/ApplyManager.ts | 25 ++- extensions/vscode/src/commands.ts | 3 +- .../vscode/src/diff/vertical/manager.ts | 26 ++- .../vscode/src/extension/VsCodeMessenger.ts | 1 + .../src/quickEdit/QuickEditQuickPick.ts | 1 + packages/config-yaml/package-lock.json | 4 +- packages/continue-sdk/package-lock.json | 2 +- .../openai-adapters/src/apis/Inception.ts | 167 +++++++++++------- 19 files changed, 337 insertions(+), 164 deletions(-) diff --git a/core/core.ts b/core/core.ts index 9888a78b6..730dbbb19 100644 --- a/core/core.ts +++ b/core/core.ts @@ -17,8 +17,8 @@ import { DataLogger } from "./data/log"; import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { countTokens } from "./llm/countTokens"; -import Ollama from "./llm/llms/Ollama"; import Lemonade from "./llm/llms/Lemonade"; +import Ollama from "./llm/llms/Ollama"; import { EditAggregator } from "./nextEdit/context/aggregateEdits"; import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -729,20 +729,13 @@ export class Core { data.fileUri ?? "current-file-stream", ); // not super important since currently cancelling apply will cancel all streams it's one file at a time - return streamDiffLines({ - highlighted: data.highlighted, - prefix: data.prefix, - suffix: data.suffix, + return streamDiffLines( + data, llm, - // rules included for edit, NOT apply - rulesToInclude: data.includeRulesInSystemMessage - ? config.rules - : undefined, - input: data.input, - language: data.language, - overridePrompt: undefined, abortController, - }); + undefined, + data.includeRulesInSystemMessage ? config.rules : undefined, + ); }); on("cancelApply", async (msg) => { diff --git a/core/edit/constants.ts b/core/edit/constants.ts index ecc3340ca..0fcc4853e 100644 --- a/core/edit/constants.ts +++ b/core/edit/constants.ts @@ -1 +1,3 @@ export const EDIT_MODE_STREAM_ID = "edit-mode"; + +export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>"; diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index a835fe357..5c9f2fef6 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -1,7 +1,14 @@ -import { ChatMessage, ILLM, Prediction, PromptLog } from ".."; +import { + ChatMessage, + ILLM, + Prediction, + PromptLog, + type StreamDiffLinesType, +} from ".."; import { DEFAULT_MAX_TOKENS } from "../llm/constants"; import { countTokens } from "../llm/countTokens"; import { renderChatMessage } from "../util/messageContent"; +import { APPLY_UNIQUE_TOKEN } from "./constants.js"; const INFINITE_STREAM_SAFETY = 0.9; @@ -17,6 +24,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`; export async function* recursiveStream( llm: ILLM, abortController: AbortController, + type: StreamDiffLinesType, prompt: ChatMessage[] | string, prediction: Prediction | undefined, currentBuffer = "", @@ -28,8 +36,11 @@ export async function* recursiveStream( let buffer = currentBuffer; // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries + const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm); if (typeof prompt === "string") { - const generator = llm.streamComplete(prompt, abortController.signal, { + const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt; + + const generator = llm.streamComplete(finalPrompt, abortController.signal, { raw: true, prediction: undefined, reasoning: false, @@ -62,7 +73,11 @@ export async function* recursiveStream( } } } else { - const generator = llm.streamChat(prompt, abortController.signal, { + const promptMessages = injectApplyToken + ? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN) + : prompt; + + const generator = llm.streamChat(promptMessages, abortController.signal, { raw: true, prediction: undefined, reasoning: false, @@ -104,3 +119,36 @@ export async function* recursiveStream( } } } + +function shouldInjectApplyToken(llm: ILLM): boolean { + const model = llm.model?.toLowerCase() ?? ""; + return ( + llm.underlyingProviderName === "inception" && model.includes("mercury") + ); +} + +function appendTokenToLastMessage( + messages: ChatMessage[], + token: string, +): ChatMessage[] { + if (messages.length === 0) { + return messages; + } + + const lastMessage = messages[messages.length - 1]; + if (typeof lastMessage.content !== "string") { + return messages; + } + + if (lastMessage.content.endsWith(token)) { + return messages; + } + + const updatedMessages = [...messages]; + updatedMessages[updatedMessages.length - 1] = { + ...lastMessage, + content: lastMessage.content + token, + }; + + return updatedMessages; +} diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 53caa0df5..b76cad23e 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -4,6 +4,7 @@ import { ILLM, Prediction, RuleWithSource, + StreamDiffLinesPayload, ToolResultChatMessage, UserChatMessage, } from "../"; @@ -20,6 +21,7 @@ import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; +import { defaultApplyPrompt } from "../llm/templates/edit/gpt"; import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; import { recursiveStream } from "./recursiveStream"; @@ -42,6 +44,20 @@ function constructEditPrompt( }); } +function constructApplyPrompt( + originalCode: string, + newCode: string, + llm: ILLM, +) { + const template = llm.promptTemplates?.apply ?? defaultApplyPrompt; + const rendered = llm.renderPromptTemplate(template, [], { + original_code: originalCode, + new_code: newCode, + }); + + return rendered; +} + export async function* addIndentation( diffLineGenerator: AsyncGenerator, indentation: string, @@ -58,27 +74,15 @@ function modelIsInept(model: string): boolean { return !(model.includes("gpt") || model.includes("claude")); } -export async function* streamDiffLines({ - prefix, - highlighted, - suffix, - llm, - abortController, - input, - language, - overridePrompt, - rulesToInclude, -}: { - prefix: string; - highlighted: string; - suffix: string; - llm: ILLM; - abortController: AbortController; - input: string; - language: string | undefined; - overridePrompt: ChatMessage[] | undefined; - rulesToInclude: RuleWithSource[] | undefined; -}): AsyncGenerator { +export async function* streamDiffLines( + options: StreamDiffLinesPayload, + llm: ILLM, + abortController: AbortController, + overridePrompt: ChatMessage[] | undefined, + rulesToInclude: RuleWithSource[] | undefined, +): AsyncGenerator { + const { type, prefix, highlighted, suffix, input, language } = options; + void Telemetry.capture( "inlineEdit", { @@ -104,7 +108,9 @@ export async function* streamDiffLines({ // For apply can be overridden with simply apply prompt let prompt = overridePrompt ?? - constructEditPrompt(prefix, highlighted, suffix, llm, input, language); + (type === "apply" + ? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm) + : constructEditPrompt(prefix, highlighted, suffix, llm, input, language)); // Rules can be included with edit prompt // If any rules are present this will result in using chat instead of legacy completion @@ -159,7 +165,13 @@ export async function* streamDiffLines({ content: highlighted, }; - const completion = recursiveStream(llm, abortController, prompt, prediction); + const completion = recursiveStream( + llm, + abortController, + type, + prompt, + prediction, + ); let lines = streamLines(completion); diff --git a/core/index.d.ts b/core/index.d.ts index ae2633595..2d9b9b7ba 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1393,7 +1393,9 @@ export interface ApplyState { autoFormattingDiff?: string; } -export interface StreamDiffLinesPayload { +export type StreamDiffLinesType = "edit" | "apply"; +interface StreamDiffLinesOptionsBase { + type: StreamDiffLinesType; prefix: string; highlighted: string; suffix: string; @@ -1404,6 +1406,19 @@ export interface StreamDiffLinesPayload { fileUri?: string; } +interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase { + type: "edit"; +} + +interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase { + type: "apply"; + newCode: string; +} + +type StreamDiffLinesPayload = + | StreamDiffLinesOptionsApply + | StreamDiffLinesOptionsEdit; + export interface HighlightedCodePayload { rangeInFileWithContents: RangeInFileWithContents; prompt?: string; diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts index 9d2b67ea7..3abce6cba 100644 --- a/core/llm/llms/Inception.ts +++ b/core/llm/llms/Inception.ts @@ -2,6 +2,7 @@ import { streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; +import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js"; import { UNIQUE_TOKEN } from "../../nextEdit/constants.js"; import OpenAI from "./OpenAI.js"; @@ -96,40 +97,21 @@ class Inception extends OpenAI { options: CompletionOptions, ): AsyncGenerator { if (this.isNextEdit(messages)) { - messages = this.removeNextEditToken(messages); - - // Use edit/completions endpoint. - const endpoint = new URL("edit/completions", this.apiBase); - - const resp = await this.fetch(endpoint, { - method: "POST", - body: JSON.stringify({ - model: options.model, - messages: messages, - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - frequency_penalty: options.frequencyPenalty, - presence_penalty: options.presencePenalty, - stop: options.stop, - stream: true, - }), - headers: { - "Content-Type": "application/json", - Accept: "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, + messages = this.removeToken(messages, UNIQUE_TOKEN); + yield* this.streamSpecialEndpoint( + "edit/completions", + messages, signal, - }); - - for await (const chunk of streamSse(resp)) { - if (chunk.choices?.[0]?.delta?.content) { - yield { - role: "assistant", - content: chunk.choices[0].delta.content, - }; - } - } + options, + ); + } else if (this.isApply(messages)) { + messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN); + yield* this.streamSpecialEndpoint( + "apply/completions", + messages, + signal, + options, + ); } else { // Use regular chat/completions endpoint - call parent OpenAI implementation. yield* super._streamChat(messages, signal, options); @@ -145,23 +127,68 @@ class Inception extends OpenAI { ); } - private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] { + private isApply(messages: ChatMessage[]): boolean { + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(APPLY_UNIQUE_TOKEN), + ); + } + + private removeToken(messages: ChatMessage[], token: string): ChatMessage[] { const lastMessage = messages[messages.length - 1]; if ( typeof lastMessage?.content === "string" && - lastMessage.content.endsWith(UNIQUE_TOKEN) + lastMessage.content.endsWith(token) ) { const cleanedMessages = [...messages]; cleanedMessages[cleanedMessages.length - 1] = { ...lastMessage, - content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + content: lastMessage.content.slice(0, -token.length), }; return cleanedMessages; } return messages; } + + private async *streamSpecialEndpoint( + path: string, + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL(path, this.apiBase); + + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp)) { + const content = chunk.choices?.[0]?.delta?.content; + if (content) { + yield { role: "assistant", content }; + } + } + } } export default Inception; diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts index 61d23a732..bafad3f3b 100644 --- a/core/llm/templates/edit/gpt.ts +++ b/core/llm/templates/edit/gpt.ts @@ -71,3 +71,10 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => { return paragraphs.join("\n\n"); }; + +export const defaultApplyPrompt: PromptTemplateFunction = ( + history, + otherData, +) => { + return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`; +}; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index 733b0bd86..a5ae5eb67 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -91,7 +91,8 @@ class ApplyToFileHandler( highlighted = currentContent, // Current file content suffix = "", // No suffix since we're rewriting the whole file modelTitle = null, // No model needed for search/replace instant apply - includeRulesInSystemMessage = false // No LLM involved, just diff generation + includeRulesInSystemMessage = false, // No LLM involved, just diff generation + isApply = true ) } @@ -145,7 +146,7 @@ class ApplyToFileHandler( // Stream the diffs diffStreamHandler.streamDiffLinesToEditor( - prompt, prefix, highlighted, suffix, llmTitle, false + prompt, prefix, highlighted, suffix, llmTitle, false, true ) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 274b2d458..7792397e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -97,7 +97,8 @@ class DiffStreamHandler( highlighted: String, suffix: String, modelTitle: String?, - includeRulesInSystemMessage: Boolean + includeRulesInSystemMessage: Boolean, + isApply: Boolean ) { isRunning = true sendUpdate(ApplyStateStatus.STREAMING) @@ -112,7 +113,8 @@ class DiffStreamHandler( language = virtualFile?.fileType?.name, modelTitle = modelTitle, includeRulesInSystemMessage = includeRulesInSystemMessage, - fileUri = virtualFile?.url + fileUri = virtualFile?.url, + isApply = isApply ), null ) { response -> diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt index e0dbcb0c2..914f70552 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt @@ -205,7 +205,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) customPanelRef.get().enter() diffStreamHandler.streamDiffLinesToEditor( - textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true + textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true, false ) } 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 cddcd035b..d937b0add 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 @@ -306,7 +306,8 @@ data class StreamDiffLinesPayload( val language: String?, val modelTitle: String?, val includeRulesInSystemMessage: Boolean, - val fileUri: String? + val fileUri: String?, + val isApply: Boolean ) data class AcceptOrRejectDiffPayload( diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index e57d9e815..e79d8fe16 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -244,6 +244,7 @@ export class ApplyManager { newCode: text, toolCallId, rulesToInclude: undefined, // No rules for apply + isApply: true, }); } else { // Non-streaming: accumulate LLM output, then apply via Myers diff @@ -295,17 +296,23 @@ export class ApplyManager { const streamedLines: string[] = []; // Use streamDiffLines to get the LLM output - const stream = streamDiffLines({ - highlighted: rangeContent, - prefix, - suffix, + const stream = streamDiffLines( + { + highlighted: rangeContent, + prefix, + suffix, + input: prompt, + language: getMarkdownLanguageTagForFile(fileUri), + type: "apply", + newCode, + includeRulesInSystemMessage: false, + modelTitle: llm.title ?? llm.model, + }, llm, - rulesToInclude: undefined, // No rules for apply - input: prompt, - language: getMarkdownLanguageTagForFile(fileUri), - overridePrompt: undefined, abortController, - }); + undefined, + undefined, + ); // Accumulate all the streamed content for await (const line of stream) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 05dd18300..aca5b0e29 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -8,8 +8,8 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; import { walkDirAsync } from "core/indexing/walkDir"; import { isModelInstaller } from "core/llm"; -import { startLocalOllama } from "core/util/ollamaHelper"; import { startLocalLemonade } from "core/util/lemonadeHelper"; +import { startLocalOllama } from "core/util/ollamaHelper"; import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -153,6 +153,7 @@ const getCommandsMap: ( llm, range, rulesToInclude: config.rules, + isApply: false, }); } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index e338656af..cdcf30000 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -302,6 +302,7 @@ export class VerticalDiffManager { newCode, toolCallId, rulesToInclude, + isApply, }: { input: string; llm: ILLM; @@ -311,6 +312,7 @@ export class VerticalDiffManager { newCode?: string; toolCallId?: string; rulesToInclude: undefined | RuleWithSource[]; + isApply: boolean; }): Promise { void vscode.commands.executeCommand( "setContext", @@ -468,17 +470,23 @@ export class VerticalDiffManager { const streamedLines: string[] = []; async function* recordedStream() { - const stream = streamDiffLines({ - highlighted: rangeContent, - prefix, - suffix, + const stream = streamDiffLines( + { + highlighted: rangeContent, + prefix, + suffix, + input, + language: getMarkdownLanguageTagForFile(fileUri), + type: isApply ? "apply" : "edit", + newCode: newCode ?? "", + includeRulesInSystemMessage: !!rulesToInclude && !isApply, + modelTitle: llm.title ?? llm.model, + }, llm, - rulesToInclude, - input, - language: getMarkdownLanguageTagForFile(fileUri), - overridePrompt, abortController, - }); + overridePrompt, + rulesToInclude, + ); for await (const line of stream) { if (line.type === "new" || line.type === "same") { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 352e4fd66..9af399c73 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -229,6 +229,7 @@ export class VsCodeMessenger { new vscode.Position(end.line, end.character), ), rulesToInclude: config.rules, + isApply: false, }); // Log dev data diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index af3b3f882..662a4e326 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -332,6 +332,7 @@ export class QuickEdit { quickEdit: this.previousInput, range: this.range, rulesToInclude: rules, + isApply: false, }); } diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 00d44cbc7..9f9724af4 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.17.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.17.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/continue-sdk/package-lock.json b/packages/continue-sdk/package-lock.json index 90b6b3401..2d9966303 100644 --- a/packages/continue-sdk/package-lock.json +++ b/packages/continue-sdk/package-lock.json @@ -20,7 +20,7 @@ }, "../config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.17.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/openai-adapters/src/apis/Inception.ts b/packages/openai-adapters/src/apis/Inception.ts index e32694277..eb5c2ba50 100644 --- a/packages/openai-adapters/src/apis/Inception.ts +++ b/packages/openai-adapters/src/apis/Inception.ts @@ -23,6 +23,7 @@ import { FimCreateParamsStreaming } from "./base.js"; // }; export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; +export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>"; export const INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/"; export class InceptionApi extends OpenAIApi { constructor(config: InceptionConfig) { @@ -38,37 +39,7 @@ export class InceptionApi extends OpenAIApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - const endpoint = new URL("edit/completions", this.apiBase); - const resp = await customFetch(this.config.requestOptions)(endpoint, { - method: "POST", - body: JSON.stringify({ - model: body.model, - messages: body.messages, - max_tokens: body.max_tokens, - temperature: body.temperature, - top_p: body.top_p, - frequency_penalty: body.frequency_penalty, - presence_penalty: body.presence_penalty, - stop: body.stop, - stream: true, - }), - headers: { - "Content-Type": "application/json", - Accept: "application/json", - Authorization: `Bearer ${this.config.apiKey}`, - }, - signal, - }); - - for await (const chunk of streamSse(resp as any)) { - if (chunk.choices?.[0]?.delta?.content) { - yield chatChunk({ - content: chunk.choices[0].delta.content, - finish_reason: chunk.choices[0].finish_reason || null, - model: body.model, - }); - } - } + yield* this.streamCustomEndpoint("edit/completions", body, signal); } // Add custom edit completions method (non-streaming). @@ -76,30 +47,7 @@ export class InceptionApi extends OpenAIApi { body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { - const endpoint = new URL("edit/completions", this.apiBase); - const resp = await customFetch(this.config.requestOptions)(endpoint, { - method: "POST", - body: JSON.stringify({ - model: body.model, - messages: body.messages, - max_tokens: body.max_tokens, - temperature: body.temperature, - top_p: body.top_p, - frequency_penalty: body.frequency_penalty, - presence_penalty: body.presence_penalty, - stop: body.stop, - stream: false, // Set to false for non-streaming - }), - headers: { - "Content-Type": "application/json", - Accept: "application/json", - Authorization: `Bearer ${this.config.apiKey}`, - }, - signal, - }); - - const data = await resp.json(); - return data as ChatCompletion; + return this.nonStreamCustomEndpoint("edit/completions", body, signal); } // Override the regular chat stream method to route to edit endpoint for next edit requests. @@ -108,8 +56,11 @@ export class InceptionApi extends OpenAIApi { signal: AbortSignal, ): AsyncGenerator { if (this.isNextEdit(body.messages)) { - body.messages = this.removeNextEditToken(body.messages); + body.messages = this.removeToken(body.messages, UNIQUE_TOKEN); yield* this.editCompletionStream(body, signal); + } else if (this.isApply(body.messages)) { + body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN); + yield* this.applyCompletionStream(body, signal); } else { yield* super.chatCompletionStream(body, signal); } @@ -121,13 +72,30 @@ export class InceptionApi extends OpenAIApi { signal: AbortSignal, ): Promise { if (this.isNextEdit(body.messages)) { - body.messages = this.removeNextEditToken(body.messages); + body.messages = this.removeToken(body.messages, UNIQUE_TOKEN); return this.editCompletionNonStream(body, signal); + } else if (this.isApply(body.messages)) { + body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN); + return this.applyCompletionNonStream(body, signal); } else { return super.chatCompletionNonStream(body, signal); } } + async *applyCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + yield* this.streamCustomEndpoint("apply/completions", body, signal); + } + + async applyCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + return this.nonStreamCustomEndpoint("apply/completions", body, signal); + } + async *fimStream( body: FimCreateParamsStreaming, signal: AbortSignal, @@ -179,24 +147,103 @@ export class InceptionApi extends OpenAIApi { ); } + private isApply(messages: ChatCompletionMessageParam[]): boolean { + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(APPLY_UNIQUE_TOKEN), + ); + } + // Remove the unique token from messages. - private removeNextEditToken( + private removeToken( messages: ChatCompletionMessageParam[], + token: string, ): ChatCompletionMessageParam[] { const lastMessage = messages[messages.length - 1]; if ( typeof lastMessage?.content === "string" && - lastMessage.content.endsWith(UNIQUE_TOKEN) + lastMessage.content.endsWith(token) ) { const cleanedMessages = [...messages]; cleanedMessages[cleanedMessages.length - 1] = { ...lastMessage, - content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + content: lastMessage.content.slice(0, -token.length), }; return cleanedMessages; } return messages; } + + private async *streamCustomEndpoint( + path: string, + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const endpoint = new URL(path, this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp as any)) { + const deltaContent = chunk.choices?.[0]?.delta?.content; + if (deltaContent) { + yield chatChunk({ + content: deltaContent, + finish_reason: chunk.choices[0].finish_reason || null, + model: body.model, + }); + } + } + } + + private async nonStreamCustomEndpoint( + path: string, + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + const endpoint = new URL(path, this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: false, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + const data = await resp.json(); + return data as ChatCompletion; + } } From 12e933bf9d13736c5f47728c436445ef4127fd52 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Fri, 19 Sep 2025 00:25:33 -0700 Subject: [PATCH 14/20] feat: next edit char-level diff (#7776) * remove filter from next edit svg border * reduce border radius to 2 in next edit svg * update border * remove strikethrough from next edit deletion ui * remove diff background for now * feat: word-level diff in next edit svg * fix: don't alternate non-responses due to empty chain * fix: log next edit completions to continue console * fix: test and update chaining behavior to avoid repetitive requests and avoid alternating non-responses --- core/codeRenderer/CodeRenderer.ts | 125 +++-- core/llm/index.ts | 4 + .../src/activation/NextEditWindowManager.ts | 21 +- .../ContinueCompletionProvider.vitest.ts | 488 ++++++++++++++++++ .../src/autocomplete/completionProvider.ts | 27 +- 5 files changed, 607 insertions(+), 58 deletions(-) create mode 100644 extensions/vscode/src/autocomplete/__tests__/ContinueCompletionProvider.vitest.ts diff --git a/core/codeRenderer/CodeRenderer.ts b/core/codeRenderer/CodeRenderer.ts index c61d2e3cb..c09b1ef51 100644 --- a/core/codeRenderer/CodeRenderer.ts +++ b/core/codeRenderer/CodeRenderer.ts @@ -19,7 +19,7 @@ import { getSingletonHighlighter, Highlighter, } from "shiki"; -import { DiffLine } from ".."; +import { DiffChar, DiffLine } from ".."; import { escapeForSVG, kebabOfThemeStr } from "../util/text"; interface CodeRendererOptions { @@ -228,6 +228,7 @@ export class CodeRenderer { options: ConversionOptions, currLineOffsetFromTop: number, newDiffLines: DiffLine[], + newDiffChars: DiffChar[], ): Promise { const strokeWidth = 1; const highlightedCodeHtml = await this.highlightCode( @@ -236,13 +237,14 @@ export class CodeRenderer { currLineOffsetFromTop, newDiffLines, ); - // console.log(highlightedCodeHtml); const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut( highlightedCodeHtml, options, + newDiffChars, ); const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); + const borderColor = "#6b6b6b"; const lines = code.split("\n"); const actualHeight = lines.length * options.lineHeight; @@ -256,12 +258,11 @@ export class CodeRenderer { } - + ${lineBackgrounds} ${guts} `; - // console.log(svg); return Buffer.from(svg, "utf8"); } @@ -269,11 +270,56 @@ export class CodeRenderer { convertShikiHtmlToSvgGut( shikiHtml: string, options: ConversionOptions, + diffChars: DiffChar[], ): { guts: string; lineBackgrounds: string } { const dom = new JSDOM(shikiHtml); const document = dom.window.document; const lines = Array.from(document.querySelectorAll(".line")); + + const additionSegmentsByLine = new Map< + number, + Array<{ start: number; end: number }> + >(); + + diffChars.forEach((diff) => { + if ( + diff.type !== "new" || + diff.newLineIndex === undefined || + diff.newCharIndexInLine === undefined + ) { + return; + } + + if (diff.char.includes("\n")) { + return; + } + + const start = diff.newCharIndexInLine; + const end = start + diff.char.length; + const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? []; + existing.push({ start, end }); + additionSegmentsByLine.set(diff.newLineIndex, existing); + }); + + additionSegmentsByLine.forEach((segments, lineIndex) => { + segments.sort((a, b) => a.start - b.start); + const merged: Array<{ start: number; end: number }> = []; + segments.forEach((segment) => { + if (merged.length === 0) { + merged.push({ ...segment }); + return; + } + + const last = merged[merged.length - 1]; + if (segment.start <= last.end) { + last.end = Math.max(last.end, segment.end); + } else { + merged.push({ ...segment }); + } + }); + additionSegmentsByLine.set(lineIndex, merged); + }); const svgLines = lines.map((line, index) => { const spans = Array.from(line.childNodes) .map((node) => { @@ -309,60 +355,37 @@ export class CodeRenderer { return `${spans}`; }); + const estimatedCharWidth = options.fontSize * 0.6; + const additionFill = "rgba(40, 167, 69, 0.25)"; + const lineBackgrounds = lines .map((line, index) => { const classes = line?.getAttribute("class") || ""; - const bgColor = classes.includes("highlighted") - ? this.editorLineHighlight - : classes.includes("diff add") - ? "rgba(255, 255, 0, 0.2)" - : this.editorBackground; - const y = index * options.lineHeight; - const isFirst = index === 0; - const isLast = index === lines.length - 1; - const isSingleLine = isFirst && isLast; - const radius = 10; + const segments = additionSegmentsByLine.get(index) ?? []; + const backgrounds: string[] = []; - // Handle single line case (both first and last) - if (isSingleLine) { - return ``; + if (classes.includes("highlighted")) { + backgrounds.push( + ``, + ); } - // SVG notes: - // By default SVGs have anti-aliasing on. - // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps. - // Turning it off with 'shape-rendering="crispEdges"' solves the issue. - return isFirst - ? `` - : isLast - ? `` - : ``; + segments.forEach(({ start, end }) => { + const widthInChars = Math.max(end - start, 0); + if (widthInChars <= 0) { + return; + } + const x = start * estimatedCharWidth; + const segmentWidth = widthInChars * estimatedCharWidth; + backgrounds.push( + ``, + ); + }); + + return backgrounds.join("\n"); }) + .filter((bg) => bg.length > 0) .join("\n"); return { @@ -394,6 +417,7 @@ export class CodeRenderer { options: ConversionOptions, currLineOffsetFromTop: number, newDiffLines: DiffLine[], + newDiffChars: DiffChar[], ): Promise { switch (options.imageType) { // case "png": @@ -413,6 +437,7 @@ export class CodeRenderer { options, currLineOffsetFromTop, newDiffLines, + newDiffChars, ); return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; } diff --git a/core/llm/index.ts b/core/llm/index.ts index 58808a80e..751a537ea 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1056,6 +1056,10 @@ export abstract class BaseLLM implements ILLM { const msg = fromChatResponse(response); yield msg; completion = this._formatChatMessage(msg); + interaction?.logItem({ + kind: "message", + message: msg, + }); } else { // Stream true const stream = this.openaiAdapter.chatCompletionStream( diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 1c1da98fd..a19a34b3f 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -41,10 +41,11 @@ const SVG_CONFIG = { // filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4)) // drop-shadow(8px 8px 0px rgba(107, 166, 205, 0.3)) // drop-shadow(12px 12px 0px rgba(136, 194, 163, 0.2));`, - filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4)) - drop-shadow(-2px 4px 0px rgba(107, 166, 205, 0.3)) - drop-shadow(4px -2px 0px rgba(136, 194, 163, 0.2)) - drop-shadow(-2px -2px 0px rgba(112, 114, 209, 0.2));`, + // filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4)) + // drop-shadow(-2px 4px 0px rgba(107, 166, 205, 0.3)) + // drop-shadow(4px -2px 0px rgba(136, 194, 163, 0.2)) + // drop-shadow(-2px -2px 0px rgba(112, 114, 209, 0.2));`, + filter: "none", radius: 3, leftMargin: 40, defaultText: "", @@ -413,6 +414,8 @@ export class NextEditWindowManager { ); } + const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); + // Create and apply decoration with the text. if (newEditRangeSlice !== "") { try { @@ -423,6 +426,7 @@ export class NextEditWindowManager { newEditRangeSlice, this.editableRegionStartLine, diffLines, + diffChars, ); } catch (error) { console.error("Failed to render window:", error); @@ -432,8 +436,6 @@ export class NextEditWindowManager { } } - const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); - this.renderDeletions(editor, diffChars); // Reserve tab and esc to either accept or reject the displayed next edit contents. @@ -686,6 +688,7 @@ export class NextEditWindowManager { text: string, currLineOffsetFromTop: number, newDiffLines: DiffLine[], + diffChars: DiffChar[], ): Promise< | { uri: vscode.Uri; dimensions: { width: number; height: number } } | undefined @@ -710,6 +713,7 @@ export class NextEditWindowManager { }, currLineOffsetFromTop, newDiffLines, + diffChars, ); return { @@ -733,12 +737,14 @@ export class NextEditWindowManager { position: vscode.Position, editableRegionStartLine: number, newDiffLines: DiffLine[], + diffChars: DiffChar[], ): Promise { const currLineOffsetFromTop = position.line - editableRegionStartLine; const uriAndDimensions = await this.createCodeRender( predictedCode, currLineOffsetFromTop, newDiffLines, + diffChars, ); if (!uriAndDimensions) { return undefined; @@ -857,6 +863,7 @@ export class NextEditWindowManager { predictedCode: string, editableRegionStartLine: number, newDiffLines: DiffLine[], + diffChars: DiffChar[], ) { // Capture document version to detect changes. const docVersion = editor.document.version; @@ -868,6 +875,7 @@ export class NextEditWindowManager { position, editableRegionStartLine, newDiffLines, + diffChars, ); if (!decoration) { console.error("Failed to create decoration for text:", predictedCode); @@ -944,7 +952,6 @@ export class NextEditWindowManager { const deleteDecorationType = vscode.window.createTextEditorDecorationType({ backgroundColor: "rgba(255, 0, 0, 0.5)", - textDecoration: "line-through", }); editor.setDecorations(deleteDecorationType, charsToDelete); diff --git a/extensions/vscode/src/autocomplete/__tests__/ContinueCompletionProvider.vitest.ts b/extensions/vscode/src/autocomplete/__tests__/ContinueCompletionProvider.vitest.ts new file mode 100644 index 000000000..9d6e816c6 --- /dev/null +++ b/extensions/vscode/src/autocomplete/__tests__/ContinueCompletionProvider.vitest.ts @@ -0,0 +1,488 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import * as vscode from "vscode"; + +import { ContinueCompletionProvider } from "../completionProvider"; + +import * as NextEditLoggingServiceModule from "core/nextEdit/NextEditLoggingService"; +import * as PrefetchQueueModule from "core/nextEdit/NextEditPrefetchQueue"; +import * as NextEditProviderModule from "core/nextEdit/NextEditProvider"; +import * as JumpManagerModule from "../../activation/JumpManager"; + +type MockNextEditProvider = ReturnType; +type MockPrefetchQueue = ReturnType; +type MockJumpManager = ReturnType; + +const mockOutcome = { + completion: "suggested change", + diffLines: [], + editableRegionStartLine: 0, + editableRegionEndLine: 0, +} as any; + +let mockNextEditProvider: MockNextEditProvider; +let mockPrefetchQueue: MockPrefetchQueue; +let mockJumpManager: MockJumpManager; + +beforeEach(() => { + vi.clearAllMocks(); + + mockNextEditProvider = createMockNextEditProvider(); + (NextEditProviderModule as any).__setMockNextEditProviderInstance( + mockNextEditProvider, + ); + + mockPrefetchQueue = createMockPrefetchQueue(); + (PrefetchQueueModule as any).__setMockPrefetchQueueInstance( + mockPrefetchQueue, + ); + + mockJumpManager = createMockJumpManager(); + (JumpManagerModule as any).__setMockJumpManagerInstance(mockJumpManager); + + const mockLoggingService = createMockLoggingService(); + (NextEditLoggingServiceModule as any).__setMockNextEditLoggingServiceInstance( + mockLoggingService, + ); + + (vscode.window as any).activeTextEditor = null; +}); + +describe("ContinueCompletionProvider triggering logic", () => { + it("starts a new chain when none exists", async () => { + const document = createDocument(); + setActiveEditor(document); + + const provider = buildProvider(); + + await provider.provideInlineCompletionItems( + document, + createPosition(), + createContext(), + createToken(), + ); + + expect(mockNextEditProvider.startChain).toHaveBeenCalledTimes(1); + expect( + mockNextEditProvider.provideInlineCompletionItems, + ).toHaveBeenCalledTimes(1); + expect(mockNextEditProvider.deleteChain).not.toHaveBeenCalled(); + }); + + it("clears an empty chain once in full file diff mode", async () => { + const document = createDocument(); + setActiveEditor(document); + + mockNextEditProvider.chainExists.mockReturnValue(true); + mockPrefetchQueue.__setProcessed([]); + mockPrefetchQueue.__setUnprocessed([]); + + const provider = buildProvider(); + + await provider.provideInlineCompletionItems( + document, + createPosition(), + createContext(), + createToken(), + ); + + expect(mockNextEditProvider.deleteChain).toHaveBeenCalledTimes(1); + expect(mockNextEditProvider.startChain).toHaveBeenCalledTimes(1); + expect( + mockNextEditProvider.provideInlineCompletionItems, + ).toHaveBeenCalledTimes(1); + }); + + it("returns null after clearing empty chain when no outcome is available", async () => { + const document = createDocument(); + setActiveEditor(document); + + mockNextEditProvider.chainExists.mockReturnValue(true); + mockPrefetchQueue.__setProcessed([]); + mockPrefetchQueue.__setUnprocessed([]); + mockNextEditProvider.provideInlineCompletionItems.mockResolvedValueOnce( + undefined, + ); + + const provider = buildProvider(); + + const result = await provider.provideInlineCompletionItems( + document, + createPosition(), + createContext(), + createToken(), + ); + + expect(result).toBeNull(); + expect(mockNextEditProvider.deleteChain).toHaveBeenCalledTimes(1); + expect(mockNextEditProvider.startChain).toHaveBeenCalledTimes(1); + expect( + mockNextEditProvider.provideInlineCompletionItems, + ).toHaveBeenCalledTimes(1); + }); + + it("uses queued outcomes when processed items exist", async () => { + const document = createDocument(); + setActiveEditor(document); + + mockNextEditProvider.chainExists.mockReturnValue(true); + mockPrefetchQueue.__setProcessed([ + { + location: { + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + }, + outcome: mockOutcome, + }, + ]); + mockJumpManager.suggestJump.mockResolvedValue(true); + + const provider = buildProvider(); + + await provider.provideInlineCompletionItems( + document, + createPosition(), + createContext(), + createToken(), + ); + + expect(mockPrefetchQueue.dequeueProcessed).toHaveBeenCalledTimes(1); + expect(mockJumpManager.setCompletionAfterJump).toHaveBeenCalledTimes(1); + expect(mockNextEditProvider.startChain).not.toHaveBeenCalled(); + expect(mockNextEditProvider.deleteChain).not.toHaveBeenCalled(); + expect( + mockNextEditProvider.provideInlineCompletionItems, + ).not.toHaveBeenCalled(); + }); +}); + +function buildProvider(options: { usingFullFileDiff?: boolean } = {}) { + const usingFullFileDiff = options.usingFullFileDiff ?? true; + const configHandler = { + loadConfig: vi.fn(async () => ({ + config: { selectedModelByRole: { autocomplete: undefined } }, + })), + } as any; + + const ide = { ideUtils: {} } as any; + const webviewProtocol = {} as any; + + const provider = new ContinueCompletionProvider( + configHandler, + ide, + webviewProtocol, + usingFullFileDiff, + ); + provider.activateNextEdit(); + return provider; +} + +function createDocument( + text = "function example() {\n return true;\n}", +): vscode.TextDocument { + const lines = text.split("\n"); + return { + uri: vscode.Uri.parse("file:///test"), + isUntitled: false, + getText: (range?: any) => { + if (!range) { + return text; + } + const startLine = range.start?.line ?? 0; + const endLine = range.end?.line ?? startLine; + const startChar = range.start?.character ?? 0; + const endChar = range.end?.character ?? lines[endLine]?.length ?? 0; + if (startLine === endLine) { + const lineText = lines[startLine] ?? ""; + return lineText.slice(startChar, endChar); + } + return text; + }, + lineAt: (position: any) => { + const lineNumber = + typeof position === "number" ? position : position.line; + const lineText = lines[lineNumber] ?? ""; + const range = new (vscode.Range as any)( + new (vscode.Position as any)(lineNumber, 0), + new (vscode.Position as any)(lineNumber, lineText.length), + ); + return { + lineNumber, + text: lineText, + range, + rangeIncludingLineBreak: range, + firstNonWhitespaceCharacterIndex: 0, + isEmptyOrWhitespace: lineText.trim().length === 0, + } as unknown as vscode.TextLine; + }, + } as unknown as vscode.TextDocument; +} + +function createContext(): any { + return { + triggerKind: (vscode.InlineCompletionTriggerKind as any).Automatic, + selectedCompletionInfo: undefined, + }; +} + +function createPosition(line = 0, character = 0) { + return new (vscode.Position as any)(line, character); +} + +function createToken(): any { + return { + isCancellationRequested: false, + onCancellationRequested: vi.fn(), + }; +} + +function setActiveEditor(document: any, cursor = createPosition()) { + const selection = { active: cursor, anchor: cursor }; + (vscode.window as any).activeTextEditor = { + document, + selection, + selections: [selection], + }; +} + +function createMockNextEditProvider() { + return { + chainExists: vi.fn(() => false), + startChain: vi.fn(), + deleteChain: vi.fn(async () => {}), + provideInlineCompletionItems: vi.fn(async () => mockOutcome), + provideInlineCompletionItemsWithChain: vi.fn(async () => mockOutcome), + markDisplayed: vi.fn(), + getChainLength: vi.fn(() => 0), + }; +} + +function createMockPrefetchQueue() { + let processedItems: any[] = []; + let unprocessedItems: any[] = []; + + const queue: any = { + initialize: vi.fn(), + process: vi.fn(), + peekThreeProcessed: vi.fn(), + dequeueProcessed: vi.fn(() => processedItems.shift()), + enqueueProcessed: vi.fn((item: any) => { + processedItems.push(item); + }), + __setProcessed(items: any[]) { + processedItems = [...items]; + }, + __setUnprocessed(items: any[]) { + unprocessedItems = [...items]; + }, + }; + + Object.defineProperty(queue, "processedCount", { + get: () => processedItems.length, + }); + + Object.defineProperty(queue, "unprocessedCount", { + get: () => unprocessedItems.length, + }); + + return queue; +} + +function createMockJumpManager() { + return { + isJumpInProgress: vi.fn(() => false), + setJumpInProgress: vi.fn(), + completionAfterJump: undefined, + clearCompletionAfterJump: vi.fn(), + setCompletionAfterJump: vi.fn(), + suggestJump: vi.fn(async () => false), + wasJumpJustAccepted: vi.fn(() => false), + }; +} + +function createMockLoggingService() { + return { + trackPendingCompletion: vi.fn(), + handleAbort: vi.fn(), + markDisplayed: vi.fn(), + cancelRejectionTimeout: vi.fn(), + deleteAbortController: vi.fn(), + cancel: vi.fn(), + }; +} + +vi.mock("vscode", () => { + class Position { + constructor( + public line: number, + public character: number, + ) {} + } + + class Range { + constructor( + public start: Position, + public end: Position, + ) {} + } + + class InlineCompletionItem { + public insertText: string; + public range: Range; + public command?: any; + + constructor(insertText: string, range: Range, command?: any) { + this.insertText = insertText; + this.range = range; + this.command = command; + } + } + + const window = { + activeTextEditor: null as any, + showErrorMessage: vi.fn(() => Promise.resolve(undefined)), + }; + + const workspace = { + notebookDocuments: [] as any[], + getConfiguration: vi.fn(() => ({ get: vi.fn() })), + }; + + return { + window, + workspace, + Uri: { parse: (value: string) => ({ toString: () => value }) }, + Position, + Range, + InlineCompletionItem, + InlineCompletionTriggerKind: { Automatic: 0, Invoke: 1 }, + NotebookCellKind: { Markup: 1 }, + }; +}); + +vi.mock("core/autocomplete/CompletionProvider", () => { + return { + CompletionProvider: class { + provideInlineCompletionItems = vi.fn(); + markDisplayed = vi.fn(); + }, + }; +}); + +vi.mock("core/autocomplete/util/processSingleLineCompletion", () => ({ + processSingleLineCompletion: vi.fn((text: string) => ({ + completionText: text, + range: { start: 0, end: text.length }, + })), +})); + +vi.mock("../statusBar", () => { + const StatusBarStatus = { + Enabled: "enabled", + Disabled: "disabled", + } as const; + + return { + StatusBarStatus, + getStatusBarStatus: vi.fn(() => StatusBarStatus.Enabled), + setupStatusBar: vi.fn(), + stopStatusBarLoading: vi.fn(), + }; +}); + +vi.mock("../GhostTextAcceptanceTracker", () => { + const instance = { + setExpectedGhostTextAcceptance: vi.fn(), + }; + return { + GhostTextAcceptanceTracker: { + getInstance: () => instance, + }, + }; +}); + +vi.mock("../lsp", () => ({ + getDefinitionsFromLsp: vi.fn(), +})); + +vi.mock("../recentlyEdited", () => ({ + RecentlyEditedTracker: class { + async getRecentlyEditedRanges() { + return []; + } + }, +})); + +vi.mock("../RecentlyVisitedRangesService", () => ({ + RecentlyVisitedRangesService: class { + getSnippets() { + return []; + } + }, +})); + +vi.mock("../activation/NextEditWindowManager", () => ({ + NextEditWindowManager: { + isInstantiated: vi.fn(() => false), + getInstance: vi.fn(), + }, +})); + +vi.mock("../../activation/JumpManager", () => { + let instance: any = null; + return { + JumpManager: { + getInstance: () => instance, + }, + __setMockJumpManagerInstance(value: any) { + instance = value; + }, + }; +}); + +vi.mock("core/nextEdit/NextEditPrefetchQueue", () => { + let instance: any = null; + return { + PrefetchQueue: { + getInstance: () => instance, + }, + __setMockPrefetchQueueInstance(value: any) { + instance = value; + }, + }; +}); + +vi.mock("core/nextEdit/NextEditProvider", () => { + let instance: any = null; + return { + NextEditProvider: { + initialize: vi.fn(() => instance), + getInstance: vi.fn(() => instance), + }, + __setMockNextEditProviderInstance(value: any) { + instance = value; + }, + }; +}); + +vi.mock("core/nextEdit/NextEditLoggingService", () => { + let instance: any = null; + return { + NextEditLoggingService: { + getInstance: () => instance, + }, + __setMockNextEditLoggingServiceInstance(value: any) { + instance = value; + }, + }; +}); + +vi.mock("core/nextEdit/diff/diff", () => ({ + checkFim: vi.fn(() => ({ isFim: true, fimText: "ghost" })), +})); + +vi.mock("../util/errorHandling", () => ({ + handleLLMError: vi.fn(async () => false), +})); diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d9901a3d0..30b48220f 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -330,10 +330,25 @@ export class ContinueCompletionProvider // Determine why this method was triggered. const isJumping = this.jumpManager.isJumpInProgress(); - const chainExists = this.nextEditProvider.chainExists(); + let chainExists = this.nextEditProvider.chainExists(); + const processedCount = this.prefetchQueue.processedCount; + const unprocessedCount = this.prefetchQueue.unprocessedCount; console.log("isJumping:", isJumping, "/ chainExists:", chainExists); this.prefetchQueue.peekThreeProcessed(); + let resetChainInFullFileDiff = false; + if ( + chainExists && + this.usingFullFileDiff && + processedCount === 0 && + unprocessedCount === 0 + ) { + // Skipping jump logic due to empty queues while using full file diff + await this.nextEditProvider.deleteChain(); + chainExists = false; + resetChainInFullFileDiff = true; + } + if (isJumping && chainExists) { // Case 2: Jumping (chain exists, jump was taken) console.log("trigger reason: jumping"); @@ -421,6 +436,7 @@ export class ContinueCompletionProvider } } else { // Case 1: Typing (chain does not exist). + // if resetChainInFullFileDiff is true then we are Rebuilding next edit chain after clearing empty queues in full file diff mode this.nextEditProvider.startChain(); const input: AutocompleteInput = { @@ -439,6 +455,15 @@ export class ContinueCompletionProvider { withChain: false, usingFullFileDiff: this.usingFullFileDiff }, ); + if ( + resetChainInFullFileDiff && + (!outcome || + (!outcome.completion && outcome.diffLines.length === 0)) + ) { + // No next edit outcome after resetting chain; returning null + return null; + } + // Start prefetching next edits if not using full file diff. // NOTE: this is better off not awaited. fire and forget. if (!this.usingFullFileDiff) { From 1a61e5a95bb77aecd28ba033396fb036b35b6fca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 09:09:44 +0000 Subject: [PATCH 15/20] build(deps): bump continuedev/continue Bumps [continuedev/continue](https://github.com/continuedev/continue) from e3ed0b6218e5d339e2fb265d06a267e98e7c7585 to 12e933bf9d13736c5f47728c436445ef4127fd52. - [Release notes](https://github.com/continuedev/continue/releases) - [Commits](https://github.com/continuedev/continue/compare/e3ed0b6218e5d339e2fb265d06a267e98e7c7585...12e933bf9d13736c5f47728c436445ef4127fd52) --- updated-dependencies: - dependency-name: continuedev/continue dependency-version: 12e933bf9d13736c5f47728c436445ef4127fd52 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- .github/workflows/continue-detailed-review.yaml | 2 +- .github/workflows/continue-general-review.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml index 45154075c..e7b095e87 100644 --- a/.github/workflows/continue-detailed-review.yaml +++ b/.github/workflows/continue-detailed-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Detailed PR Review - uses: continuedev/continue/actions/detailed-review@e3ed0b6218e5d339e2fb265d06a267e98e7c7585 + uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52 with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: continuedev diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 299797379..0fabfdf05 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Continue PR Review Action - uses: continuedev/continue/actions/general-review@e3ed0b6218e5d339e2fb265d06a267e98e7c7585 + uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52 with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" From c19aab8350f4b184dbdb65415ed1d3ec85ee0a5d Mon Sep 17 00:00:00 2001 From: Ting-Wai <40179554+tingwai@users.noreply.github.com> Date: Fri, 19 Sep 2025 11:01:46 -0700 Subject: [PATCH 16/20] fix: pastes for Terminal and Ghostty (#7821) * fix: pastes timing for Terminal and Ghostty * update tests --- extensions/cli/src/ui/TextBuffer.test.ts | 418 ++++++++++++----------- extensions/cli/src/ui/TextBuffer.ts | 18 +- 2 files changed, 234 insertions(+), 202 deletions(-) diff --git a/extensions/cli/src/ui/TextBuffer.test.ts b/extensions/cli/src/ui/TextBuffer.test.ts index 27ae83f61..4d88015af 100644 --- a/extensions/cli/src/ui/TextBuffer.test.ts +++ b/extensions/cli/src/ui/TextBuffer.test.ts @@ -1,7 +1,7 @@ import { - TextBuffer, COLLAPSE_SIZE, RAPID_INPUT_THRESHOLD, + TextBuffer, } from "./TextBuffer.js"; describe("TextBuffer", () => { @@ -313,231 +313,255 @@ describe("TextBuffer", () => { }); }); - describe("paste collapse", () => { - it("should not collapse short pasted text", () => { - const shortText = "hello world"; - buffer.handleInput(shortText, { ctrl: false, meta: false } as any); + describe("paste detection and collapse", () => { + describe("basic collapse behavior", () => { + it("should not collapse short content", () => { + const shortText = "hello world"; + buffer.handleInput(shortText, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe("hello world"); + }); - expect(buffer.text).toBe("hello world"); + it("should collapse content exceeding threshold", () => { + const longText = "a".repeat(COLLAPSE_SIZE + 1); + buffer.handleInput(longText, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + expect(buffer.text).toBe("[Paste #1]"); + }); + + it("should count lines correctly in placeholders", () => { + const multiLineText = + "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE); + buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + expect(buffer.text).toBe("[Paste #1, 4 lines]"); + }); }); - it("should collapse long pasted text exceeding collapse threshold", () => { - const longText = "a".repeat(COLLAPSE_SIZE + 1); - buffer.handleInput(longText, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); + describe("expansion and state management", () => { + it("should expand collapsed content on demand", () => { + const longText = "content " + "a".repeat(COLLAPSE_SIZE); + buffer.handleInput(longText, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + + expect(buffer.text).toBe("[Paste #1]"); + buffer.expandAllPasteBlocks(); + expect(buffer.text).toBe(longText); + }); + + it("should increment paste counter for multiple pastes", () => { + const text1 = "a".repeat(COLLAPSE_SIZE + 1); + const text2 = "b".repeat(COLLAPSE_SIZE + 1); + + buffer.handleInput(text1, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + buffer.insertText(" "); + buffer.handleInput(text2, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + + expect(buffer.text).toBe("[Paste #1] [Paste #2]"); + }); + + it("should normalize line endings when expanding", () => { + const textWithMixedEndings = + "line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE); + buffer.handleInput(textWithMixedEndings, { + ctrl: false, + meta: false, + } as any); + buffer.flushPendingInput(); + + buffer.expandAllPasteBlocks(); + const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE); + expect(buffer.text).toBe(expected); + }); + + it("should clear paste map after expansion", () => { + const longText = "a".repeat(COLLAPSE_SIZE + 1); + buffer.handleInput(longText, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + + buffer.expandAllPasteBlocks(); + buffer.expandAllPasteBlocks(); // Second call should be no-op + expect(buffer.text).toBe(longText); + }); + }); + + describe("rapid input detection (Terminal.app/Ghostty)", () => { + it("should detect large single input as rapid paste", () => { + const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1); + buffer.handleInput(rapidText, { ctrl: false, meta: false } as any); + + expect(buffer.text).toBe(""); // Should be buffered + expect(buffer.isInRapidInputMode()).toBe(true); + + buffer.flushPendingInput(); + expect(buffer.text).toBe(rapidText); // < COLLAPSE_SIZE, so not collapsed + }); + + it("should combine multiple chunks into single paste", () => { + const chunk1 = "a".repeat(200); + const chunk2 = "b".repeat(700); // Combined > COLLAPSE_SIZE + + buffer.handleInput(chunk1, { ctrl: false, meta: false } as any); + buffer.handleInput(chunk2, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + + expect(buffer.text).toBe("[Paste #1]"); + buffer.expandAllPasteBlocks(); + expect(buffer.text).toBe(chunk1 + chunk2); + }); + + it("should detect 50+ char chunks as start of paste session", () => { + const smallChunk = "x".repeat(60); // >= 50, should trigger + const largeChunk = "y".repeat(800); + + buffer.handleInput(smallChunk, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe(""); + + buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); + buffer.flushPendingInput(); + + expect(buffer.text).toBe("[Paste #1]"); + buffer.expandAllPasteBlocks(); + expect(buffer.text).toBe(smallChunk + largeChunk); + }); + }); + + describe("bracketed paste (iTerm2)", () => { + it("should handle bracketed paste sequences", () => { + const content = "function test() { return 'hello'; }" + "x".repeat(800); + + buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any); + expect(buffer.isInPasteMode()).toBe(true); + expect(buffer.text).toBe(""); + + buffer.handleInput(content, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe(""); // Nothing visible during paste + + buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any); + expect(buffer.isInPasteMode()).toBe(false); + expect(buffer.text).toBe("[Paste #1]"); + + buffer.expandAllPasteBlocks(); + expect(buffer.text).toBe(content); + }); + + it("should not collapse short bracketed content", () => { + const shortContent = "Hello world!"; + + buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any); + buffer.handleInput(shortContent, { ctrl: false, meta: false } as any); + buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any); + + expect(buffer.text).toBe(shortContent); + }); + + it("should prioritize bracketed paste over rapid input", () => { + const largeContent = "x".repeat(1000); + + buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any); + buffer.handleInput(largeContent, { ctrl: false, meta: false } as any); + + expect(buffer.isInPasteMode()).toBe(true); + expect(buffer.isInRapidInputMode()).toBe(false); + + buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any); + expect(buffer.text).toBe("[Paste #1]"); + }); + }); + }); + + describe("timing behavior", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("should combine chunks within 200ms timing window", () => { + const chunk1 = "x".repeat(100); + const chunk2 = "y".repeat(800); + + buffer.handleInput(chunk1, { ctrl: false, meta: false } as any); + + vi.advanceTimersByTime(100); // Within 200ms window + buffer.handleInput(chunk2, { ctrl: false, meta: false } as any); + + vi.advanceTimersByTime(250); // Finalize expect(buffer.text).toBe("[Paste #1]"); - }); - - it("should count lines correctly in collapsed text", () => { - const multiLineText = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE); - buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); - - expect(buffer.text).toBe("[Paste #1, 4 lines]"); - }); - - it("should expand collapsed content on expandAllPasteBlocks", () => { - const longText = "hello " + "a".repeat(COLLAPSE_SIZE); - buffer.handleInput(longText, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); - - // Verify it was collapsed - expect(buffer.text).toBe("[Paste #1]"); - - // Expand it buffer.expandAllPasteBlocks(); - - // Verify it was expanded with normalized line endings - expect(buffer.text).toBe(longText); + expect(buffer.text).toBe(chunk1 + chunk2); }); - it("should handle typing before and after collapsed content", () => { - buffer.setText("before "); - buffer.setCursor(7); + it("should finalize buffered content after 200ms timeout", () => { + const chunk = "x".repeat(100); + + buffer.handleInput(chunk, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe(""); + + vi.advanceTimersByTime(250); + expect(buffer.text).toBe(chunk); + }); + + it("should separate sessions when timing window expires", () => { + const chunk1 = "a".repeat(60); + const chunk2 = "b".repeat(900); + + buffer.handleInput(chunk1, { ctrl: false, meta: false } as any); + vi.advanceTimersByTime(300); // Exceed timing window + expect(buffer.text).toBe(chunk1); + + buffer.handleInput(chunk2, { ctrl: false, meta: false } as any); + vi.advanceTimersByTime(250); + expect(buffer.text).toBe(chunk1 + "[Paste #1]"); + }); + }); + + describe("regression tests", () => { + it("should prevent typing during paste accumulation (Terminal.app fix)", () => { + const largeChunk = "x".repeat(100); + buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); + + // Small typed input should not be mixed into paste + const typedChar = "a"; + buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe("a"); - const longText = "a".repeat(COLLAPSE_SIZE + 1); - buffer.handleInput(longText, { ctrl: false, meta: false } as any); buffer.flushPendingInput(); - - expect(buffer.text).toBe("before [Paste #1]"); - - // Type after collapsed content - buffer.insertText(" after"); - expect(buffer.text).toBe("before [Paste #1] after"); - - // Move cursor to beginning and type - buffer.setCursor(0); - buffer.insertText("start "); - expect(buffer.text).toBe("start before [Paste #1] after"); + expect(buffer.text).toBe("a" + largeChunk); }); - it("should handle exactly collapse threshold without collapsing", () => { - const exactText = "a".repeat(COLLAPSE_SIZE); // exactly at threshold - buffer.handleInput(exactText, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); // This will go into rapid input mode due to size - - expect(buffer.text).toBe(exactText); // Should not be collapsed - }); - - it("should handle paste operations as single large inputs", () => { - // This simulates the most common paste scenario: a single large input - const longText = "x".repeat(COLLAPSE_SIZE + 1); - - expect(longText.length).toBeGreaterThan(COLLAPSE_SIZE); - - buffer.handleInput(longText, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); - - // Should be collapsed - expect(buffer.text).toBe("[Paste #1]"); - }); - - it("should handle bracketed paste mode", () => { - // Simulate bracketed paste: start sequence, content, end sequence - - // Start paste mode - buffer.handleInput("\u001b[200~", {} as any); - expect(buffer.isInPasteMode()).toBe(true); - - // Add some content (in chunks like real paste) - const chunks = [ - "Hello ", - "world! ", - "This is a long piece of text. ".repeat(30), - ]; - const totalContent = chunks.join(""); + it("should preserve all chunks when expanding (content loss fix)", () => { + const chunks = ["a".repeat(1000), "b".repeat(1000), "c".repeat(1000)]; chunks.forEach((chunk) => { buffer.handleInput(chunk, { ctrl: false, meta: false } as any); }); - - // Text should NOT be visible during paste mode (to avoid visual bugs) - expect(buffer.text).toBe(""); - - // End paste mode - buffer.handleInput("\u001b[201~", {} as any); - expect(buffer.isInPasteMode()).toBe(false); - - // Now should be collapsed if > COLLAPSE_SIZE - if (totalContent.length > COLLAPSE_SIZE) { - expect(buffer.text).toBe("[Paste #1]"); - } - }); - - it("should not collapse short bracketed paste content", () => { - // Start paste mode - buffer.handleInput("\u001b[200~", {} as any); - - // Add short content - const shortContent = "Hello world!"; - buffer.handleInput(shortContent, { ctrl: false, meta: false } as any); - - // End paste mode - buffer.handleInput("\u001b[201~", {} as any); - - // Should not be collapsed - expect(buffer.text).toBe(shortContent); - }); - - it("should normalize line endings when expanding", () => { - const textWithCarriageReturns = - "line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE); - buffer.handleInput(textWithCarriageReturns, { - ctrl: false, - meta: false, - } as any); buffer.flushPendingInput(); - expect(buffer.text).toBe("[Paste #1, 4 lines]"); - - buffer.expandAllPasteBlocks(); - - // Should have normalized line endings - const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE); - expect(buffer.text).toBe(expected); - }); - - it("should increment paste counter for multiple pastes", () => { - const longText1 = "a".repeat(COLLAPSE_SIZE + 1); - const longText2 = "b".repeat(COLLAPSE_SIZE + 1); - - buffer.handleInput(longText1, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); expect(buffer.text).toBe("[Paste #1]"); - buffer.insertText(" "); - buffer.handleInput(longText2, { ctrl: false, meta: false } as any); - buffer.flushPendingInput(); - expect(buffer.text).toBe("[Paste #1] [Paste #2]"); - }); - - it("should detect rapid input above threshold", () => { - // Test that input above RAPID_INPUT_THRESHOLD triggers rapid input detection - const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1); - buffer.handleInput(rapidText, { ctrl: false, meta: false } as any); - - // Should go into rapid input buffer (not displayed yet) - expect(buffer.text).toBe(""); - expect(buffer.isInRapidInputMode()).toBe(true); - - // Flush to finalize - buffer.flushPendingInput(); - - // Now should be displayed (but not collapsed since < COLLAPSE_SIZE) - expect(buffer.text).toBe(rapidText); - }); - - it("should combine split paste chunks", () => { - // Simulate macOS Terminal splitting paste - const firstChunk = "a".repeat(COLLAPSE_SIZE + 200); // Large first chunk - buffer.handleInput(firstChunk, { ctrl: false, meta: false } as any); - - // First chunk goes into rapid input mode - no placeholder yet - expect(buffer.text).toBe(""); - - // Second chunk should be combined with the first (needs to be > 50 chars) - const secondChunk = "b".repeat(100); // Large enough to trigger split paste detection - buffer.handleInput(secondChunk, { ctrl: false, meta: false } as any); - - // Flush to finalize the rapid input synchronously - buffer.flushPendingInput(); - - // Should show only one placeholder with combined content - expect(buffer.text).toBe("[Paste #1]"); - - // Verify the combined content is stored correctly buffer.expandAllPasteBlocks(); - const expectedContent = firstChunk + secondChunk; - expect(buffer.text).toBe(expectedContent); + expect(buffer.text).toBe(chunks.join("")); + expect(buffer.text.length).toBe(3000); }); - it("should expand paste blocks on submission (simulating Enter key behavior)", () => { - // Add some text before the paste - buffer.insertText("Command: "); + it("should handle complete paste-to-submit workflow", () => { + const pastedCode = 'console.log("test");' + "x".repeat(800); - // Add a large paste that gets collapsed - const pastedCode = - 'function example() {\n console.log("hello");\n ' + - "x".repeat(COLLAPSE_SIZE); buffer.handleInput(pastedCode, { ctrl: false, meta: false } as any); buffer.flushPendingInput(); + expect(buffer.text).toBe("[Paste #1]"); - // Verify it's collapsed - expect(buffer.text).toBe("Command: [Paste #1, 3 lines]"); - - // Simulate what happens when user presses Enter - UserInput calls expandAllPasteBlocks() + // Simulate Enter key - expand before submission buffer.expandAllPasteBlocks(); + expect(buffer.text).toBe(pastedCode); - // Should now show the full content with normalized line endings - const expectedFullText = - 'Command: function example() {\n console.log("hello");\n ' + - "x".repeat(COLLAPSE_SIZE); - expect(buffer.text).toBe(expectedFullText); - - // Verify paste map is cleared after expansion - buffer.expandAllPasteBlocks(); // Should be no-op now - expect(buffer.text).toBe(expectedFullText); // Should remain the same + buffer.clear(); + expect(buffer.text).toBe(""); }); }); diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index 25723ae8f..103b48571 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -305,7 +305,13 @@ export class TextBuffer { const timeSinceLastInput = now - this._lastInputTime; // If we're already in rapid input mode and this comes quickly, add to buffer - if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 100) { + // But only if it's a reasonably large chunk - small inputs are likely typing, not paste + // This prevents typed characters from being mixed into paste content during accumulation + if ( + this._rapidInputBuffer.length > 0 && + timeSinceLastInput < 200 && + input.length >= 50 + ) { this._rapidInputBuffer += input; this._lastInputTime = now; @@ -323,8 +329,11 @@ export class TextBuffer { // Fallback paste detection: some terminals send large pastes as rapid chunks // instead of using bracketed paste mode. We detect this by timing between inputs. - // Only trigger for actually large chunks to avoid interfering with normal typing - if (input.length > RAPID_INPUT_THRESHOLD) { + // The >= 50 char threshold was restored to detect Terminal.app/Ghostty split pastes + if ( + input.length > RAPID_INPUT_THRESHOLD || + (input.length >= 50 && this._rapidInputBuffer.length === 0) + ) { this._rapidInputStartPos = this._cursor; // Accumulate chunks without inserting to avoid visual flicker @@ -511,8 +520,7 @@ export class TextBuffer { } // Fallback: detect chunked paste operations - // Don't trigger rapid input detection for small inputs (e.g. single characters like "/" or "@") - if (input.length > 50 && this.handleRapidInput(input)) { + if (this.handleRapidInput(input)) { return true; } From 507cdfc61a1c76c714b7ddd33017008dd42cb4ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20B=C5=82ach?= Date: Fri, 19 Sep 2025 21:54:25 +0200 Subject: [PATCH 17/20] test: use intellij-ide-starter for e2e tests (#7690) * test: use intellij-ide-starter for e2e tests Solves CON-3723 Extra / details: * Update the CI and docs accordingly * Remove robot dependencies and remove the custom runIdeForUiTests task. The IDE startup is now automatic/per test (+ instance can be reused if we want). * A new DSL for E2E tests means we no longer need to add "wait" everywhere, because each closure opening ensures that the window is ready to use. As a result, the tests are slightly faster. The only exception is waiting for inline completion. * The testing task now depends on prepareSandbox, because an E2E test requires specifying where the plugin can be copied from (hence this dependency, since we need to make sure these files exist, see: CONTINUE_PLUGIN_DIR). * The test framework is specified in a different version than the platform version, because older versions don't have the required drivers (241 vs 243). * fix: add testIntegration * fix: fix warning in build script * fix: remove invalid run config --- .../actions/run-jetbrains-tests/action.yml | 18 +-- extensions/intellij/.gitignore | 4 +- extensions/intellij/.run/Run Test IDE.run.xml | 26 ---- .../intellij/.run/Run e2e tests.run.xml | 7 - extensions/intellij/CONTRIBUTING.md | 58 ++------ extensions/intellij/build.gradle.kts | 70 ++++----- .../e2e/Autocomplete.kt | 75 ---------- .../continueintellijextension/e2e/GUI.kt | 96 ------------ .../e2e/InlineEdit.kt | 96 ------------ .../e2e/Onboarding.kt | 85 ----------- .../fixtures/DialogFixture.kt | 36 ----- .../fixtures/IdeaFrame.kt | 92 ------------ .../fixtures/WelcomeFrame.kt | 27 ---- .../utils/BrowserUtils.kt | 76 ---------- .../utils/RemoteRobotExtension.kt | 138 ------------------ .../utils/StepsLogger.kt | 19 --- .../continueintellijextension/Autocomplete.kt | 48 ++++++ .../test-continue/config.json | 0 18 files changed, 99 insertions(+), 872 deletions(-) delete mode 100644 extensions/intellij/.run/Run Test IDE.run.xml delete mode 100644 extensions/intellij/.run/Run e2e tests.run.xml delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/StepsLogger.kt create mode 100644 extensions/intellij/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/Autocomplete.kt rename extensions/intellij/src/{test/kotlin/com/github/continuedev/continueintellijextension/e2e => testIntegration/kotlin/com/github/continuedev/continueintellijextension}/test-continue/config.json (100%) diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index 77f6ceff3..03a9c7855 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -107,7 +107,7 @@ runs: cd binary npm run build - - name: Start test IDE + - name: Run tests shell: bash run: | cd extensions/intellij @@ -115,21 +115,7 @@ runs: Xvfb -ac :99 -screen 0 1920x1080x24 & sleep 10 mkdir -p build/reports - ./gradlew runIdeForUiTests & - - - name: Wait for JB connection - uses: jtalk/url-health-check-action@v3 - with: - url: http://127.0.0.1:8082 - max-attempts: 15 - retry-delay: 30s - - - name: Run tests - shell: bash - run: | - cd extensions/intellij - export DISPLAY=:99.0 - ./gradlew test + ./gradlew test testIntegration - name: Move video if: ${{ failure() }} diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index 147aaa022..9619f5d1f 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -5,5 +5,5 @@ src/main/resources/config_schema.json src/main/resources/continue_rc_schema.json video .intellijPlatform -src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/* -!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json \ No newline at end of file +src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/* +!src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/config.json \ No newline at end of file diff --git a/extensions/intellij/.run/Run Test IDE.run.xml b/extensions/intellij/.run/Run Test IDE.run.xml deleted file mode 100644 index 94ab5809f..000000000 --- a/extensions/intellij/.run/Run Test IDE.run.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - true - true - false - false - - - - \ No newline at end of file diff --git a/extensions/intellij/.run/Run e2e tests.run.xml b/extensions/intellij/.run/Run e2e tests.run.xml deleted file mode 100644 index 2280aece0..000000000 --- a/extensions/intellij/.run/Run e2e tests.run.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index fc1fdaa24..c9d05b502 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -179,55 +179,29 @@ This will generate a .zip file in `./build/distributions` with the version defin ## Testing -### e2e testing +Test commands: -#### Overview +- `./gradlew test` - to run **unit tests** +- `./gradlew testIntegration` - to run **e2e tests** -The e2e tests are written using [intellij-ui-test-robot](`https://github.com/JetBrains/intellij-ui-test-robot`). The -README for this project has a lot of helpful info on how to use the library. +### About e2e tests -Note that these tests fully take control of your mouse while executing. +The e2e tests are written using [intellij-ide-starter](https://github.com/JetBrains/intellij-ide-starter). +The first run of the e2e tests may take a while because the required IDE needs +to be downloaded. Note that these tests +fully take control of your mouse while executing. #### Setup If you are on macOS, you'll need to give IntelliJ permission to control your computer in order to run the e2e tests. -Open _System Settings_ and select `Privacy & Security` -> `Accessibility` and toggle the switch for IntelliJ. +Open `System Settings > Privacy & Security > Accessibility` and toggle the switch for IntelliJ. -#### Running the tests +#### Working with Intellij IDE Starter -Instantiate the test IDE as a background task: +The testing platform provides a rich DSL for most UI components in IntelliJ. However, if you want to interact with a +custom element, you can define your own XPath selector. -```sh -./gradlew clean runIdeForUiTests & -``` - -Once the IDE has loaded, you can run the tests. Note that you need to have the test IDE focused in order for the tests -to run. - -```sh -./gradlew test -``` - -Run a single test - -```sh -./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME" -``` - -#### Identifying selectors - -While the `runIdeForUiTests` task is running, you can visit the following URL -to view the UI hierarchy of the running IDE: - - - -#### Rebuilding the extension - -To rebuild the extension with the latest source code, run the following: - -```sh -./gradlew buildPlugin -``` - -This will update the contents of the extension that is loaded into the test IDE from -`build/idea-sandbox/plugins-uiTest/continue-intellij-extension` +To do this, run an e2e test and visit [localhost:63343/api/remote-driver/](http://localhost:63343/api/remote-driver/) to +view an HTML representation of the IDE's Swing component tree. +See [Integration Tests](https://plugins.jetbrains.com/docs/intellij/integration-tests-ui.html#searching-components) for +more details about this workflow. diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 7b7ed7c29..86231350f 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -1,17 +1,17 @@ import org.jetbrains.changelog.markdownToHTML import org.jetbrains.intellij.platform.gradle.TestFrameworkType import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask +import org.gradle.kotlin.dsl.intellijPlatform fun environment(key: String) = providers.environmentVariable(key) -val remoteRobotVersion = "0.11.23" val platformVersion: String by project val pluginGroup: String by project val pluginVersion: String by project val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap" plugins { - kotlin("jvm") version "1.9.22" + kotlin("jvm") version "2.1.0" id("org.jetbrains.intellij.platform") version "2.7.2" id("org.jetbrains.changelog") version "2.1.2" id("org.jetbrains.qodana") version "0.1.13" @@ -28,17 +28,28 @@ repositories { } } +sourceSets { + val testIntegration = create("testIntegration") + testIntegration.apply { + compileClasspath += sourceSets.main.get().output + runtimeClasspath += sourceSets.main.get().output + } +} + +val testIntegrationImplementation: Configuration by configurations.getting { + extendsFrom(configurations.testImplementation.get()) +} + dependencies { intellijPlatform { - create("IC", platformVersion) + intellijIdeaCommunity(platformVersion) plugins(listOf("org.jetbrains.plugins.terminal:241.14494.150")) testFramework(TestFrameworkType.Platform) + testFramework(TestFrameworkType.Starter, "243.21565.193", configurationName = "testIntegrationImplementation") } implementation("com.posthog.java:posthog:1.2.0") testImplementation("junit:junit:4.13.2") - testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion") - testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion") testImplementation("io.mockk:mockk:1.14.2") { // this transitive dependency (1.6.4) conflicts with built-in version (1.7.3) // otherwise e2e tests (runIdeForUiTests) will have linkage errors @@ -47,6 +58,10 @@ dependencies { testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0") testImplementation("com.automation-remarks:video-recorder-junit5:2.0") testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3 + + testIntegrationImplementation("org.junit.jupiter:junit-jupiter:5.7.1") + testIntegrationImplementation("org.kodein.di:kodein-di-jvm:7.20.2") + testIntegrationImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.10.1") } kotlin { @@ -88,40 +103,6 @@ qodana { showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) } -intellijPlatformTesting { - runIde { - // This task might not work locally because the binary tends to ignore CONTINUE_GLOBAL_DIR when a - // local Continue config is present. If you want to run the e2e tests locally, the most effective - // way is to temporarily disconnect from the network and run the tests again. - // todo: fix it properly - register("runIdeForUiTests") { - task { - environment( - "CONTINUE_GLOBAL_DIR", - "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue" - ) - jvmArgumentProviders += CommandLineArgumentProvider { - listOf( - "-Drobot-server.port=8082", - "-Dide.mac.message.dialogs.as.sheets=false", - "-Djb.privacy.policy.text=", - "-Djb.consents.confirmation.enabled=false", - "-Dide.mac.file.chooser.native=false", - "-DjbScreenMenuBar.enabled=false", - "-Dapple.laf.useScreenMenuBar=false", - "-Didea.trust.all.projects=true", - "-Dide.show.tips.on.startup.default.value=false", - "-Dide.browser.jcef.sandbox.enable=false" - ) - } - } - plugins { - robotServerPlugin() - } - } - } -} - tasks { withType { from("../../binary/bin") { @@ -146,6 +127,17 @@ tasks { test { useJUnitPlatform() + environment("CONTINUE_GLOBAL_DIR", "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/test-continue") jvmArgumentProviders += CommandLineArgumentProvider { listOf("-Dide.browser.jcef.sandbox.enable=false") } } } + +val testIntegration = task("testIntegration") { + val integrationTestSourceSet = sourceSets.getByName("testIntegration") + testClassesDirs = integrationTestSourceSet.output.classesDirs + classpath = integrationTestSourceSet.runtimeClasspath + systemProperty("CONTINUE_PLUGIN_DIR", tasks.prepareSandbox.get().pluginDirectory.get().asFile) + environment("CONTINUE_GLOBAL_DIR", "${rootProject.projectDir}/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue") + useJUnitPlatform() + dependsOn(tasks.prepareSandbox) +} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt deleted file mode 100644 index 44171e581..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.github.continuedev.continueintellijextension.e2e - -import com.automation.remarks.junit5.Video -import com.github.continuedev.continueintellijextension.fixtures.dialog -import com.github.continuedev.continueintellijextension.fixtures.idea -import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame -import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension -import com.github.continuedev.continueintellijextension.utils.StepsLogger -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ComponentFixture -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.steps.CommonSteps -import com.intellij.remoterobot.utils.keyboard -import com.intellij.remoterobot.utils.waitFor -import com.intellij.remoterobot.utils.waitForIgnoringError -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import java.time.Duration.ofMinutes -import java.time.Duration.ofSeconds - -@ExtendWith(RemoteRobotExtension::class) -class Autocomplete { - init { - StepsLogger.init() - } - - @BeforeEach - fun waitForIde(remoteRobot: RemoteRobot) { - waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } - } - - @AfterEach - fun closeProject(remoteRobot: RemoteRobot) { - CommonSteps(remoteRobot).closeProject() - } - - @Test - @Video - fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { - welcomeFrame { - createNewProjectLink.click() - dialog("New Project") { - findText("Java").click() - checkBox("Add sample code").select() - button("Create").click() - } - } - - // Wait for the default "Main.java" tab to load - // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. - waitFor(ofSeconds(20)) { - findAll( - byXpath("//div[@visible_text='Main.java']") - ).isNotEmpty() - } - - idea { - with(textEditor()) { - val userMsg = "TEST_USER_MESSAGE_0" - editor.insertTextAtLine(0, 0, userMsg) - editor.clickOnOffset(userMsg.length) - - keyboard { - enterText(" ") - } - - waitFor(ofSeconds(20)) { - editor.hasText("TEST_LLM_RESPONSE_0") - } - } - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt deleted file mode 100644 index 44b205134..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Currently we can't test any actions in the GUI that involve clicks. - * See this open issue for details: https://github.com/JetBrains/intellij-ui-test-robot/issues/491 - */ -package com.github.continuedev.continueintellijextension.e2e - -import com.automation.remarks.junit5.Video -import com.github.continuedev.continueintellijextension.fixtures.* -import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension -import com.github.continuedev.continueintellijextension.utils.StepsLogger -import com.github.continuedev.continueintellijextension.utils.getMetaKey -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ComponentFixture -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.steps.CommonSteps -import com.intellij.remoterobot.stepsProcessing.step -import com.intellij.remoterobot.utils.keyboard -import com.intellij.remoterobot.utils.waitFor -import com.intellij.remoterobot.utils.waitForIgnoringError -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import java.awt.event.KeyEvent.* -import java.time.Duration.ofMinutes -import java.time.Duration.ofSeconds - -@ExtendWith(RemoteRobotExtension::class) -class GUI { - init { - StepsLogger.init() - } - - @BeforeEach - fun waitForIde(remoteRobot: RemoteRobot) { - waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } - } - - @AfterEach - fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() - - // @Test - @Video - fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { - welcomeFrame { - createNewProjectLink.click() - dialog("New Project") { - findText("Java").click() - checkBox("Add sample code").select() - button("Create").click() - } - } - - // Wait for the default "Main.java" tab to load - // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. - // If we don't wait for this, clicking on the GUI may fail because a popup displays - // while the `continue_tutorial.java` is loading. - waitFor(ofSeconds(20)) { - findAll( - byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") - ).isNotEmpty() - } - - idea { - step("Manually open the webview") { - // Manually open the webview - find(byXpath("//div[@text='Continue']"), ofSeconds((10))).click() - - waitFor(ofSeconds(10)) { - browser().isShowing - } - - // Arbitrary timeout due to a bug where the webview will refresh - // and clear the editor state on first load - Thread.sleep(5000) - } - - step("Verify we can highlight code and add to webview") { - val textToInsert = "Hello world!" - - with(textEditor()) { - editor.insertTextAtLine(0, 0, textToInsert) - editor.selectText(textToInsert) - - keyboard { - hotKey(getMetaKey(), VK_J) - } - } - - waitFor(ofSeconds(10)) { - browser().findElementByContainsText(textToInsert).html.isNotEmpty() - } - } - } - } -} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt deleted file mode 100644 index e668bd4b1..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt +++ /dev/null @@ -1,96 +0,0 @@ -package com.github.continuedev.continueintellijextension.e2e - -import com.automation.remarks.junit5.Video -import com.github.continuedev.continueintellijextension.fixtures.dialog -import com.github.continuedev.continueintellijextension.fixtures.idea -import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame -import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension -import com.github.continuedev.continueintellijextension.utils.StepsLogger -import com.github.continuedev.continueintellijextension.utils.* -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ComponentFixture -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.steps.CommonSteps -import com.intellij.remoterobot.utils.keyboard -import com.intellij.remoterobot.utils.waitFor -import com.intellij.remoterobot.utils.waitForIgnoringError -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Disabled -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import java.awt.event.KeyEvent.VK_I -import java.time.Duration.ofMinutes -import java.time.Duration.ofSeconds - -@ExtendWith(RemoteRobotExtension::class) -class InlineEdit { - init { - StepsLogger.init() - } - - @BeforeEach - fun waitForIde(remoteRobot: RemoteRobot) { - waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } - } - - @AfterEach - fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() - - @Test - @Disabled("Failing in CI, seems like the timeout just needs to be increased") - @Video - fun submitInlineEdit(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { - welcomeFrame { - createNewProjectLink.click() - dialog("New Project") { - findText("Java").click() - checkBox("Add sample code").select() - button("Create").click() - } - } - - // Wait for the default "Main.java" tab to load - // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. - waitFor(ofSeconds(20)) { - findAll( - byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") - ).isNotEmpty() - } - - idea { - with(textEditor()) { - val userMsg = "TEST_USER_MESSAGE_0" - editor.insertTextAtLine(0, 0, userMsg) - editor.selectText(userMsg) - - keyboard { - hotKey(getMetaKey(), VK_I) - } - - val textArea = find(byXpath("//div[@class='CustomTextArea']")) - textArea.hasText("Enter instructions...") - - val modelSelect = find(byXpath("//div[@class='JComboBox']")) - modelSelect.hasText("TEST LLM") - - keyboard { - enterText("Hello world!") - } - - val enterBtn = find(byXpath("//div[@class='CustomButton']")) - enterBtn.click() - - val rejectText = "${getAltKeyLabel()}${getShiftKeyLabel()}N" - val acceptText = "${getAltKeyLabel()}${getShiftKeyLabel()}Y" - val acceptAllText = "Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)" - val rejectAllText = "Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)" - - find(byXpath("//div[@text='$rejectText']")).isShowing - find(byXpath("//div[@text='$acceptText']")).isShowing - find(byXpath("//div[@text='$acceptAllText']")).isShowing - find(byXpath("//div[@text='$rejectAllText']")).isShowing - } - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt deleted file mode 100644 index 30306b7ba..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt +++ /dev/null @@ -1,85 +0,0 @@ -package com.github.continuedev.continueintellijextension.e2e - -import com.automation.remarks.junit5.Video -import com.github.continuedev.continueintellijextension.fixtures.dialog -import com.github.continuedev.continueintellijextension.fixtures.idea -import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame -import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension -import com.github.continuedev.continueintellijextension.utils.StepsLogger -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ComponentFixture -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.steps.CommonSteps -import com.intellij.remoterobot.stepsProcessing.step -import com.intellij.remoterobot.utils.waitFor -import com.intellij.remoterobot.utils.waitForIgnoringError -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import java.time.Duration.ofMinutes -import java.time.Duration.ofSeconds - -@ExtendWith(RemoteRobotExtension::class) -class Onboarding { - init { - StepsLogger.init() - } - - @BeforeEach - fun waitForIde(remoteRobot: RemoteRobot) { - waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } - } - - @AfterEach - fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() - - - // @Test - @Video - fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { - welcomeFrame { - createNewProjectLink.click() - dialog("New Project") { - findText("Java").click() - checkBox("Add sample code").select() - button("Create").click() - } - } - - idea { - // Wait for the default "Main.java" tab to load - // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. - // So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft" - waitFor(ofSeconds(20)) { - findAll( - byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") - ).isNotEmpty() - } - - // TODO: Need a good way to ensure this is the first test ran in the entire suite -// step("Verify Continue tutorial file is loaded") { -// find(byXpath("//div[@visible_text='continue_tutorial.java']")) -// } - - step("Manually open the webview") { - // Manually open the webview - find(byXpath("//div[@text='Continue']"), ofSeconds((10))).click() - - waitFor(ofSeconds(10)) { - browser().isShowing - } - } - - step("Verify the onboarding card is present") { - waitFor(ofSeconds(30)) { - try { - browser().findElement("//*[@data-testid='onboarding-card']").html.isNotEmpty() - } catch (e: Exception) { - false - } - } - } - } - } -} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt deleted file mode 100644 index d9643a96b..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.github.continuedev.continueintellijextension.fixtures - -/* - * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/DialogFixture.kt - */ -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.data.RemoteComponent -import com.intellij.remoterobot.fixtures.CommonContainerFixture -import com.intellij.remoterobot.fixtures.ContainerFixture -import com.intellij.remoterobot.fixtures.FixtureName -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.stepsProcessing.step -import java.time.Duration - -fun ContainerFixture.dialog( - title: String, - timeout: Duration = Duration.ofSeconds(30), - function: DialogFixture.() -> Unit = {} -): DialogFixture = step("Search for dialog with title $title") { - find(DialogFixture.byTitle(title), timeout).apply(function) -} - -@FixtureName("Dialog") -class DialogFixture( - remoteRobot: RemoteRobot, - remoteComponent: RemoteComponent -) : CommonContainerFixture(remoteRobot, remoteComponent) { - - companion object { - @JvmStatic - fun byTitle(title: String) = byXpath("title $title", "//div[@title='$title' and @class='MyDialog']") - } - - val title: String - get() = callJs("component.getTitle();") -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt deleted file mode 100644 index 141677c15..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.github.continuedev.continueintellijextension.fixtures - -/* - * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/IdeaFrame.kt - */ -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.data.RemoteComponent -import com.intellij.remoterobot.fixtures.* -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.stepsProcessing.step -import com.intellij.remoterobot.utils.waitFor -import java.time.Duration - -fun RemoteRobot.idea(function: IdeaFrame.() -> Unit) { - find(timeout = Duration.ofSeconds(10)).apply(function) -} - -@FixtureName("Idea frame") -@DefaultXpath("IdeFrameImpl type", "//div[@class='IdeFrameImpl']") -class IdeaFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) : - CommonContainerFixture(remoteRobot, remoteComponent) { - - val projectViewTree - get() = find(byXpath("ProjectViewTree", "//div[@class='ProjectViewTree']")) - - val projectName - get() = step("Get project name") { return@step callJs("component.getProject().getName()") } - - val menuBar: JMenuBarFixture - get() = step("Menu...") { - return@step remoteRobot.find(JMenuBarFixture::class.java, JMenuBarFixture.byType()) - } - - @JvmOverloads - fun dumbAware(timeout: Duration = Duration.ofMinutes(5), function: () -> Unit) { - step("Wait for smart mode") { - waitFor(duration = timeout, interval = Duration.ofSeconds(5)) { - runCatching { isDumbMode().not() }.getOrDefault(false) - } - function() - step("..wait for smart mode again") { - waitFor(duration = timeout, interval = Duration.ofSeconds(5)) { - isDumbMode().not() - } - } - } - } - - fun isDumbMode(): Boolean { - return callJs( - """ - const frameHelper = com.intellij.openapi.wm.impl.ProjectFrameHelper.getFrameHelper(component) - if (frameHelper) { - const project = frameHelper.getProject() - project ? com.intellij.openapi.project.DumbService.isDumb(project) : true - } else { - true - } - """, true - ) - } - - fun openFile(path: String) { - runJs( - """ - importPackage(com.intellij.openapi.fileEditor) - importPackage(com.intellij.openapi.vfs) - importPackage(com.intellij.openapi.wm.impl) - importClass(com.intellij.openapi.application.ApplicationManager) - - const path = '$path' - const frameHelper = ProjectFrameHelper.getFrameHelper(component) - if (frameHelper) { - const project = frameHelper.getProject() - const projectPath = project.getBasePath() - const file = LocalFileSystem.getInstance().findFileByPath(projectPath + '/' + path) - const openFileFunction = new Runnable({ - run: function() { - FileEditorManager.getInstance(project).openTextEditor( - new OpenFileDescriptor( - project, - file - ), true - ) - } - }) - ApplicationManager.getApplication().invokeLater(openFileFunction) - } - """, true - ) - } -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt deleted file mode 100644 index 70029fdaf..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.github.continuedev.continueintellijextension.fixtures - -/* - * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/WelcomeFrame.kt - */ -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.data.RemoteComponent -import com.intellij.remoterobot.fixtures.* -import com.intellij.remoterobot.search.locators.byXpath -import java.time.Duration - -fun RemoteRobot.welcomeFrame(function: WelcomeFrame.() -> Unit) { - find(WelcomeFrame::class.java, Duration.ofSeconds(20)).apply(function) -} - -@FixtureName("Welcome Frame") -@DefaultXpath("type", "//div[@class='FlatWelcomeFrame']") -class WelcomeFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) : - CommonContainerFixture(remoteRobot, remoteComponent) { - val createNewProjectLink - get() = actionLink( - byXpath( - "New Project", - "//div[(@class='MainButton' and @text='New Project') or (@accessiblename='New Project' and @class='JButton')]" - ) - ) -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt deleted file mode 100644 index 51868f031..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Notes: - * - `sendIntellijMessage` isn't working, but keeping this around as an example of how we might be able to implement - * - Below is an AI generated summary of what the problem might be based on troubleshooting attempts - * - For details, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/26714246086162--intellij-ui-test-robot-Error-when-attempting-to-click-on-DomElement-491 - * - * - * The issue is with how the JCefBrowserFixture.executeJsInBrowser method handles JavaScript code execution. - * When trying to call window.postIntellijMessage, we're encountering these challenges: - * - * 1. **Double Injection Problem**: The postIntellijMessage function already uses JBCefJSQuery.inject internally. - * When we try to call it through executeJsInBrowser, we're essentially trying to pass it through another injection - * mechanism, creating nested injections that break. - * - * 2. **String Escaping Issues**: The way quotes are being escaped between the layers of execution is causing syntax - * errors in the final JavaScript that gets executed. - * - * 3. **Context Isolation**: The executeJsInBrowser method likely runs in a different execution context than where the - * function was defined, causing scope/reference issues. - * - * The key insight is that we cannot directly call a function that itself uses the JBCefJSQuery bridge through the test - * framework's executeJsInBrowser method. These bridge functions are designed to be called directly in the browser - * context, not through another layer of script injection. - */ -package com.github.continuedev.continueintellijextension.utils - -import com.intellij.remoterobot.fixtures.JCefBrowserFixture - -/** - * Utility functions for interacting with browser components in tests - */ -object BrowserUtils { - - /** - * Sends a message to the webview using JCefBrowserFixture's executeJsInBrowser - * - * @param browser The JCefBrowserFixture to execute JavaScript in - * @param messageType The type of message to send - * @param messageData The data object to send as message payload - * @param messageId A unique ID for the message - */ - fun sendIntellijMessage( - browser: JCefBrowserFixture, - messageType: String, - messageData: Any, - messageId: String = "test-message-id" - ) { - // Convert the messageData to a JSON string - val dataJson = when (messageData) { - is String -> "\"$messageData\"" - else -> messageData.toString() - } - - val jsCode = """ - (function() { - window.postIntellijMessage( - "$messageType", - $dataJson, - "$messageId" - ); - return true; - })(); - """.trimIndent() - - browser.executeJsInBrowser(jsCode) - } -} - -// Extension function for JCefBrowserFixture for easier usage -fun JCefBrowserFixture.sendIntellijMessage( - messageType: String, - messageData: Any, - messageId: String = "test-message-id" -) { - BrowserUtils.sendIntellijMessage(this, messageType, messageData, messageId) -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt deleted file mode 100644 index 0ae25a389..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt +++ /dev/null @@ -1,138 +0,0 @@ -package com.github.continuedev.continueintellijextension.utils - -/** - * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/utils/RemoteRobotExtension.kt - */ -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ContainerFixture -import com.intellij.remoterobot.search.locators.byXpath -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.logging.HttpLoggingInterceptor -import org.junit.jupiter.api.extension.AfterTestExecutionCallback -import org.junit.jupiter.api.extension.ExtensionContext -import org.junit.jupiter.api.extension.ParameterContext -import org.junit.jupiter.api.extension.ParameterResolver -import java.awt.image.BufferedImage -import java.io.ByteArrayOutputStream -import java.io.File -import java.lang.IllegalStateException -import java.lang.reflect.Method -import javax.imageio.ImageIO - -class RemoteRobotExtension : AfterTestExecutionCallback, ParameterResolver { - private val url: String = System.getProperty("remote-robot-url") ?: "http://127.0.0.1:8082" - private val remoteRobot: RemoteRobot = if (System.getProperty("debug-retrofit")?.equals("enable") == true) { - val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { - this.level = HttpLoggingInterceptor.Level.BODY - } - val client = OkHttpClient.Builder().apply { - this.addInterceptor(interceptor) - }.build() - RemoteRobot(url, client) - } else { - RemoteRobot(url) - } - private val client = OkHttpClient() - - override fun supportsParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Boolean { - return parameterContext?.parameter?.type?.equals(RemoteRobot::class.java) ?: false - } - - override fun resolveParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Any { - return remoteRobot - } - - override fun afterTestExecution(context: ExtensionContext?) { - val testMethod: Method = context?.requiredTestMethod ?: throw IllegalStateException("test method is null") - val testMethodName = testMethod.name - val testFailed: Boolean = context.executionException?.isPresent ?: false - if (testFailed) { -// saveScreenshot(testMethodName) - saveIdeaFrames(testMethodName) - saveHierarchy(testMethodName) - } - } - - private fun saveScreenshot(testName: String) { - fetchScreenShot().save(testName) - } - - private fun saveHierarchy(testName: String) { - val hierarchySnapshot = - saveFile(url, "build/reports", "hierarchy-$testName.html") - if (File("build/reports/styles.css").exists().not()) { - saveFile("$url/styles.css", "build/reports", "styles.css") - } - println("Hierarchy snapshot: ${hierarchySnapshot.absolutePath}") - } - - private fun saveFile(url: String, folder: String, name: String): File { - val response = client.newCall(Request.Builder().url(url).build()).execute() - return File(folder).apply { - mkdirs() - }.resolve(name).apply { - writeText(response.body?.string() ?: "") - } - } - - private fun BufferedImage.save(name: String) { - val bytes = ByteArrayOutputStream().use { b -> - ImageIO.write(this, "png", b) - b.toByteArray() - } - File("build/reports").apply { mkdirs() }.resolve("$name.png").writeBytes(bytes) - } - - private fun saveIdeaFrames(testName: String) { - remoteRobot.findAll(byXpath("//div[@class='IdeFrameImpl']")).forEachIndexed { n, frame -> - val pic = try { - frame.callJs( - """ - importPackage(java.io) - importPackage(javax.imageio) - importPackage(java.awt.image) - const screenShot = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB); - component.paint(screenShot.getGraphics()) - let pictureBytes; - const baos = new ByteArrayOutputStream(); - try { - ImageIO.write(screenShot, "png", baos); - pictureBytes = baos.toByteArray(); - } finally { - baos.close(); - } - pictureBytes; - """, true - ) - } catch (e: Throwable) { - e.printStackTrace() - throw e - } - pic.inputStream().use { - ImageIO.read(it) - }.save(testName + "_" + n) - } - } - - private fun fetchScreenShot(): BufferedImage { - return remoteRobot.callJs( - """ - importPackage(java.io) - importPackage(javax.imageio) - const screenShot = new java.awt.Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); - let pictureBytes; - const baos = new ByteArrayOutputStream(); - try { - ImageIO.write(screenShot, "png", baos); - pictureBytes = baos.toByteArray(); - } finally { - baos.close(); - } - pictureBytes; - """ - ).inputStream().use { - ImageIO.read(it) - } - } -} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/StepsLogger.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/StepsLogger.kt deleted file mode 100644 index bf4c86214..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/StepsLogger.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.github.continuedev.continueintellijextension.utils - -/** - * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/utils/StepsLogger.kt - */ -import com.intellij.remoterobot.stepsProcessing.StepLogger -import com.intellij.remoterobot.stepsProcessing.StepWorker - -object StepsLogger { - private var initialized = false - - @JvmStatic - fun init() { - if (initialized.not()) { - StepWorker.registerProcessor(StepLogger()) - initialized = true - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/Autocomplete.kt b/extensions/intellij/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/Autocomplete.kt new file mode 100644 index 000000000..beca66839 --- /dev/null +++ b/extensions/intellij/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/Autocomplete.kt @@ -0,0 +1,48 @@ +package com.github.continuedev.continueintellijextension + +import com.automation.remarks.junit5.Video +import com.intellij.driver.sdk.ui.components.* +import com.intellij.driver.sdk.wait +import com.intellij.ide.starter.driver.engine.runIdeWithDriver +import com.intellij.ide.starter.ide.IdeProductProvider +import com.intellij.ide.starter.models.TestCase +import com.intellij.ide.starter.plugins.PluginConfigurator +import com.intellij.ide.starter.project.NoProject +import com.intellij.ide.starter.runner.Starter +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assertions.assertTrue +import java.io.File +import kotlin.time.Duration.Companion.seconds + +class Autocomplete { + + @Video + @Test + fun testAutocomplete() { + val starter = Starter.newContext("testExample", TestCase(IdeProductProvider.IC, NoProject).withVersion("2024.3")) + PluginConfigurator(starter).installPluginFromFolder(File(System.getProperty("CONTINUE_PLUGIN_DIR"))) + starter.runIdeWithDriver().useDriverAndCloseIde { + welcomeScreen { + createNewProjectButton.click() + button("Create").click() + } + ideFrame { + editorTabs { + clickTab("Main.java") + } + codeEditor { + keyboard { + enterText("TEST_USER_MESSAGE_0") + space() + } + wait(2.seconds) + keyboard { + tab() + } + assertTrue(text.contains("TEST_LLM_RESPONSE_0")) + } + } + } + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json b/extensions/intellij/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/config.json similarity index 100% rename from extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json rename to extensions/intellij/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/config.json From 059c901bdb19504d6a716a8e33b56d1442138727 Mon Sep 17 00:00:00 2001 From: Aditya Mitra <61635505+uinstinct@users.noreply.github.com> Date: Sat, 20 Sep 2025 01:27:14 +0530 Subject: [PATCH 18/20] style: skip toolcall status message for terminal tool (#7856) --- gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/index.tsx | 8 +++----- manual-testing-sandbox/loco | 1 + 3 files changed, 5 insertions(+), 6 deletions(-) create mode 160000 manual-testing-sandbox/loco diff --git a/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx b/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx index bb0cdd25c..d776ba6e4 100644 --- a/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx +++ b/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx @@ -420,7 +420,7 @@ export function UnifiedTerminalCommand({ return (
diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 40e5e8cd5..eb0397162 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,7 +1,4 @@ -import { - ArrowRightIcon, - MagnifyingGlassIcon, -} from "@heroicons/react/24/outline"; +import { ArrowRightIcon } from "@heroicons/react/24/outline"; import { ToolCallState } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { useState } from "react"; @@ -62,7 +59,8 @@ export function ToolCallDiv({ // But we'd need a nicer place to put the truncate button and the X icon when tool call fails if ( functionName === BuiltInToolNames.SingleFindAndReplace || - functionName === BuiltInToolNames.MultiEdit + functionName === BuiltInToolNames.MultiEdit || + functionName === BuiltInToolNames.RunTerminalCommand ) { return (
diff --git a/manual-testing-sandbox/loco b/manual-testing-sandbox/loco new file mode 160000 index 000000000..02fec6cd8 --- /dev/null +++ b/manual-testing-sandbox/loco @@ -0,0 +1 @@ +Subproject commit 02fec6cd89f89d5a0e7e471bd7a63bdb75b42e49 From 39efd1e5624c19c44ef5814e4c9d4c9b5cc072dd Mon Sep 17 00:00:00 2001 From: Ting-Wai <40179554+tingwai@users.noreply.github.com> Date: Fri, 19 Sep 2025 13:43:46 -0700 Subject: [PATCH 19/20] chore: default to org agent when onboarding (#7793) * chore: default to org agent when onboarding * tests * remove console logs --- extensions/cli/src/auth/orgSelection.test.ts | 233 +++++++++++++++++++ extensions/cli/src/auth/orgSelection.ts | 155 ++++++++++++ extensions/cli/src/auth/workos.helpers.ts | 42 +--- extensions/cli/src/auth/workos.ts | 33 ++- extensions/cli/src/commands/chat.ts | 7 +- extensions/cli/src/config.ts | 2 +- extensions/cli/src/configLoader.ts | 2 +- extensions/cli/src/onboarding.ts | 5 +- 8 files changed, 412 insertions(+), 67 deletions(-) create mode 100644 extensions/cli/src/auth/orgSelection.test.ts create mode 100644 extensions/cli/src/auth/orgSelection.ts diff --git a/extensions/cli/src/auth/orgSelection.test.ts b/extensions/cli/src/auth/orgSelection.test.ts new file mode 100644 index 000000000..838a20899 --- /dev/null +++ b/extensions/cli/src/auth/orgSelection.test.ts @@ -0,0 +1,233 @@ +import * as fs from "fs"; + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { + autoSelectOrganizationAndConfig, + createUpdatedAuthConfig, +} from "./orgSelection.js"; +import type { AuthenticatedConfig } from "./workos.js"; + +// Mock dependencies +vi.mock("fs"); +vi.mock("../config.js"); +vi.mock("../env.js"); +vi.mock("./workos.js"); + +const mockApiClient = { + listOrganizations: vi.fn(), + listAssistants: vi.fn(), +} as any; // Mock API client for testing + +describe("orgSelection", () => { + const mockConfig: AuthenticatedConfig = { + userId: "user123", + userEmail: "user@example.com", + accessToken: "token123", + refreshToken: "refresh123", + expiresAt: Date.now() + 3600000, + organizationId: undefined, + configUri: undefined, + modelName: undefined, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Mock modules using vi.mocked + const configMod = await import("../config.js"); + const envMod = await import("../env.js"); + const workosMod = await import("./workos.js"); + + vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient); + vi.mocked(envMod.env).continueHome = "/mock/home"; + vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {}); + + // Default: no local config + vi.mocked(fs.existsSync).mockReturnValue(false); + }); + + describe("createUpdatedAuthConfig", () => { + it("should update organization ID", () => { + const result = createUpdatedAuthConfig(mockConfig, "org123"); + expect(result.organizationId).toBe("org123"); + }); + + it("should update organization ID and config URI", () => { + const result = createUpdatedAuthConfig( + mockConfig, + "org123", + "slug://owner/assistant", + ); + expect(result.organizationId).toBe("org123"); + expect(result!.configUri).toBe("slug://owner/assistant"); + }); + + it("should set personal organization", () => { + const result = createUpdatedAuthConfig(mockConfig, null); + expect(result.organizationId).toBe(null); + }); + }); + + describe("autoSelectOrganizationAndConfig scenarios", () => { + it("Priority 1: Org with assistants → select first assistant", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [ + { id: "org1", name: "Org 1" }, + { id: "org2", name: "Org 2" }, + ], + }); + + // Mock API calls in order: org1 assistants, org2 assistants + mockApiClient.listAssistants.mockImplementation( + ({ organizationId }: { organizationId?: string }) => { + if (organizationId === "org1") return Promise.resolve([]); + if (organizationId === "org2") + return Promise.resolve([ + { ownerSlug: "owner", packageSlug: "assistant1" }, + ]); + return Promise.resolve([]); + }, + ); + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe("org2"); + expect(result!.configUri).toBe("slug://owner/assistant1"); + }); + + it("Priority 2: No org assistants → personal assistants exist", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [{ id: "org1", name: "Org 1" }], + }); + + mockApiClient.listAssistants.mockImplementation( + ({ organizationId }: { organizationId?: string }) => { + if (organizationId === "org1") return Promise.resolve([]); + if (organizationId === undefined) + return Promise.resolve([ + { ownerSlug: "personal", packageSlug: "my-assistant" }, + ]); + return Promise.resolve([]); + }, + ); + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe(null); // personal org + expect(result!.configUri).toBe("slug://personal/my-assistant"); + expect(mockApiClient.listAssistants).toHaveBeenCalledWith({ + organizationId: undefined, + }); + }); + + it("Priority 3: No assistants anywhere → local config.yaml exists", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [{ id: "org1", name: "Org 1" }], + }); + + mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere + vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe(null); + expect(result!.configUri).toContain("config.yaml"); + }); + + it("Priority 4: No assistants, no config.yaml → fallback", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [{ id: "org1", name: "Org 1" }], + }); + + mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere + vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe(null); + expect(result!.configUri).toBeUndefined(); + }); + + it("Multiple orgs with assistants → pick first one", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [ + { id: "org1", name: "Org 1" }, + { id: "org2", name: "Org 2" }, + ], + }); + + mockApiClient.listAssistants.mockImplementation( + ({ organizationId }: { organizationId?: string }) => { + if (organizationId === "org1") + return Promise.resolve([ + { ownerSlug: "owner1", packageSlug: "assistant1" }, + ]); + if (organizationId === "org2") + return Promise.resolve([ + { ownerSlug: "owner2", packageSlug: "assistant2" }, + ]); + return Promise.resolve([]); + }, + ); + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe("org1"); // First org wins + expect(result!.configUri).toBe("slug://owner1/assistant1"); + }); + + it("Personal assistants API fails → fallback to config.yaml", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [{ id: "org1", name: "Org 1" }], + }); + + mockApiClient.listAssistants + .mockResolvedValueOnce([]) // org1: no assistants + .mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error + + vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe(null); + expect(result!.configUri).toContain("config.yaml"); + }); + + it("Empty organizations list → check personal assistants", async () => { + mockApiClient.listOrganizations.mockResolvedValue({ + organizations: [], // No orgs + }); + + mockApiClient.listAssistants.mockResolvedValue([ + { ownerSlug: "personal", packageSlug: "my-assistant" }, + ]); + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe(null); + expect(result!.configUri).toBe("slug://personal/my-assistant"); + }); + + it("API error → fallback with error message", async () => { + mockApiClient.listOrganizations.mockRejectedValue( + new Error("Network error"), + ); + + const consoleSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const result = await autoSelectOrganizationAndConfig(mockConfig); + + expect(result!.organizationId).toBe(null); + expect(result!.configUri).toBeUndefined(); + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("Error fetching organizations:"), + "Network error", + ); + + consoleSpy.mockRestore(); + }); + }); +}); diff --git a/extensions/cli/src/auth/orgSelection.ts b/extensions/cli/src/auth/orgSelection.ts new file mode 100644 index 000000000..e82bea8ae --- /dev/null +++ b/extensions/cli/src/auth/orgSelection.ts @@ -0,0 +1,155 @@ +import * as fs from "fs"; +import * as path from "path"; + +import chalk from "chalk"; + +import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js"; +import { saveAuthConfig } from "../auth/workos.js"; +import { getApiClient } from "../config.js"; +import { env } from "../env.js"; + +/** + * Creates an updated AuthenticatedConfig with a new organization ID and optional config URI + */ +export function createUpdatedAuthConfig( + config: AuthenticatedConfig, + organizationId: string | null | undefined, + configUri?: string | null, +): AuthenticatedConfig { + return { + userId: config.userId, + userEmail: config.userEmail, + accessToken: config.accessToken, + refreshToken: config.refreshToken, + expiresAt: config.expiresAt, + organizationId, + configUri: configUri ?? config.configUri, + modelName: config.modelName, + }; +} + +/** + * Check if an organization has available assistants + */ +async function hasOrgAssistants( + apiClient: ReturnType, + organizationId: string, +): Promise { + try { + const assistants = await apiClient.listAssistants({ organizationId }); + return assistants.length > 0; + } catch { + // If we can't check, assume no assistants + return false; + } +} + +/** + * Get the first available assistant from an organization + */ +async function getFirstAssistant( + apiClient: ReturnType, + organizationId: string, +): Promise { + try { + const assistants = await apiClient.listAssistants({ organizationId }); + if (assistants.length > 0) { + const first = assistants[0]; + return `${first.ownerSlug}/${first.packageSlug}`; + } + return null; + } catch { + return null; + } +} + +/** + * Check if personal local config.yaml exists + */ +function hasPersonalLocalConfig(): boolean { + const defaultConfigPath = path.join(env.continueHome, "config.yaml"); + return fs.existsSync(defaultConfigPath); +} + +/** + * Automatically select organization and configuration for authenticated config + * Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback + */ +export async function autoSelectOrganizationAndConfig( + authenticatedConfig: AuthenticatedConfig, +): Promise { + const apiClient = getApiClient(authenticatedConfig.accessToken); + + try { + const resp = await apiClient.listOrganizations(); + const organizations = resp.organizations; + + // Priority 1: Find any organization that has assistants - use first assistant + for (const org of organizations) { + const hasAssistants = await hasOrgAssistants(apiClient, org.id); + if (hasAssistants) { + // Get the first assistant from this org + const firstAssistantSlug = await getFirstAssistant(apiClient, org.id); + const configUri = firstAssistantSlug + ? `slug://${firstAssistantSlug}` + : undefined; + + const updatedConfig = createUpdatedAuthConfig( + authenticatedConfig, + org.id, + configUri, + ); + saveAuthConfig(updatedConfig); + return updatedConfig; + } + } + + // Priority 2: Check if personal organization has assistants + try { + const personalAssistants = await apiClient.listAssistants({ + organizationId: undefined, + }); + if (personalAssistants.length > 0) { + const firstAssistant = personalAssistants[0]; + const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`; + const configUri = `slug://${firstAssistantSlug}`; + + const updatedConfig = createUpdatedAuthConfig( + authenticatedConfig, + null, + configUri, + ); + saveAuthConfig(updatedConfig); + console.log(chalk.green("✓ Automatically selected personal assistant")); + return updatedConfig; + } + } catch { + // If personal assistants can't be fetched, continue to next priority + } + + // Priority 3: If no assistants anywhere, use local config.yaml + if (hasPersonalLocalConfig()) { + const updatedConfig = createUpdatedAuthConfig( + authenticatedConfig, + null, + `file://${path.join(env.continueHome, "config.yaml")}`, + ); + saveAuthConfig(updatedConfig); + console.log(chalk.green("✓ Using local config.yaml")); + return updatedConfig; + } + + // no org assistants or config.yaml + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); + saveAuthConfig(updatedConfig); + return updatedConfig; + } catch (error: any) { + console.error( + chalk.red("Error fetching organizations:"), + error.response?.data?.message || error.message || error, + ); + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); + saveAuthConfig(updatedConfig); + return updatedConfig; + } +} diff --git a/extensions/cli/src/auth/workos.helpers.ts b/extensions/cli/src/auth/workos.helpers.ts index 8e33b5127..cc4690cdf 100644 --- a/extensions/cli/src/auth/workos.helpers.ts +++ b/extensions/cli/src/auth/workos.helpers.ts @@ -16,7 +16,7 @@ import { saveAuthConfig } from "./workos.js"; */ export function createUpdatedAuthConfig( config: AuthenticatedConfig, - organizationId: string | null, + organizationId: string | null | undefined, ): AuthenticatedConfig { return { userId: config.userId, @@ -124,43 +124,3 @@ export async function handleCliOrgForAuthenticatedConfig( saveAuthConfig(updatedConfig); return updatedConfig; } - -/** - * Automatically select organization for authenticated config - */ -export async function autoSelectOrganization( - authenticatedConfig: AuthenticatedConfig, -): Promise { - const apiClient = getApiClient(authenticatedConfig.accessToken); - - try { - const resp = await apiClient.listOrganizations(); - const organizations = resp.organizations; - - if (organizations.length === 0) { - const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); - saveAuthConfig(updatedConfig); - return updatedConfig; - } - - // Automatically select the first organization if available - const selectedOrg = organizations[0]; - const selectedOrgId = selectedOrg.id; - - const updatedConfig = createUpdatedAuthConfig( - authenticatedConfig, - selectedOrgId, - ); - saveAuthConfig(updatedConfig); - return updatedConfig; - } catch (error: any) { - console.error( - chalk.red("Error fetching organizations:"), - error.response?.data?.message || error.message || error, - ); - console.info(chalk.yellow("Continuing without organization selection.")); - const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); - saveAuthConfig(updatedConfig); - return updatedConfig; - } -} diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts index a775ee670..9dcadf312 100644 --- a/extensions/cli/src/auth/workos.ts +++ b/extensions/cli/src/auth/workos.ts @@ -22,7 +22,7 @@ export interface AuthenticatedConfig { accessToken: string; refreshToken: string; expiresAt: number; - organizationId: string | null; // null means personal organization + organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection configUri?: string; // Optional config URI (file:// or slug://owner/slug) modelName?: string; // Name of the selected model } @@ -74,7 +74,9 @@ export function getAccessToken(config: AuthConfig): string | null { /** * Gets the organization ID from any auth config type */ -export function getOrganizationId(config: AuthConfig): string | null { +export function getOrganizationId( + config: AuthConfig, +): string | null | undefined { if (config === null) return null; return config.organizationId; } @@ -96,10 +98,9 @@ export function getModelName(config: AuthConfig): string | null { } // URI utility functions have been moved to ./uriUtils.ts +import { autoSelectOrganizationAndConfig } from "./orgSelection.js"; import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js"; import { - autoSelectOrganization, - createUpdatedAuthConfig, handleCliOrgForAuthenticatedConfig, handleCliOrgForEnvironmentAuth, } from "./workos.helpers.js"; @@ -360,7 +361,7 @@ async function pollForDeviceToken( accessToken: access_token, refreshToken: refresh_token, expiresAt: tokenExpiresAt, - organizationId: null, + organizationId: undefined, // undefined triggers auto-selection, null means personal org selected }; // Save the config @@ -563,20 +564,18 @@ export async function ensureOrganization( ); } - // If already have organization ID (including null for personal), return as-is - if (authenticatedConfig.organizationId !== undefined) { - return authenticatedConfig; + // Only auto-select if user hasn't made any previous selections + // - organizationId === undefined means first-time setup + // - configUri being set means they've chosen a specific assistant/config + if ( + authenticatedConfig.organizationId === undefined && + !authenticatedConfig.configUri + ) { + return autoSelectOrganizationAndConfig(authenticatedConfig); } - // In headless mode, default to personal organization if none saved - if (isHeadless) { - const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); - saveAuthConfig(updatedConfig); - return updatedConfig; - } - - // Need to select organization - return autoSelectOrganization(authenticatedConfig); + // User already has made a selection (org or config) - respect their choice + return authenticatedConfig; } /** diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 61dd79c9c..4436d18b7 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -498,17 +498,12 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { const { permissionOverrides } = processCommandFlags(options); // Initialize services with onboarding handled internally - const initResult = await initializeServices({ + await initializeServices({ options, headless: false, toolPermissionOverrides: permissionOverrides, }); - // If onboarding was completed, show success message - if (initResult.wasOnboarded) { - console.log(chalk.green("✓ Setup complete! Starting chat...")); - } - // Start TUI with skipOnboarding since we already handled it const tuiOptions: any = { initialPrompt: prompt, diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts index d9ea6dca8..6c97767bc 100644 --- a/extensions/cli/src/config.ts +++ b/extensions/cli/src/config.ts @@ -39,7 +39,7 @@ export function createLlmApi( apiKey: accessToken ?? undefined, env: { apiKeyLocation: (model as any).apiKeyLocation, - orgScopeId: organizationId, + orgScopeId: organizationId ?? null, proxyUrl: (model as { onPremProxyUrl: string | undefined }) .onPremProxyUrl ?? undefined, diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts index 3fe00fd21..423875312 100644 --- a/extensions/cli/src/configLoader.ts +++ b/extensions/cli/src/configLoader.ts @@ -55,7 +55,7 @@ export async function loadConfiguration( const config = await loadFromSource( configSource, accessToken, - organizationId, + organizationId ?? null, apiClient, ); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 7eb59d89a..6d8e2b99f 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -105,7 +105,10 @@ async function runOnboardingFlow( if (choice === "1" || choice === "") { const newAuthConfig = await login(); - const result = await initialize(newAuthConfig, undefined); + const { ensureOrganization } = await import("./auth/workos.js"); + const finalAuthConfig = await ensureOrganization(newAuthConfig); + + const result = await initialize(finalAuthConfig, undefined); return { ...result, wasOnboarded: true }; } else if (choice === "2") { const apiKey = readlineSync.question( From 3b1227c27ed16cbdb0050e02904f60097b9fa10b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 19 Sep 2025 17:39:53 -0700 Subject: [PATCH 20/20] fix: address cubic feedback --- core/util/errors.ts | 2 +- gui/src/redux/thunks/callToolById.ts | 10 ++++++---- gui/src/util/clientTools/callClientTool.ts | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/core/util/errors.ts b/core/util/errors.ts index 8e7a1ad3e..90539f8f3 100644 --- a/core/util/errors.ts +++ b/core/util/errors.ts @@ -46,6 +46,6 @@ export enum ContinueErrorReason { ParentDirectoryNotFound = "parent_directory_not_found", // Other - Unspecificied = "unspecified", + Unspecified = "unspecified", Unknown = "unknown", } diff --git a/gui/src/redux/thunks/callToolById.ts b/gui/src/redux/thunks/callToolById.ts index 9a70e39f5..30e136efb 100644 --- a/gui/src/redux/thunks/callToolById.ts +++ b/gui/src/redux/thunks/callToolById.ts @@ -99,10 +99,12 @@ export const callToolById = createAsyncThunk< throw new Error(result.error); } else { output = result.content.contextItems; - error = new ContinueError( - ContinueErrorReason.Unspecificied, - result.content.errorMessage, - ); + error = result.content.errorMessage + ? new ContinueError( + ContinueErrorReason.Unspecified, + result.content.errorMessage, + ) + : undefined; } streamResponse = true; } diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts index 1bde6613f..7b76fc6f5 100644 --- a/gui/src/util/clientTools/callClientTool.ts +++ b/gui/src/util/clientTools/callClientTool.ts @@ -60,7 +60,7 @@ export async function callClientTool( e instanceof ContinueError ? e : e instanceof Error - ? new ContinueError(ContinueErrorReason.Unspecificied, e.message) + ? new ContinueError(ContinueErrorReason.Unspecified, e.message) : new ContinueError(ContinueErrorReason.Unknown), output: undefined, };