diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 4abb7bc49..744371c4c 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -31,6 +31,62 @@ jobs: if: steps.root-cache.outputs.cache-hit != 'true' run: npm ci + install-config-yaml: + needs: install-root + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Install config-yaml dependencies + if: steps.config-yaml-cache.outputs.cache-hit != 'true' + run: | + cd packages/config-yaml + npm ci + + config-yaml-checks: + needs: install-config-yaml + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build and check config-yaml + run: | + cd packages/config-yaml + npx tsc --noEmit + # Tests are currently failing, commenting out for now + # npm test + npm run build + install-core: needs: install-root runs-on: ubuntu-latest @@ -60,7 +116,7 @@ jobs: npm ci core-checks: - needs: install-core + needs: [install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -81,6 +137,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check and lint run: | cd core @@ -90,7 +157,7 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -115,6 +182,17 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install gui dependencies if: steps.gui-cache.outputs.cache-hit != 'true' run: | @@ -147,13 +225,24 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check run: | cd gui npx tsc --noEmit binary-checks: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -178,6 +267,17 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install binary dependencies if: steps.binary-cache.outputs.cache-hit != 'true' run: | @@ -190,7 +290,7 @@ jobs: npx tsc --noEmit install-vscode: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -215,6 +315,17 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install vscode dependencies if: steps.vscode-cache.outputs.cache-hit != 'true' run: | @@ -249,14 +360,26 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check and lint run: | cd extensions/vscode + npm run write-build-timestamp npx tsc --noEmit npm run lint core-tests: - needs: install-core + needs: [install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -270,6 +393,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Run core tests run: | cd core @@ -309,7 +443,7 @@ jobs: vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [install-root, install-vscode] + needs: [install-root, install-vscode, install-config-yaml] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: @@ -321,6 +455,17 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Get test files id: vscode-get-test-file-matrix run: | @@ -344,7 +489,7 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [install-vscode, install-core, install-config-yaml] steps: - uses: actions/checkout@v4 @@ -364,6 +509,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Package extension run: | cd extensions/vscode @@ -377,7 +533,7 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [install-vscode, install-core, install-config-yaml] steps: - uses: actions/checkout@v4 @@ -397,6 +553,17 @@ jobs: path: extensions/vscode/e2e/storage key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Download Dependencies if: steps.storage-cache.outputs.cache-hit != 'true' run: | @@ -418,6 +585,7 @@ jobs: vscode-package-extension, install-vscode, install-core, + install-config-yaml, ] runs-on: ubuntu-latest # Tests requiring secrets need approval from maintainers @@ -458,6 +626,17 @@ jobs: name: vscode-e2e-dependencies path: extensions/vscode/e2e/storage + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Fix VSCode binary permissions run: | chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code @@ -513,7 +692,7 @@ jobs: path: e2e.log gui-tests: - needs: [install-gui, install-core] + needs: [install-gui, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -533,6 +712,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install GUI dependencies if: steps.gui-cache.outputs.cache-hit != 'true' run: cd gui && npm ci @@ -545,7 +735,7 @@ jobs: npm test jetbrains-tests: - needs: [install-root, core-checks] + needs: [install-root, core-checks, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -554,6 +744,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Setup Java uses: actions/setup-java@v4.5.0 with: @@ -665,6 +866,8 @@ jobs: - vscode-e2e-tests - gui-tests - jetbrains-tests + - config-yaml-checks + - install-config-yaml steps: - name: Decide whether the needed jobs succeeded or failed diff --git a/binary/package-lock.json b/binary/package-lock.json index 51ea6b1f1..5c2324e82 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index ac673b38f..fbd390fb4 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -14,7 +14,7 @@ "eqeqeq": "error", "complexity": ["error", { "max": 36 }], "max-lines-per-function": ["error", { "max": 472 }], - "max-statements": ["error", { "max": 114 }], + "max-statements": ["error", { "max": 108 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], "max-params": ["error", { "max": 8 }] diff --git a/core/commands/util.ts b/core/commands/util.ts index 5a0ea32e4..3785b4f52 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -34,13 +34,18 @@ export function ctxItemToRifWithContents( ): RangeInFileWithContents { let startLine = 0; let endLine = 0; + let adjustLines = linesOffByOne ? 1 : 0; const nameSplit = item.name.split("("); if (nameSplit.length > 1) { const lines = nameSplit[1].split(")")[0].split("-"); - startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0); - endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0); + startLine = Number.parseInt(lines[0], 10); + if (startLine === 0) { + adjustLines = 0; // safety to make sure doesn't go negative + } + startLine -= adjustLines; + endLine = Number.parseInt(lines[1], 10) - adjustLines; } const rif: RangeInFileWithContents = { diff --git a/core/config/load.ts b/core/config/load.ts index 2853077fc..6473d3a51 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -70,7 +70,11 @@ import { localPathToUri } from "../util/pathToUri"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; -import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util"; +import { + getModelByRole, + isSupportedLanceDbCpuTargetForLinux, + serializePromptTemplates, +} from "./util"; import { validateConfig } from "./validation.js"; export function resolveSerializedConfig( @@ -607,8 +611,9 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { template: llm.template, completionOptions: llm.completionOptions, systemMessage: llm.systemMessage, + baseChatSystemMessage: llm.baseChatSystemMessage, requestOptions: llm.requestOptions, - promptTemplates: llm.promptTemplates as any, + promptTemplates: serializePromptTemplates(llm.promptTemplates), capabilities: llm.capabilities, roles: llm.roles, configurationStatus: llm.getConfigurationStatus(), diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index cf689b45d..e1e66000d 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -1,3 +1,10 @@ +/** + * I'm disabling this rule for the entire file under the assumption + * that this is a one-time migration script. I'm expecting this + * code to be removed in the future. + */ +/* eslint-disable max-statements */ + import { IDE } from ".."; import { deduplicateArray } from "../util"; import { GlobalContext } from "../util/GlobalContext"; diff --git a/core/config/util.test.ts b/core/config/util.test.ts new file mode 100644 index 000000000..e7de79e1b --- /dev/null +++ b/core/config/util.test.ts @@ -0,0 +1,45 @@ +import { PromptTemplate } from ".."; +import { serializePromptTemplates } from "./util"; + +describe("serializePromptTemplates", () => { + it("should return undefined for undefined input", () => { + expect(serializePromptTemplates(undefined)).toBeUndefined(); + }); + + it("should convert function templates to empty strings", () => { + const functionTemplate: PromptTemplate = () => "Generated template"; + const templates: Record = { + template1: functionTemplate, + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual({ template1: "" }); + }); + + it("should pass through string templates unchanged", () => { + const templates: Record = { + template1: "This is a static template", + template2: "Another static template", + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual(templates); + }); + + it("should handle mixed template types", () => { + const functionTemplate: PromptTemplate = () => "Generated template"; + const templates: Record = { + function: functionTemplate, + string: "This is a static template", + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual({ + function: "", + string: "This is a static template", + }); + }); +}); diff --git a/core/config/util.ts b/core/config/util.ts index 957e6c6ff..4c70acb38 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -7,6 +7,7 @@ import { IDE, ILLM, ModelDescription, + PromptTemplate, } from "../"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; @@ -169,3 +170,22 @@ async function showUnsupportedCpuToast(ide: IDE) { ); } } + +/** + * This is required because users are only able to define prompt templates as a + * string, while internally we also allow prompt templates to be functions + * @param templates + * @returns + */ +export function serializePromptTemplates( + templates: Record | undefined, +): Record | undefined { + if (!templates) return undefined; + + return Object.fromEntries( + Object.entries(templates).map(([key, template]) => { + const serialized = typeof template === "function" ? "" : template; + return [key, serialized]; + }), + ); +} diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 0bbe19235..535908b4a 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -63,6 +63,7 @@ async function modelConfigToBaseLLM({ systemMessage: config.systemMessage, rules: config.rules, promptTemplates: model.promptTemplates, + baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { tools: model.capabilities?.includes("tool_use"), uploadImage: model.capabilities?.includes("image_input"), diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index f30751d70..d2323aca3 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -3,9 +3,8 @@ import { generateLines } from "../../diff/util"; import { supportedLanguages } from "../../util/treeSitter"; import { getUriFileExtension } from "../../util/uri"; -import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; -import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply"; +import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; function canUseInstantApply(filename: string) { const fileExtension = getUriFileExtension(filename); @@ -17,22 +16,21 @@ export async function applyCodeBlock( newFile: string, filename: string, llm: ILLM, - fastLlm: ILLM, ): Promise<[boolean, AsyncGenerator]> { // This was buggy, removed for now, maybe forever - if (false && canUseInstantApply(filename)) { - const diffLines = await deterministicApplyLazyEdit( - oldFile, - newFile, - filename, - ); + // if (canUseInstantApply(filename)) { + // const diffLines = await deterministicApplyLazyEdit( + // oldFile, + // newFile, + // filename, + // ); - // Fall back to LLM method if we couldn't apply deterministically - if (diffLines !== undefined) { - const diffGenerator = generateLines(diffLines!); - return [true, diffGenerator]; - } - } + // // Fall back to LLM method if we couldn't apply deterministically + // if (diffLines !== undefined) { + // const diffGenerator = generateLines(diffLines!); + // return [true, diffGenerator]; + // } + // } // If the code block is a diff if (isUnifiedDiffFormat(newFile)) { @@ -45,5 +43,5 @@ export async function applyCodeBlock( } } - return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)]; + return [false, streamLazyApply(oldFile, filename, newFile, llm)]; } diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 982e263e8..ce7af0ef7 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -16,7 +16,6 @@ export async function* streamLazyApply( filename: string, newCode: string, llm: ILLM, - fastLlm: ILLM, ): AsyncGenerator { const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName); if (!promptFactory) { @@ -39,7 +38,7 @@ export async function* streamLazyApply( oldCode, linesBefore, linesAfter, - fastLlm, + llm, )) { yield line; } diff --git a/core/index.d.ts b/core/index.d.ts index f81f14262..30a977717 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -77,39 +77,19 @@ export type PromptTemplateFunction = ( export type PromptTemplate = string | PromptTemplateFunction; -export interface ILLM extends LLMOptions { +type RequiredLLMOptions = + | "uniqueId" + | "contextLength" + | "embeddingId" + | "maxEmbeddingChunkSize" + | "maxEmbeddingBatchSize" + | "completionOptions"; + +export interface ILLM + extends Omit, + Required> { get providerName(): string; - uniqueId: string; - model: string; - - title?: string; - systemMessage?: string; - contextLength: number; - maxStopWords?: number; - completionOptions: CompletionOptions; - requestOptions?: RequestOptions; - promptTemplates?: Record; - templateMessages?: (messages: ChatMessage[]) => string; - llmLogger?: ILLMLogger; - llmRequestHook?: (model: string, prompt: string) => any; - apiKey?: string; - apiBase?: string; - cacheBehavior?: CacheBehavior; - capabilities?: ModelCapability; - roles?: ModelRole[]; - - deployment?: string; - apiVersion?: string; - apiType?: string; - region?: string; - projectId?: string; - - // Embedding options - embeddingId: string; - maxEmbeddingChunkSize: number; - maxEmbeddingBatchSize: number; - complete( prompt: string, signal: AbortSignal, @@ -580,6 +560,7 @@ export interface LLMOptions { title?: string; uniqueId?: string; systemMessage?: string; + baseChatSystemMessage?: string; contextLength?: number; maxStopWords?: number; completionOptions?: CompletionOptions; @@ -1059,6 +1040,7 @@ export interface ModelDescription { template?: TemplateType; completionOptions?: BaseCompletionOptions; systemMessage?: string; + baseChatSystemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; cacheBehavior?: CacheBehavior; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 99dc1d539..0bd7ba93a 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -64,6 +64,48 @@ export type AddParams = { favicon?: string; }; +const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const newFailedDocs = failedDocs.filter( + (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + newFailedDocs.push(siteIndexingConfig); + globalContext.update("failedDocs", newFailedDocs); +}; + +const removeFromFailedGlobalContext = ( + siteIndexingConfig: SiteIndexingConfig, +) => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const newFailedDocs = failedDocs.filter( + (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + globalContext.update("failedDocs", newFailedDocs); +}; + +const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + return failedDocs.find((d) => + siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); +}; + +const siteIndexingConfigsAreEqual = ( + config1: SiteIndexingConfig, + config2: SiteIndexingConfig, +) => { + return ( + config1.startUrl === config2.startUrl && + config1.faviconUrl === config2.faviconUrl && + config1.title === config2.title && + config1.maxDepth === config2.maxDepth && + config1.useLocalCrawling === config2.useLocalCrawling + ); +}; + /* General process: - On config update: @@ -433,12 +475,7 @@ export default class DocsService { // If not force-reindexing and has failed with same config, don't reattempt if (!forceReindex) { - const globalContext = new GlobalContext(); - const failedDocs = globalContext.get("failedDocs") ?? []; - const hasFailed = failedDocs.find((d) => - this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), - ); - if (hasFailed) { + if (hasIndexingFailed(siteIndexingConfig)) { console.log( `Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`, ); @@ -473,25 +510,6 @@ export default class DocsService { return; } - const markFailedInGlobalContext = () => { - const globalContext = new GlobalContext(); - const failedDocs = globalContext.get("failedDocs") ?? []; - const newFailedDocs = failedDocs.filter( - (d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), - ); - newFailedDocs.push(siteIndexingConfig); - globalContext.update("failedDocs", newFailedDocs); - }; - - const removeFromFailedGlobalContext = () => { - const globalContext = new GlobalContext(); - const failedDocs = globalContext.get("failedDocs") ?? []; - const newFailedDocs = failedDocs.filter( - (d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), - ); - globalContext.update("failedDocs", newFailedDocs); - }; - try { this.docsIndexingQueue.add(startUrl); @@ -630,7 +648,7 @@ export default class DocsService { }); // void this.ide.showToast("info", `Failed to index ${startUrl}`); - markFailedInGlobalContext(); + markFailedInGlobalContext(siteIndexingConfig); return; } @@ -690,7 +708,7 @@ export default class DocsService { providers: ["docs"], }); - removeFromFailedGlobalContext(); + removeFromFailedGlobalContext(siteIndexingConfig); } catch (e) { console.error( `Error indexing docs at: ${siteIndexingConfig.startUrl}`, @@ -711,7 +729,7 @@ export default class DocsService { status: "failed", progress: 1, }); - markFailedInGlobalContext(); + markFailedInGlobalContext(siteIndexingConfig); } finally { this.docsIndexingQueue.delete(startUrl); } @@ -973,10 +991,7 @@ export default class DocsService { (d) => d.startUrl === doc.startUrl, ); - if ( - oldConfigDoc && - !this.siteIndexingConfigsAreEqual(oldConfigDoc, doc) - ) { + if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) { changedDocs.push(doc); } else { if (forceReindex) { @@ -1163,24 +1178,11 @@ export default class DocsService { ); } - private siteIndexingConfigsAreEqual( - config1: SiteIndexingConfig, - config2: SiteIndexingConfig, - ) { - return ( - config1.startUrl === config2.startUrl && - config1.faviconUrl === config2.faviconUrl && - config1.title === config2.title && - config1.maxDepth === config2.maxDepth && - config1.useLocalCrawling === config2.useLocalCrawling - ); - } - private addToConfig(siteIndexingConfig: SiteIndexingConfig) { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file const doesEquivalentDocExist = this.config.docs?.some((doc) => - this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig), + siteIndexingConfigsAreEqual(doc, siteIndexingConfig), ); if (!doesEquivalentDocExist) { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 69425d33e..f3e6b4d07 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,14 +1,41 @@ import { ChatHistoryItem, ChatMessage, MessagePart } from "../"; import { normalizeToMessageParts } from "../util/messageContent"; -const DEFAULT_SYSTEM_MESSAGE = ` - Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'. +const DEFAULT_SYSTEM_MESSAGE = `\ + + Always include the language and file name in the info string when you write code blocks. + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' + + When addressing code modification requests, present a concise code snippet that + emphasizes only the necessary changes and uses abbreviated placeholders for + unmodified sections. For instance: + + \`\`\`typescript /path/to/file + // ... rest of code here ... + + {{ modified code here }} + + // ... rest of code here ... + + {{ another modification }} + + // ... rest of code here ... + \`\`\` + + Since users have access to their complete file, they prefer reading only the + relevant modifications. It's perfectly acceptable to omit unmodified portions + at the beginning, middle, or end of files using these "lazy" comments. Only + provide the complete file when explicitly requested. Include a concise explanation + of changes unless the user specifically asks for code only. `; const CANCELED_TOOL_CALL_MESSAGE = "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; -export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { +export function constructMessages( + history: ChatHistoryItem[], + baseChatSystemMessage: string | undefined, +): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", ); @@ -16,7 +43,7 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { msgs.push({ role: "system", - content: DEFAULT_SYSTEM_MESSAGE, + content: baseChatSystemMessage ?? DEFAULT_SYSTEM_MESSAGE, }); for (let i = 0; i < filteredHistory.length; i++) { diff --git a/core/llm/index.ts b/core/llm/index.ts index 723ab2f45..a380bd5de 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -127,6 +127,7 @@ export abstract class BaseLLM implements ILLM { title?: string; systemMessage?: string; + baseChatSystemMessage?: string; contextLength: number; maxStopWords?: number | undefined; completionOptions: CompletionOptions; @@ -195,6 +196,7 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; this.systemMessage = options.systemMessage; + this.baseChatSystemMessage = options.baseChatSystemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; this.maxStopWords = options.maxStopWords ?? this.maxStopWords; diff --git a/core/package-lock.json b/core/package-lock.json index 8ab0eb882..3df30cd17 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.85", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -109,6 +109,27 @@ "node": ">=20.11.0" } }, + "../packages/config-yaml": { + "name": "@continuedev/config-yaml", + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2" + } + }, "node_modules/@75lb/deep-merge": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz", @@ -2986,17 +3007,8 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.85", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.85.tgz", - "integrity": "sha512-yqcoUMlA/qjhVYJt6BBfY6xCpfKar20LfljHMjObG+ndo3MLzPXFxU/+aB4MAQmyn54P5VGbXrALJFo/EErxMA==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - }, - "bin": { - "config-yaml": "dist/cli.js" - } + "resolved": "../packages/config-yaml", + "link": true }, "node_modules/@continuedev/fetch": { "version": "1.0.4", diff --git a/core/package.json b/core/package.json index 1ed7b3e37..f34c863f5 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.85", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index b477fcce9..cc1191d92 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -11,8 +11,6 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB applyToFile: [ { text: string; diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index b21f78092..310c64df2 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -70,7 +70,7 @@ To add a single documentation site, we recommend using the **Add Documentation** In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site. -- `Title`: The name of the documentation site, used for identification in the UI +- `Title`: The name of the documentation site, used for identification in the UI. - `Start URL`: The URL where the indexing process should begin. Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page. @@ -154,9 +154,9 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo -### Github +### GitHub -The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file: +The GitHub API rate limits public requests to 60 per hour. If you want to reliably index GitHub repos, you can add a github token to your config file: @@ -223,7 +223,7 @@ Chromium crawling has been deprecated Further notes: - If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential. -- For Github Repos this has no effect because only the Github Crawler will be used, and if the repo is private it can only be accessed with a priveleged Github token anyways. +- For GitHub Repos this has no effect because only the GitHub Crawler will be used, and if the repo is private it can only be accessed with a priveleged GitHub token anyways. ## Managing your docs indexes @@ -237,6 +237,7 @@ You can view indexing statuses and manage your documentation sites from the `@do ![More Page @docs indexes section](/img/docs-indexes.png) You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page + ![Documentation indexing peek](/img/docs-indexing-peek.png) You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`. @@ -327,7 +328,7 @@ The following configuration example includes: - Examples of both public and private documentation sources - A custom embeddings provider - A reranker model available, with reranking parameters customized -- A Github token to enable Github crawling +- A GitHub token to enable GitHub crawling diff --git a/docs/docs/customize/model-providers/more/asksage.mdx b/docs/docs/customize/model-providers/more/asksage.mdx index 675cedc7f..b7d7ede26 100644 --- a/docs/docs/customize/model-providers/more/asksage.mdx +++ b/docs/docs/customize/model-providers/more/asksage.mdx @@ -4,7 +4,7 @@ import TabItem from "@theme/TabItem"; import Tabs from "@theme/Tabs"; :::info -To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs:[Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) +To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs: [Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) ::: ## Configuration @@ -55,7 +55,7 @@ Currently, the setup for the models provided by Ask Sage is to support the follo More models, functionalities and documentation will be added in the future for Ask Sage Integration. -> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. +> We recommend to utilize the `OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. ## Ask Sage Documentation diff --git a/docs/docs/customize/model-providers/more/siliconflow.mdx b/docs/docs/customize/model-providers/more/siliconflow.mdx index a496d3757..79ccd8e71 100644 --- a/docs/docs/customize/model-providers/more/siliconflow.mdx +++ b/docs/docs/customize/model-providers/more/siliconflow.mdx @@ -81,8 +81,8 @@ We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete ## Embeddings model -SiliconFlow provide some embeddings models, [Click here](https://siliconflow.cn/models) to see a list of embeddings models. +SiliconFlow provide some embeddings models. [Click here](https://siliconflow.cn/models) to see a list of embeddings models. ## Reranking model -SiliconFlow provide some reranking models, [Click here](https://siliconflow.cn/models) to see a list of reranking models. +SiliconFlow provide some reranking models. [Click here](https://siliconflow.cn/models) to see a list of reranking models. diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 1ecace184..78574b096 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -13,3 +13,27 @@ When editing code, Chat and Edit model output often doesn't clearly align with e Generally speaking, models proficient in chat and edit can also be used for applying code. Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply). + +## Prompt templating + +You can customize the prompt template used for applying code changes by setting the `promptTemplates.apply` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the apply template: + +- `{{{original_code}}}` - The original code before changes +- `{{{new_code}}}` - The new code after changes + +Example: + +```yaml +models: + - name: My Custom Apply Template + provider: anthropic + model: claude-3-5-sonnet-latest + promptTemplates: + apply: | + Original: {{{original_code}}} + New: {{{new_code}}} + + Please generate the final code without any markers or explanations. +``` diff --git a/docs/docs/customize/model-roles/chat.mdx b/docs/docs/customize/model-roles/chat.mdx index aca683782..781ce37d9 100644 --- a/docs/docs/customize/model-roles/chat.mdx +++ b/docs/docs/customize/model-roles/chat.mdx @@ -257,6 +257,14 @@ If your local machine can run an 8B parameter model, then we recommend running L model: llama3.1:8b ``` + + ```yaml title="config.yaml" + models: + - name: Llama 3.1 8B + provider: msty + model: llama3.1:8b + ``` + @@ -287,6 +295,19 @@ If your local machine can run an 8B parameter model, then we recommend running L } ``` + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "msty", + "model": "llama3.1-8b" + } + ] + } + ``` + @@ -325,6 +346,14 @@ If your local machine can run a 16B parameter model, then we recommend running D model: deepseek-coder-v2:16b ``` + + ```yaml title="config.yaml" + models: + - name: DeepSeek Coder 2 16B + provider: msty + model: deepseek-coder-v2:16b + ``` + @@ -356,6 +385,19 @@ If your local machine can run a 16B parameter model, then we recommend running D } ``` + + ```json title="config.json" + { + "models": [ + { + "title": "DeepSeek Coder 2 16B", + "provider": "msty", + "model": "deepseek-coder-v2:16b" + } + ] + } + ``` + diff --git a/docs/docs/customize/model-roles/edit.mdx b/docs/docs/customize/model-roles/edit.mdx index de817ed42..ca4572f26 100644 --- a/docs/docs/customize/model-roles/edit.mdx +++ b/docs/docs/customize/model-roles/edit.mdx @@ -29,8 +29,8 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use Set the `experimental.modelRoles.inlineEdit` property in `config.json`. ```json title="config.json" { - "models": { - "name": "Claude 3.5 Sonnet", + "models": { + "name": "Claude 3.5 Sonnet", "provider": "anthropic", "model": "claude-3-5-sonnet-latest", "apiKey": "" @@ -46,3 +46,37 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat. + +## Prompt templating + +You can customize the prompt template used for editing code by setting the `promptTemplates.edit` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the edit template: + +- `{{{userInput}}}` - The user's edit request/instruction +- `{{{language}}}` - The programming language of the code +- `{{{codeToEdit}}}` - The code that's being edited +- `{{{prefix}}}` - Content before the edit area +- `{{{suffix}}}` - Content after the edit area +- `{{{supportsCompletions}}}` - Whether the model supports completions API +- `{{{supportsPrefill}}}` - Whether the model supports prefill capability + +Example: + +```yaml +models: + - name: My Custom Edit Template + provider: openai + model: gpt-4o + promptTemplates: + edit: | + `Here is the code before editing: + \`\`\`{{{language}}} + {{{codeToEdit}}} + \`\`\` + + Here is the edit requested: + "{{{userInput}}}" + + Here is the code after editing:` +``` diff --git a/docs/docs/customize/tutorials/custom-code-rag.mdx b/docs/docs/customize/tutorials/custom-code-rag.mdx index f5e43dc8e..145c38f10 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.mdx +++ b/docs/docs/customize/tutorials/custom-code-rag.mdx @@ -22,7 +22,7 @@ Most embeddings models can only handle a limited amount of text at once. To get If you use `voyage-code-3`, it has a maximum context length of 16,000 tokens, which is enough to fit most files. This means that in the beginning you can get away with a more naive strategy of truncating files that exceed the limit. In order of easiest to most comprehensive, 3 chunking strategies you can use are: 1. Truncate the file when it goes over the context length: in this case you will always have 1 chunk per file. -2. Split the file into chunks of a fixed length: starting at the top of the file, add lines you your current chunk until it reaches the limit, then start a new chunk. +2. Split the file into chunks of a fixed length: starting at the top of the file, add lines in your current chunk until it reaches the limit, then start a new chunk. 3. Use a recursive, abstract syntax tree (AST)-based strategy: this is the most exact, but most complex. In most cases you can achieve high quality results by using (1) or (2), but if you'd like to try this you can find a reference example in [our code chunker](https://github.com/continuedev/continue/blob/main/core/indexing/chunk/code.ts) or in [LlamaIndex](https://docs.llamaindex.ai/en/stable/api_reference/node_parsers/code/). As usual in this guide, we recommend starting with the strategy that gives 80% of the benefit with 20% of the effort. @@ -51,8 +51,8 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-3` model. - vector: Vector(1536) = func.VectorField() + # 1024 is the default dimension for `voyage-code-3`: https://docs.voyageai.com/docs/embeddings#model-choices + vector: Vector(1024) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") table.add([ @@ -79,7 +79,7 @@ Regardless of which database or model you have chosen, your script should iterat In a perfect production version, you would want to build "automatic, incremental indexing", so that you whenever a file changes, that file and nothing else is automatically re-indexed. This has the benefits of perfectly up-to-date embeddings and lower cost. -That said, we highly recommend first building and testing the pipeline before attempting this. Unless your codebase is being entirely rewritten frequently, a full refresh of the index is likely to be sufficient and reasonably cheap. +That said, we highly recommend first building and testing the pipeline before attempting this. Unless your codebase is being entirely rewritten frequently, an incremental refresh of the index is likely to be sufficient and reasonably cheap. ::: At this point, you've written your indexing script and tested that you can make queries from your vector database. Now, you'll want a plan for when to run the indexing script. diff --git a/docs/docs/customize/tutorials/llama3.1.mdx b/docs/docs/customize/tutorials/llama3.1.mdx index 413214fb4..bb65be947 100644 --- a/docs/docs/customize/tutorials/llama3.1.mdx +++ b/docs/docs/customize/tutorials/llama3.1.mdx @@ -198,7 +198,7 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L - name: Cerebras Llama 3.1 70B provider: cerebras model: llama3.1-70b - apiKey: + apiKey: ``` @@ -209,7 +209,7 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L "title": "Cerebras Llama 3.1 70B", "provider": "cerebras", "model": "llama3.1-70b", - "apiKey": "" + "apiKey": "" } ] } diff --git a/docs/docs/customize/tutorials/set-up-codestral.mdx b/docs/docs/customize/tutorials/set-up-codestral.mdx index 1ace12f2f..833da53bc 100644 --- a/docs/docs/customize/tutorials/set-up-codestral.mdx +++ b/docs/docs/customize/tutorials/set-up-codestral.mdx @@ -61,6 +61,3 @@ import TabItem from "@theme/TabItem"; 5. If you run into any issues or have any questions, please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) -### Ask for help on Discord - -Please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) if you are having problems using Codestral diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index b9c5bbd13..03b92c08a 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -15,7 +15,7 @@ Continue supports [many model providers](../../customize/model-providers), inclu ## Context -Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and Github issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. +Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and GitHub issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. Learn more about context providers [here](../../reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../reference.md#context). diff --git a/docs/docs/reference.md b/docs/docs/reference.md index b9ae84846..6269a1bb7 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -145,15 +145,13 @@ The `models` section defines the language models used in your configuration. Mod - `apiBase`: Can be used to override the default API base that is specified per model - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating). +- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: + - `baseSystemMessage`: Can be used to override the default system prompt. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: - - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - - `defaultCompletionOptions`: Default completion options for model settings. - - **Properties:** - - `contextLength`: Maximum context length of the model, typically in tokens. - `maxTokens`: Maximum number of tokens to generate in a completion. - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). @@ -161,11 +159,7 @@ The `models` section defines the language models used in your configuration. Mod - `topK`: Maximum number of tokens considered at each step. - `stop`: An array of stop tokens that will terminate the completion. - `n`: Number of completions to generate. - - `requestOptions`: HTTP request options specific to the model. - - **Properties:** - - `timeout`: Timeout for each request to the language model. - `verifySsl`: Whether to verify SSL certificates for requests. - `caBundlePath`: Path to a custom CA bundle for HTTP requests. @@ -178,7 +172,7 @@ The `models` section defines the language models used in your configuration. Mod - `key`: Path to the client certificate key file. - `passphrase`: Optional passphrase for the client certificate key file. -#### Example: +#### Example ```yaml title="config.yaml" models: diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 29ad0b023..aa99f752c 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -3,6 +3,7 @@ node_modules/ out/ .vscode-test/ data/ +src/.buildTimestamp.ts src/client .continue diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 126df7e51..fdcad544a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.22", + "version": "1.1.23", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.22", + "version": "1.1.23", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -62,7 +62,7 @@ }, "devDependencies": { "@biomejs/biome": "1.6.4", - "@nestjs/common": "^8.4.7", + "@nestjs/common": "^11.0.16", "@openapitools/openapi-generator-cli": "^2.5.2", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", @@ -88,7 +88,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.5.12", + "vite": "^4.5.13", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.85", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -1433,43 +1433,29 @@ "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" }, - "node_modules/@nestjs/axios": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz", - "integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==", - "dev": true, - "peerDependencies": { - "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", - "axios": "^1.3.1", - "rxjs": "^6.0.0 || ^7.0.0" - } - }, "node_modules/@nestjs/common": { - "version": "8.4.7", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-8.4.7.tgz", - "integrity": "sha512-m/YsbcBal+gA5CFrDpqXqsSfylo+DIQrkFY3qhVIltsYRfu8ct8J9pqsTO6OPf3mvqdOpFGrV5sBjoyAzOBvsw==", + "version": "11.0.16", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.16.tgz", + "integrity": "sha512-agvuQ8su4aZ+PVxAmY89odG1eR97HEQvxPmTMdDqyvDWzNerl7WQhUEd+j4/UyNWcF1or1UVcrtPj52x+eUSsA==", "dev": true, + "license": "MIT", "dependencies": { - "axios": "0.27.2", "iterare": "1.2.1", - "tslib": "2.4.0", - "uuid": "8.3.2" + "tslib": "2.8.1", + "uid": "2.0.2" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/nest" }, "peerDependencies": { - "cache-manager": "*", "class-transformer": "*", "class-validator": "*", - "reflect-metadata": "^0.1.12", + "file-type": "^20.4.1", + "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, "peerDependenciesMeta": { - "cache-manager": { - "optional": true - }, "class-transformer": { "optional": true }, @@ -1478,31 +1464,6 @@ } } }, - "node_modules/@nestjs/common/node_modules/axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "dev": true, - "dependencies": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "node_modules/@nestjs/common/node_modules/tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", - "dev": true - }, - "node_modules/@nestjs/common/node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "dev": true, - "bin": { - "uuid": "dist/bin/uuid" - } - }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1692,6 +1653,18 @@ "url": "https://opencollective.com/openapi_generator" } }, + "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/axios": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz", + "integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", + "axios": "^1.3.1", + "rxjs": "^6.0.0 || ^7.0.0" + } + }, "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common": { "version": "10.4.6", "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.6.tgz", @@ -1963,6 +1936,53 @@ "resolved": "https://registry.npmjs.org/@tediousjs/connection-string/-/connection-string-0.5.0.tgz", "integrity": "sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ==" }, + "node_modules/@tokenizer/inflate": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", + "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "fflate": "^0.8.2", + "token-types": "^6.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/inflate/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -5941,6 +5961,14 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/figures": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", @@ -5977,6 +6005,26 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/file-type": { + "version": "20.4.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.4.1.tgz", + "integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@tokenizer/inflate": "^0.2.6", + "strtok3": "^10.2.0", + "token-types": "^6.0.0", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, "node_modules/file-uri-to-path": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", @@ -10090,6 +10138,21 @@ "node": "*" } }, + "node_modules/peek-readable": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-7.0.0.tgz", + "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -12046,6 +12109,25 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/strtok3": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.2.2.tgz", + "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/style-to-object": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.4.4.tgz", @@ -12677,6 +12759,25 @@ "node": ">=0.6" } }, + "node_modules/token-types": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.0.tgz", + "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/tough-cookie": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", @@ -12916,6 +13017,20 @@ "node": ">=8" } }, + "node_modules/uint8array-extras": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.4.0.tgz", + "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/underscore": { "version": "1.13.7", "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz", @@ -13322,9 +13437,9 @@ } }, "node_modules/vite": { - "version": "4.5.12", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz", - "integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==", + "version": "4.5.13", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.13.tgz", + "integrity": "sha512-Hgp8IF/yZDzKsN1hQWOuQZbrKiaFsbQud+07jJ8h9m9PaHWkpvZ5u55Xw5yYjWRXwRQ4jwFlJvY7T7FUJG9MCA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index bd056e12e..061baec75 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -607,6 +607,7 @@ "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", "package": "node scripts/package.js", "package-all": "node scripts/package-all.js", @@ -633,7 +634,7 @@ }, "devDependencies": { "@biomejs/biome": "1.6.4", - "@nestjs/common": "^8.4.7", + "@nestjs/common": "^11.0.16", "@openapitools/openapi-generator-cli": "^2.5.2", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", @@ -659,7 +660,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.5.12", + "vite": "^4.5.13", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index d8a9d4e68..9382e2b7a 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -1,4 +1,5 @@ const fs = require("fs"); +const { writeBuildTimestamp } = require("./utils"); const esbuild = require("esbuild"); @@ -49,6 +50,8 @@ const esbuildConfig = { }; (async () => { + // Create .buildTimestamp.js before starting the first build + writeBuildTimestamp(); // Bundles the extension into one file if (flags.includes("--watch")) { const ctx = await esbuild.context(esbuildConfig); @@ -74,7 +77,7 @@ const esbuildConfig = { }); console.log("Triggering VS Code Extension esbuild rebuild..."); - fs.utimesSync(inFile, new Date(), new Date()); + writeBuildTimestamp(); } else { await esbuild.build(esbuildConfig); } diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index aeab677ca..fbec94f6c 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,7 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema } = require("./utils"); +const { copyConfigSchema, writeBuildTimestamp } = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -71,6 +71,9 @@ const isMacTarget = target?.startsWith("darwin"); process.chdir("extensions/vscode"); } + // Make sure we have an initial timestamp file + writeBuildTimestamp(); + // Install node_modules // execCmdSync("npm install"); console.log("[info] npm install in extensions/vscode completed"); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index c4d392cfa..8a144731f 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -511,6 +511,20 @@ async function copyScripts() { console.log("[info] Copied script files"); } +// We can't simply touch one of our files to trigger a rebuild, because +// esbuild doesn't always use modifications times to detect changes - +// for example, if it finds a file changed within the last 3 seconds, +// it will fall back to full-contents-comparison for that file +// +// So to facilitate development workflows, we always include a timestamp string +// in the build +function writeBuildTimestamp() { + fs.writeFileSync( + "src/.buildTimestamp.ts", + `export default "${new Date().toISOString()}";\n`, + ); +} + module.exports = { copyConfigSchema, installNodeModules, @@ -526,4 +540,5 @@ module.exports = { downloadRipgrepBinary, copyTokenizers, copyScripts, + writeBuildTimestamp, }; diff --git a/extensions/vscode/scripts/write-build-timestamp.js b/extensions/vscode/scripts/write-build-timestamp.js new file mode 100644 index 000000000..a26f9b8d3 --- /dev/null +++ b/extensions/vscode/scripts/write-build-timestamp.js @@ -0,0 +1,3 @@ +const { writeBuildTimestamp } = require("./utils"); + +writeBuildTimestamp(); diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts new file mode 100644 index 000000000..4942cb0c1 --- /dev/null +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -0,0 +1,182 @@ +import { ConfigHandler } from "core/config/ConfigHandler"; +import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; +import { getUriPathBasename } from "core/util/uri"; +import * as vscode from "vscode"; + +import { VerticalDiffManager } from "../diff/vertical/manager"; +import { VsCodeIde } from "../VsCodeIde"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; + +export interface ApplyToFileOptions { + streamId: string; + filepath?: string; + text: string; + toolCallId?: string; +} + +/** + * Handles applying text/code to files including diff generation and streaming + */ +export class ApplyManager { + constructor( + private readonly ide: VsCodeIde, + private readonly webviewProtocol: VsCodeWebviewProtocol, + private readonly verticalDiffManager: VerticalDiffManager, + private readonly configHandler: ConfigHandler, + ) {} + + async applyToFile({ + streamId, + filepath, + text, + toolCallId, + }: ApplyToFileOptions) { + await this.webviewProtocol.request("updateApplyState", { + streamId, + status: "streaming", + fileContent: text, + toolCallId, + }); + + if (filepath) { + await this.ensureFileOpen(filepath); + } + + const { activeTextEditor } = vscode.window; + if (!activeTextEditor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + + const hasExistingDocument = !!activeTextEditor.document.getText().trim(); + + if (hasExistingDocument) { + await this.handleExistingDocument( + activeTextEditor, + text, + streamId, + toolCallId, + ); + } else { + await this.handleEmptyDocument( + activeTextEditor, + text, + streamId, + toolCallId, + ); + } + } + + private async ensureFileOpen(filepath: string): Promise { + const fileExists = await this.ide.fileExists(filepath); + if (!fileExists) { + await this.ide.writeFile(filepath, ""); + await this.ide.openFile(filepath); + } + await this.ide.openFile(filepath); + } + + private async handleEmptyDocument( + editor: vscode.TextEditor, + text: string, + streamId: string, + toolCallId?: string, + ) { + await editor.edit((builder) => + builder.insert(new vscode.Position(0, 0), text), + ); + + await this.webviewProtocol.request("updateApplyState", { + streamId, + status: "closed", + numDiffs: 0, + fileContent: text, + toolCallId, + }); + } + + private async handleExistingDocument( + editor: vscode.TextEditor, + text: string, + streamId: string, + toolCallId?: string, + ) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + vscode.window.showErrorMessage("Config not loaded"); + return; + } + + const llm = + config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; + if (!llm) { + vscode.window.showErrorMessage( + `No model with roles "apply" or "chat" found in config.`, + ); + return; + } + + const [instant, diffLines] = await applyCodeBlock( + editor.document.getText(), + text, + getUriPathBasename(editor.document.uri.toString()), + llm, + ); + + if (instant) { + await this.verticalDiffManager.streamDiffLines( + diffLines, + instant, + streamId, + toolCallId, + ); + } else { + await this.handleNonInstantDiff( + editor, + text, + llm, + streamId, + this.verticalDiffManager, + toolCallId, + ); + } + } + + /** + * Creates a prompt for applying code edits + */ + private getApplyPrompt(text: string): string { + return `The following code was suggested as an edit:\n\`\`\`\n${text}\n\`\`\`\nPlease apply it to the previous code.`; + } + + private async handleNonInstantDiff( + editor: vscode.TextEditor, + text: string, + llm: any, + streamId: string, + verticalDiffManager: VerticalDiffManager, + toolCallId?: string, + ) { + const prompt = this.getApplyPrompt(text); + const fullEditorRange = new vscode.Range( + 0, + 0, + editor.document.lineCount - 1, + editor.document.lineAt(editor.document.lineCount - 1).text.length, + ); + const rangeToApplyTo = editor.selection.isEmpty + ? fullEditorRange + : editor.selection; + + await verticalDiffManager.streamEdit( + prompt, + llm, + streamId, + undefined, + undefined, + rangeToApplyTo, + text, + toolCallId, + ); + } +} diff --git a/extensions/vscode/src/apply/index.ts b/extensions/vscode/src/apply/index.ts new file mode 100644 index 000000000..43b6ac276 --- /dev/null +++ b/extensions/vscode/src/apply/index.ts @@ -0,0 +1 @@ +export * from "./ApplyManager"; diff --git a/extensions/vscode/src/apply/utils.ts b/extensions/vscode/src/apply/utils.ts new file mode 100644 index 000000000..69ea37a3e --- /dev/null +++ b/extensions/vscode/src/apply/utils.ts @@ -0,0 +1,15 @@ +import { ILLM } from "core"; + +export const FAST_APPLY_MODELS: Array = ["Fast-Apply"]; + +/** + * Checks against model names, which can include proxy prefixes + * such as `continuedev/hub` + * @param llm + * @returns + */ +export function isFastApplyModel(llm: ILLM): boolean { + return FAST_APPLY_MODELS?.some((fastApplyModel) => + llm.model.toLowerCase().includes(fastApplyModel.toLowerCase()) + ); +} diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 48741a142..f5496fe2f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -6,6 +6,7 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import * as URI from "uri-js"; import * as vscode from "vscode"; +import { isFastApplyModel } from "../../apply/utils"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; @@ -345,6 +346,7 @@ export class VerticalDiffManager { startLine, endLine, { + instant: isFastApplyModel(llm), input, onStatusUpdate: (status, numDiffs, fileContent) => streamId && diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index f1aa3f3e4..be2b12487 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -8,6 +8,7 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; +export { default as buildTimestamp } from "./.buildTimestamp"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { await setupCa(); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 591c82454..3112572d9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,6 +1,4 @@ import { ConfigHandler } from "core/config/ConfigHandler"; -import { getModelByRole } from "core/config/util"; -import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; import { FromCoreProtocol, FromWebviewProtocol, @@ -15,9 +13,9 @@ import { WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; import { stripImages } from "core/util/messageContent"; -import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ApplyManager } from "../apply"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -29,14 +27,13 @@ import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & + ToWebviewFromCoreProtocol; + /** * A shared messenger class between Core and Webview * so we don't have to rewrite some of the handlers */ -type TODO = any; -type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & - ToWebviewFromCoreProtocol; - export class VsCodeMessenger { onWebview( messageType: T, @@ -128,110 +125,19 @@ export class VsCodeMessenger { }); this.onWebview("applyToFile", async ({ data }) => { - webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "streaming", - fileContent: data.text, - toolCallId: data.toolCallId, - }); + const [verticalDiffManager, configHandler] = await Promise.all([ + verticalDiffManagerPromise, + configHandlerPromise, + ]); - if (data.filepath) { - const fileExists = await this.ide.fileExists(data.filepath); - if (!fileExists) { - await this.ide.writeFile(data.filepath, ""); - await this.ide.openFile(data.filepath); - } - - await this.ide.openFile(data.filepath); - } - - // Get active text editor - const editor = vscode.window.activeTextEditor; - - if (!editor) { - vscode.window.showErrorMessage("No active editor to apply edits to"); - return; - } - - // If document is empty, insert at 0,0 and finish - if (!editor.document.getText().trim()) { - editor.edit((builder) => - builder.insert(new vscode.Position(0, 0), data.text), - ); - - void webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "closed", - numDiffs: 0, - fileContent: data.text, - toolCallId: data.toolCallId, - }); - - return; - } - - // Get LLM from config - const configHandler = await configHandlerPromise; - const { config } = await configHandler.loadConfig(); - - if (!config) { - vscode.window.showErrorMessage("Config not loaded"); - return; - } - - let llm = - config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; - - if (!llm) { - vscode.window.showErrorMessage( - `No model with roles "apply" or "chat" found in config.`, - ); - return; - } - - const fastLlm = getModelByRole(config, "repoMapFileSelection") ?? llm; - - // Generate the diff and pass through diff manager - const [instant, diffLines] = await applyCodeBlock( - editor.document.getText(), - data.text, - getUriPathBasename(editor.document.uri.toString()), - llm, - fastLlm, + const applyManager = new ApplyManager( + this.ide, + webviewProtocol, + verticalDiffManager, + configHandler, ); - const verticalDiffManager = await this.verticalDiffManagerPromise; - - if (instant) { - await verticalDiffManager.streamDiffLines( - diffLines, - instant, - data.streamId, - data.toolCallId, - ); - } else { - const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; - const fullEditorRange = new vscode.Range( - 0, - 0, - editor.document.lineCount - 1, - editor.document.lineAt(editor.document.lineCount - 1).text.length, - ); - const rangeToApplyTo = editor.selection.isEmpty - ? fullEditorRange - : editor.selection; - - await verticalDiffManager.streamEdit( - prompt, - llm, - data.streamId, - undefined, - undefined, - rangeToApplyTo, - data.text, - data.toolCallId, - ); - } + await applyManager.applyToFile(data); }); this.onWebview("showTutorial", async (msg) => { diff --git a/gui/package-lock.json b/gui/package-lock.json index 4cd481b0c..2105fc59b 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.82", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -109,7 +109,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.85", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -204,6 +204,27 @@ "node": ">=20.11.0" } }, + "../packages/config-yaml": { + "name": "@continuedev/config-yaml", + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2" + } + }, "node_modules/@adobe/css-tools": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.0.tgz", @@ -544,26 +565,9 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, - "node_modules/@continuedev/config-types": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", - "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", - "dependencies": { - "zod": "^3.23.8" - } - }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.82", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.82.tgz", - "integrity": "sha512-IscUcyDoN4DiYEdoAJRo0LcbqgHAWYIUCqNSmjRQuASY4s2Xel2iejmnCj0oHj4DXz/bAlNBLHR6lUBs9tqSDQ==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - }, - "bin": { - "config-yaml": "dist/cli.js" - } + "resolved": "../packages/config-yaml", + "link": true }, "node_modules/@emotion/is-prop-valid": { "version": "1.3.1", @@ -13776,6 +13780,7 @@ "version": "2.6.1", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz", "integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==", + "dev": true, "bin": { "yaml": "bin.mjs" }, @@ -13795,14 +13800,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/zod": { - "version": "3.24.2", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", - "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/gui/package.json b/gui/package.json index 8a28188e8..1a46aa97e 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.82", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 18c68721f..15082d35b 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -5,7 +5,6 @@ import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProvide import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; import ConfigPage from "./pages/config"; -import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; @@ -34,10 +33,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: ROUTES.CONFIG_ERROR, - element: , - }, { path: ROUTES.CONFIG, element: , diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 24003595a..839f7ed7c 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -4,9 +4,9 @@ import { useMemo } from "react"; import { themeIcons } from "seti-file-icons"; export interface FileIconProps { - filename: string; height: `${number}px`; width: `${number}px`; + filename: string; } export default function FileIcon({ filename, height, width }: FileIconProps) { diff --git a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx index 6a7075fac..c98ca6794 100644 --- a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx @@ -1,9 +1,9 @@ import { CommandLineIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { StyledActionButton } from "../.."; -import OllamaCompletedStep from "./OllamaCompletedStep"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { ToolTip } from "../../gui/Tooltip"; +import OllamaCompletedStep from "./OllamaCompletedStep"; interface OllamaModelDownloadProps { title: string; @@ -27,14 +27,18 @@ function OllamaModelDownload({ return (
-

{title}

+

{title}

{hasDownloaded ? ( ) : ( <> - +

{command}

- +
diff --git a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx index 3839ba6ad..51c782de9 100644 --- a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx @@ -39,7 +39,7 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) { return (

{downloadUrl}

- +
); case OllamaConnectionStatuses.Downloading: @@ -48,7 +48,7 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) {

Checking for connection to Ollama at http://localhost:11434

- +
); case OllamaConnectionStatuses.Connected: diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index daa064ea2..69eed3ffb 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import { useAuth } from "../../../context/Auth"; import { useAppSelector } from "../../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; import Alert from "../../gui/Alert"; @@ -20,12 +21,21 @@ interface OnboardingCardProps { export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); + const auth = useAuth(); const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); if (getLocalStorage("onboardingStatus") === undefined) { setLocalStorage("onboardingStatus", "Started"); } + function onGetStarted() { + auth.login(true).then((success) => { + if (success) { + onboardingCard.close(isDialog); + } + }); + } + return ( - By choosing this option, Continue will be configured by a local{" "} - config.yaml file. If - you're just looking to use Ollama and still want to manage your - configuration through Continue, click{" "} - setCurrentTab("main")}> + By choosing this option, Continue will be configured by a local + config.yaml file. If you're just looking to use Ollama and still + want to manage your configuration through Continue, click{" "} + here diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx index ab197b3d4..c5590e7d8 100644 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ b/gui/src/components/OnboardingCard/platform/tabs/main.tsx @@ -96,7 +96,7 @@ export default function MainTab({ ) : ( -
+
Or, remain local
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 0f1e05da0..7e99f430d 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -6,13 +6,12 @@ import { LOCAL_ONBOARDING_PROVIDER_TITLE, } from "core/config/onboarding"; import { useContext, useEffect, useState } from "react"; -import { Button } from "../.."; +import { Button, ButtonSubtext } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { updateSelectedModelByRole } from "../../../redux/thunks"; -import AddModelButtonSubtext from "../../AddModelButtonSubtext"; import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; @@ -102,10 +101,42 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { return () => clearInterval(intervalId); }, []); + const onClickSubmitOnboarding = () => { + submitOnboarding(); + + if (isDialog) { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + } + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: LOCAL_ONBOARDING_CHAT_TITLE, + }), + ); + }; + + const onClickSkip = () => { + submitOnboarding(); + + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + + if (isDialog) { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + } + }; + return (
-

Install Ollama

+

+ Install Ollama +

@@ -129,28 +160,17 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) {
- + + + Skip and configure manually + +
); diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 405182086..4ecf299b7 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -4,11 +4,13 @@ import { ChevronLeftIcon, CubeIcon, EllipsisHorizontalIcon, + ExclamationTriangleIcon, PencilIcon, Squares2X2Icon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; -import { vscBadgeBackground, vscBadgeForeground } from "../.."; +import { vscBadgeForeground } from "../.."; +import { useAppSelector } from "../../../redux/hooks"; import { fontSize } from "../../../util"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; @@ -36,9 +38,14 @@ const sections: Section[] = [ { id: "prompts", tooltip: "Prompts", icon: ChatBubbleLeftIcon }, { id: "tools", tooltip: "Tools", icon: WrenchScrewdriverIcon }, { id: "mcp", tooltip: "MCP", icon: Squares2X2Icon }, + { id: "error", tooltip: "Errors", icon: ExclamationTriangleIcon }, ]; -function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) { +function BlockSettingsToolbarIcon( + props: BlockSettingsToolbarIcon & { sectionId?: string }, +) { + const isErrorSection = props.sectionId === "error"; + return (
store.config.configError); + const handleEllipsisClick = () => { if (isToolbarExpanded) { setSelectedSection(null); @@ -95,6 +109,12 @@ export function BlockSettingsTopToolbar() { toggleToolbar(); }; + const visibleSections = sections.filter( + (section) => + section.id !== "error" || + (section.id === "error" && configError && configError?.length > 0), + ); + return (
@@ -109,13 +129,13 @@ export function BlockSettingsTopToolbar() { onClick={handleEllipsisClick} />
- {sections.map((section) => ( + {visibleSections.map((section) => (
-
+
diff --git a/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx b/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx new file mode 100644 index 000000000..d4d01141c --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx @@ -0,0 +1,40 @@ +import { + ExclamationCircleIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../../../redux/hooks"; + +export function ErrorSection() { + const configError = useAppSelector((state) => state.config.configError); + + const sortedErrors = configError + ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) + : []; + + return ( +
+
    + {sortedErrors.map((error, index) => ( +
  • + {error.fatal ? ( + + ) : ( + + )} +

    + {error.fatal ? "Fatal Error:" : "Warning:"}{" "} + {error.message} +

    +
  • + ))} +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx index 6885870df..61eb0790a 100644 --- a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -60,7 +60,7 @@ export function ExploreBlocksButton(props: { blockType: string }) { }} >
- + {text}
diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 0465e1f74..85f72078f 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,6 +1,7 @@ import { useLump } from "../LumpContext"; import { ContextSection } from "./ContextSection"; import DocsSection from "./docs/DocsSection"; +import { ErrorSection } from "./ErrorSection"; import { MCPSection } from "./MCPSection"; import { ModelsSection } from "./ModelsSection"; import { PromptsSection } from "./PromptsSection"; @@ -28,6 +29,8 @@ export function SelectedSection() { return ; case "mcp": return ; + case "error": + return ; default: return null; } diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index db923f59b..b7f3d724c 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -134,10 +134,10 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { useEffect(() => { const resizeObserver = new ResizeObserver(() => { - setContentDims({ - width: contentRef.current?.scrollWidth ?? 0, - height: contentRef.current?.scrollHeight ?? 0, - }); + setContentDims(prevValue => ({ + width: contentRef.current?.scrollWidth ?? prevValue.width, + height: contentRef.current?.scrollHeight ?? prevValue.height, + })); }); if (contentRef.current) { diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index eb63e0ee9..bb153f62a 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -42,7 +42,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const isRangeInFile = name.includes(" (") && name.endsWith(")"); if (isRangeInFile) { - const rif = ctxItemToRifWithContents(contextItem); + const rif = ctxItemToRifWithContents(contextItem, true); ideMessenger.ide.showLines( rif.filepath, rif.range.start.line, diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx deleted file mode 100644 index 7e42dfb1c..000000000 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ /dev/null @@ -1,138 +0,0 @@ -import { - ArrowLeftEndOnRectangleIcon, - CommandLineIcon, - PlayIcon, -} from "@heroicons/react/24/outline"; -import { useContext, useRef, useState } from "react"; -import { v4 as uuidv4 } from "uuid"; -import { - defaultBorderRadius, - vscCommandCenterInactiveBorder, - vscEditorBackground, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { useAppSelector } from "../../redux/hooks"; -import { selectUIConfig } from "../../redux/slices/configSlice"; -import { isJetBrains } from "../../util"; -import { CopyIconButton } from "../gui/CopyIconButton"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { getTerminalCommand, isTerminalCodeBlock } from "./utils"; - -interface StepContainerPreActionButtonsProps { - language: string | null; - codeBlockContent: string; - codeBlockIndex: number; - children: any; -} - -export default function StepContainerPreActionButtons({ - language, - codeBlockContent, - codeBlockIndex, - children, -}: StepContainerPreActionButtonsProps) { - const [hovering, setHovering] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const uiConfig = useAppSelector(selectUIConfig); - const streamIdRef = useRef(null); - const nextCodeBlockIndex = useAppSelector( - (state) => state.session.codeBlockApplyStates.curIndex, - ); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const isBottomToolbarPosition = - uiConfig?.codeBlockToolbarPosition == "bottom"; - - const toolTipPlacement = isBottomToolbarPosition ? "top" : "bottom"; - - const shouldRunTerminalCmd = - !isJetBrains() && isTerminalCodeBlock(language, codeBlockContent); - const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; - - if (streamIdRef.current === null) { - streamIdRef.current = uuidv4(); - } - - function onClickApply() { - if (!streamIdRef.current) { - return; - } - - ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, - text: codeBlockContent, - }); - } - - async function onClickRunTerminal(): Promise { - if (shouldRunTerminalCmd) { - return ideMessenger.ide.runCommand(getTerminalCommand(codeBlockContent)); - } - } - - // Handle apply keyboard shortcut - useWebviewListener( - "applyCodeFromChat", - async () => onClickApply(), - [isNextCodeBlock, codeBlockContent], - !isNextCodeBlock, - ); - - return ( -
setHovering(true)} - onMouseLeave={() => setHovering(false)} - className="bg-vsc-editor-background relative my-2.5" - style={{ - border: `1px solid ${vscCommandCenterInactiveBorder}`, - borderRadius: defaultBorderRadius, - }} - > -
{children}
- {hovering && !isStreaming && ( -
- {shouldRunTerminalCmd && ( - - - - )} - - - - - ideMessenger.post("insertAtCursor", { text: codeBlockContent }) - } - tooltipPlacement={toolTipPlacement} - > - - - -
- )} -
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 0da1c5c7f..2c4e286c7 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -25,7 +25,7 @@ export default function ApplyActions(props: ApplyActionsProps) { setShowApplied(true); const timer = setTimeout(() => { setShowApplied(false); - }, 5_000); + }, 3_000); return () => clearTimeout(timer); } }, [isClosed, isSuccessful]); @@ -37,12 +37,12 @@ export default function ApplyActions(props: ApplyActionsProps) { const applyButton = (text: string) => ( @@ -52,33 +52,35 @@ export default function ApplyActions(props: ApplyActionsProps) { case "streaming": return (
- - Applying changes + + Applying
); case "done": return ( -
+
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`} {` remaining`} - - - +
+ + + - - - + + + +
); case "closed": @@ -87,7 +89,7 @@ export default function ApplyActions(props: ApplyActionsProps) { return ( Applied - + ); } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx index 195615380..2167afc41 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx @@ -1,6 +1,6 @@ import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline"; +import { lightGray } from "../.."; import useCopy from "../../../hooks/useCopy"; -import { lightGray, vscForeground } from "../.."; interface CopyButtonProps { text: string; @@ -11,23 +11,17 @@ export default function CopyButton({ text }: CopyButtonProps) { return (
{copied ? ( - <> - - Copied - + ) : ( - <> - - Copy - + )}
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index ee46ccee8..7b204190b 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -1,41 +1,25 @@ -import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; import { getLastNPathParts } from "core/util/uri"; -import { useContext } from "react"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; import FileIcon from "../../FileIcon"; export interface FileInfoProps { - relativeFilepath: string; + filepath: string; + onClick: () => void; range?: string; } -const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { - const ideMessenger = useContext(IdeMessengerContext); - - async function onClickFileName() { - const fileUri = await inferResolvedUriFromRelativePath( - relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("showFile", { - filepath: fileUri, - }); - } - +export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => { return (
- +
- {getLastNPathParts(relativeFilepath, 1)} + {getLastNPathParts(filepath, 1)} {range && ` ${range}`}
); }; - -export default FileInfo; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx new file mode 100644 index 000000000..7d56e012b --- /dev/null +++ b/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx @@ -0,0 +1,25 @@ +import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; +import { lightGray } from "../.."; + +/** + * Button that inserts code at the current cursor position + */ +interface InsertButtonProps { + onInsert: () => void; +} + +export default function InsertButton({ onInsert }: InsertButtonProps) { + return ( +
+
+ +
+
+ ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index c00290e4c..0397603f3 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -1,7 +1,6 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; -import { debounce } from "lodash"; -import { useContext, useEffect, useRef, useState } from "react"; +import { useContext, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, @@ -11,17 +10,17 @@ import { import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; -import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { selectApplyStateByStreamId, selectIsInEditMode, } from "../../../redux/slices/sessionSlice"; import { getFontSize } from "../../../util"; -import { childrenToText, isTerminalCodeBlock } from "../utils"; +import { isTerminalCodeBlock } from "../utils"; import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; -import FileInfo from "./FileInfo"; +import { FileInfo } from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; +import InsertButton from "./InsertButton"; import RunInTerminalButton from "./RunInTerminalButton"; const TopDiv = styled.div` @@ -50,7 +49,7 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>` export interface StepContainerPreToolbarProps { codeBlockContent: string; language: string | null; - relativeFilepath: string; + relativeFilepath?: string; isGeneratingCodeBlock: boolean; codeBlockIndex: number; // To track which codeblock we are applying codeBlockStreamId: string; @@ -60,47 +59,91 @@ export interface StepContainerPreToolbarProps { disableManualApply?: boolean; } -export default function StepContainerPreToolbar( - props: StepContainerPreToolbarProps, -) { +export default function StepContainerPreToolbar({ + codeBlockContent, + language, + relativeFilepath, + isGeneratingCodeBlock, + codeBlockIndex, + codeBlockStreamId, + range, + children, + expanded, + disableManualApply, +}: StepContainerPreToolbarProps) { const ideMessenger = useContext(IdeMessengerContext); - const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isInEditMode = useAppSelector(selectIsInEditMode); const [isExpanded, setIsExpanded] = useState( - props.expanded ?? (isInEditMode ? false : true), + expanded ?? (isInEditMode ? false : true), ); - const [codeBlockContent, setCodeBlockContent] = useState(""); + // We store the resolved file URI to ensure we use the same file when + // accepting/rejecting diffs, even if no `relativeFilepath` is provided + const [resolvedFileUri, setResolvedFileUri] = useState( + undefined, + ); const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, props.codeBlockStreamId), + selectApplyStateByStreamId(state, codeBlockStreamId), ); - const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; - const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath); + const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; + const hasFileExtension = + relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); - const selectedChatModel = useAppSelector(selectSelectedChatModel); + const displayFilepath = relativeFilepath ?? resolvedFileUri; + + async function getFileUri() { + // If we've already resolved a file URI (from clicking apply), use that + if (resolvedFileUri) { + return resolvedFileUri; + } + + // If a relative filepath was provided, try to resolve it + if (relativeFilepath) { + return await inferResolvedUriFromRelativePath( + relativeFilepath, + ideMessenger.ide, + ); + } + + // If no filepath was provided, get the current file + const currentFile = await ideMessenger.ide.getCurrentFile(); + if (currentFile) { + return currentFile.path; + } + + return undefined; + } async function onClickApply() { - if (!selectedChatModel) { + const fileUri = await getFileUri(); + if (!fileUri) { + ideMessenger.ide.showToast( + "error", + "Could not resolve filepath to apply changes", + ); + return; } - let fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); + setResolvedFileUri(fileUri); ideMessenger.post("applyToFile", { - streamId: props.codeBlockStreamId, + streamId: codeBlockStreamId, filepath: fileUri, text: codeBlockContent, }); } + function onClickInsertAtCursor() { + ideMessenger.post("insertAtCursor", { text: codeBlockContent }); + } + + // TODO: This logic should be moved to a thunk // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", @@ -109,64 +152,42 @@ export default function StepContainerPreToolbar( !isNextCodeBlock, ); - useEffect(() => { - if (codeBlockContent === "") { - setCodeBlockContent(childrenToText(props.children.props.children)); - } else { - const debouncedEffect = debounce(() => { - setCodeBlockContent(childrenToText(props.children.props.children)); - }, 100); - - debouncedEffect(); - - return () => { - debouncedEffect.cancel(); - }; + async function handleDiffAction(action: "accept" | "reject") { + const filepath = await getFileUri(); + if (!filepath) { + ideMessenger.ide.showToast( + "error", + `Could not resolve filepath to ${action} changes`, + ); + return; } - }, [props.children, codeBlockContent]); - // useEffect(() => { - // const hasCompletedGenerating = - // wasGeneratingRef.current && !isGeneratingCodeBlock; - - // wasGeneratingRef.current = isGeneratingCodeBlock; - // if (hasCompletedGenerating) { - // if (props.autoApply) { - // onClickApply(); - // } - // } - // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); - - async function onClickAcceptApply() { - const fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("acceptDiff", { - filepath: fileUri, - streamId: props.codeBlockStreamId, + ideMessenger.post(`${action}Diff`, { + filepath, + streamId: codeBlockStreamId, }); + + setResolvedFileUri(undefined); } - async function onClickRejectApply() { - const fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("rejectDiff", { - filepath: fileUri, - streamId: props.codeBlockStreamId, - }); - } + function onClickFilename() { + if (resolvedFileUri) { + ideMessenger.post("showFile", { + filepath: resolvedFileUri, + }); + } - function onClickExpand() { - setIsExpanded(!isExpanded); + if (relativeFilepath) { + ideMessenger.post("showFile", { + filepath: relativeFilepath, + }); + } } // We want until there is an extension in the filepath to avoid rendering - // an incomplete filepath - if (!hasFileExtension) { - return props.children; + // an incomplete filepath + if (relativeFilepath && !hasFileExtension) { + return children; } return ( @@ -174,35 +195,42 @@ export default function StepContainerPreToolbar(
setIsExpanded(!isExpanded)} className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${ isExpanded ? "rotate-0" : "-rotate-90" }`} /> - + {displayFilepath ? ( + + ) : ( + {language} + )}
-
- {props.isGeneratingCodeBlock ? ( +
+ {isGeneratingCodeBlock ? ( ) : ( <> - - {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - + + + + {isTerminalCodeBlock(language, codeBlockContent) ? ( + ) : ( handleDiffAction("accept")} + onClickReject={() => handleDiffAction("reject")} /> )} @@ -211,13 +239,7 @@ export default function StepContainerPreToolbar( {isExpanded && ( -
- {props.children} -
+
{children}
)} ); diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 6af2f68d5..3f7c82bca 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -22,7 +22,6 @@ import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; @@ -301,6 +300,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const preChildProps = preProps?.children?.[0]?.props ?? {}; const { className, range } = preChildProps; + const relativeFilePath = preChildProps["data-relativefilepath"]; const codeBlockContent = preChildProps["data-codeblockcontent"]; @@ -310,22 +310,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const language = getLanguageFromClassName(className); - if (!relativeFilePath) { - return ( - - - - ); - } - const isGeneratingCodeBlock = preChildProps["data-islastcodeblock"] && isLastItemRef.current && - !isStreamingRef.current; + isStreamingRef.current; if (codeblockState.current[codeBlockIndex] === undefined) { codeblockState.current[codeBlockIndex] = { @@ -337,7 +325,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( isGeneratingCodeBlock; } - // We use a custom toolbar for codeblocks in the step container return ( - + {modelSelectTitle(selectedChatModel) || "Select model"}
-
+
- +
Create your first assistant @@ -278,7 +278,7 @@ export default function AssistantSelect() {
{selectedProfile.title} @@ -291,7 +291,7 @@ export default function AssistantSelect() { -
+
Assistants
- +
@@ -375,7 +375,7 @@ export default function AssistantSelect() { {currentOrg?.iconUrl ? ( ) : ( diff --git a/gui/src/pages/config-error/index.tsx b/gui/src/pages/config-error/index.tsx deleted file mode 100644 index 7bd3a3050..000000000 --- a/gui/src/pages/config-error/index.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { - ArrowLeftIcon, - ExclamationCircleIcon, - ExclamationTriangleIcon, -} from "@heroicons/react/24/outline"; -import { useNavigate } from "react-router-dom"; -import { vscBackground } from "../../components"; -import { useAppSelector } from "../../redux/hooks"; -import { ROUTES } from "../../util/navigation"; - -export default function ConfigErrorPage() { - const navigate = useNavigate(); - const configError = useAppSelector((state) => state.config.configError); - - const sortedErrors = configError - ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) - : []; - - return ( -
-
navigate(ROUTES.HOME)} - className="sticky top-0 m-0 flex cursor-pointer items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0" - style={{ - backgroundColor: vscBackground, - }} - > - - Chat -
- -
-
-

Config Errors

-

- Please resolve the following errors in your assistant configuration. -

-
- {sortedErrors.length > 0 ? ( -
    - {sortedErrors.map((error, index) => ( -
  • - {error.fatal ? ( - - ) : ( - - )} -

    - - {error.fatal ? "Fatal Error:" : "Warning:"} - {" "} - {error.message} -

    -
  • - ))} -
- ) : ( -

- No configuration errors found. -

- )} -
-
-
-
- ); -} diff --git a/gui/src/pages/config/KeyboardShortcuts.tsx b/gui/src/pages/config/KeyboardShortcuts.tsx index 4ac0919c5..4456bf45c 100644 --- a/gui/src/pages/config/KeyboardShortcuts.tsx +++ b/gui/src/pages/config/KeyboardShortcuts.tsx @@ -1,192 +1,130 @@ import { useMemo } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscForeground, -} from "../../components"; -import { ToolTip } from "../../components/gui/Tooltip"; -import { getPlatform, isJetBrains } from "../../util"; - -const StyledKeyDiv = styled.div` - border: 0.5px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 2px; - color: ${vscForeground}; - - width: 16px; - height: 16px; - - display: flex; - justify-content: center; - align-items: center; -`; - -const keyToName: { [key: string]: string } = { - "⌘": "Cmd", - "⌃": "Ctrl", - "⇧": "Shift", - "⏎": "Enter", - "⌫": "Backspace", - "⌥": "Option", - "⎇": "Alt", -}; - -function KeyDiv({ text }: { text: string }) { - return ( - <> - - {text} - - - - {keyToName[text]} - - - ); -} +import Shortcut from "../../components/gui/Shortcut"; +import { isJetBrains } from "../../util"; interface KeyboardShortcutProps { - mac: string; - windows: string; + shortcut: string; description: string; + isEven: boolean; } function KeyboardShortcut(props: KeyboardShortcutProps) { - const shortcut = getPlatform() === "mac" ? props.mac : props.windows; return ( -
- {props.description}: -
- {shortcut.split(" ").map((key, i) => { - return ; - })} +
+
+ {props.description}: +
+
+ {props.shortcut}
); } -const vscodeShortcuts: KeyboardShortcutProps[] = [ +// Shortcut strings will be rendered correctly based on the platform by the Shortcut component +const vscodeShortcuts: Omit[] = [ { - mac: "⌘ '", - windows: "⌃ '", + shortcut: "cmd '", description: "Toggle Selected Model", }, { - mac: "⌘ I", - windows: "⌃ I", + shortcut: "cmd I", description: "Edit highlighted code", }, { - mac: "⌘ L", - windows: "⌃ L", + shortcut: "cmd L", description: "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⌫", - windows: "⌃ ⌫", + shortcut: "cmd backspace", description: "Cancel response", }, { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", + shortcut: "cmd shift I", description: "Toggle inline edit focus", }, { - mac: "⌘ ⇧ L", - windows: "⌃ ⇧ L", + shortcut: "cmd shift L", description: "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⇧ R", - windows: "⌃ ⇧ R", + shortcut: "cmd shift R", description: "Debug Terminal", }, { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", + shortcut: "cmd shift backspace", description: "Reject Diff", }, { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", + shortcut: "cmd shift enter", description: "Accept Diff", }, { - mac: "⌥ ⌘ N", - windows: "Alt ⌃ N", + shortcut: "alt cmd N", description: "Reject Top Change in Diff", }, { - mac: "⌥ ⌘ Y", - windows: "Alt ⌃ Y", + shortcut: "alt cmd Y", description: "Accept Top Change in Diff", }, { - mac: "⌘ K ⌘ A", - windows: "⌃ K ⌃ A", + shortcut: "cmd K cmd A", description: "Toggle Autocomplete Enabled", }, { - mac: "⌘ K ⌘ M", - windows: "⌃ K ⌃ M", + shortcut: "cmd K cmd M", description: "Toggle Full Screen", }, ]; -const jetbrainsShortcuts: KeyboardShortcutProps[] = [ +const jetbrainsShortcuts: Omit[] = [ { - mac: "⌘ '", - windows: "⌃ '", + shortcut: "cmd '", description: "Toggle Selected Model", }, { - mac: "⌘ I", - windows: "⌃ I", + shortcut: "cmd I", description: "Edit highlighted code", }, { - mac: "⌘ J", - windows: "⌃ J", + shortcut: "cmd J", description: "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⌫", - windows: "⌃ ⌫", + shortcut: "cmd backspace", description: "Cancel response", }, { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", + shortcut: "cmd shift I", description: "Toggle inline edit focus", }, { - mac: "⌘ ⇧ J", - windows: "⌃ ⇧ J", + shortcut: "cmd shift J", description: "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", + shortcut: "cmd shift backspace", description: "Reject Diff", }, { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", + shortcut: "cmd shift enter", description: "Accept Diff", }, { - mac: "⌥ ⇧ J", - windows: "Alt ⇧ J", + shortcut: "alt shift J", description: "Quick Input", }, { - mac: "⌥ ⌘ J", - windows: "Alt ⌃ J", + shortcut: "alt cmd J", description: "Toggle Sidebar", }, ]; @@ -197,16 +135,16 @@ function KeyboardShortcuts() { }, []); return ( -
-

Keyboard shortcuts

-
+
+

Keyboard shortcuts

+
{shortcuts.map((shortcut, i) => { return ( ); })} @@ -216,3 +154,4 @@ function KeyboardShortcuts() { } export default KeyboardShortcuts; + diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 0ffd577c1..40db6fd8c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -54,7 +54,6 @@ import { } from "../../util/freeTrial"; import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; -import ConfigErrorIndicator from "./ConfigError"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; @@ -436,7 +435,6 @@ export function Chat() {
)}
-
{hasPendingApplies && isSingleRangeEditOrInsertion && ( diff --git a/gui/src/pages/gui/ConfigError.tsx b/gui/src/pages/gui/ConfigError.tsx index 8bab2c3c9..ee85046f1 100644 --- a/gui/src/pages/gui/ConfigError.tsx +++ b/gui/src/pages/gui/ConfigError.tsx @@ -1,8 +1,8 @@ +import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; import { useLocation, useNavigate } from "react-router-dom"; import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip"; -import { ROUTES } from "../../util/navigation"; -import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; +import { ROUTES } from "../../util/navigation"; const ConfigErrorIndicator = () => { const configError = useAppSelector((store) => store.config.configError); @@ -25,7 +25,7 @@ const ConfigErrorIndicator = () => { text="Config error" onClick={onClickError} > - + ); }; diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 45396dc23..e3b0002e1 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -11,9 +11,9 @@ export function CreateFile(props: CreateFileToolCallProps) { return props.relativeFilepath ? ( ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 80927e6e7..f1592a7fe 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -29,9 +29,9 @@ export function EditFile(props: EditToolCallProps) { return ( <> diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 35fc0e54f..4bb104cce 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -9,7 +9,7 @@ interface RunTerminalCommandToolCallProps { export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { return ( ); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index e79bcdf85..c5442da55 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -85,7 +85,10 @@ export const streamResponseThunk = createAsyncThunk< // Construct messages from updated history const updatedHistory = getState().session.history; - const messages = constructMessages([...updatedHistory]); + const messages = constructMessages( + [...updatedHistory], + selectedChatModel?.baseChatSystemMessage, + ); posthog.capture("step run", { step_name: "User Input", diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 3fa335d8b..9cb6a657f 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -59,7 +59,10 @@ export const streamResponseAfterToolCall = createAsyncThunk< dispatch(setActive()); const updatedHistory = getState().session.history; - const messages = constructMessages([...updatedHistory]); + const messages = constructMessages( + [...updatedHistory], + selectedChatModel?.baseChatSystemMessage, + ); unwrapResult(await dispatch(streamNormalInput({ messages }))); }), ); diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index fe2b8c0e4..f376aa2bc 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -43,6 +43,7 @@ module.exports = { "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)", "list-active-foreground": "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))", + badge: "var(--vscode-badge-background, #1bbe84)", }, }, }, diff --git a/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js index eee0aa7c5..d2920d6af 100644 --- a/manual-testing-sandbox/test.js +++ b/manual-testing-sandbox/test.js @@ -7,7 +7,6 @@ class Calculator { this.result += number; return this; } - subtract(number) { return this; } diff --git a/package-lock.json b/package-lock.json index 06f811afa..02af18a66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "continue", + "name": "continue-fork", "lockfileVersion": 3, "requires": true, "packages": { diff --git a/packages/config-types/package-lock.json b/packages/config-types/package-lock.json index 6e6f16916..6449198ab 100644 --- a/packages/config-types/package-lock.json +++ b/packages/config-types/package-lock.json @@ -1,20 +1,31 @@ { "name": "@continuedev/config-types", - "version": "1.0.13", + "version": "1.0.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-types", - "version": "1.0.13", + "version": "1.0.14", "license": "Apache-2.0", "dependencies": { - "zod": "^3.23.8" + "zod": "^3.24.2" }, "devDependencies": { + "@types/node": "^20.11.19", "typescript": "^5.5.2" } }, + "node_modules/@types/node": { + "version": "20.17.30", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.30.tgz", + "integrity": "sha512-7zf4YyHA+jvBNfVrk2Gtvs6x7E8V+YDW05bNfG2XkWDJfYRXrTiP/DsB2zSYTaHX0bGIujTBQdMVAhb+j7mwpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, "node_modules/typescript": { "version": "5.5.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.2.tgz", @@ -28,10 +39,18 @@ "node": ">=14.17" } }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "license": "MIT" + }, "node_modules/zod": { - "version": "3.23.8", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", - "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "version": "3.24.2", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", + "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", + "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/packages/config-types/package.json b/packages/config-types/package.json index 5c420223f..2cccfe1ab 100644 --- a/packages/config-types/package.json +++ b/packages/config-types/package.json @@ -12,9 +12,10 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "devDependencies": { + "@types/node": "^20.11.19", "typescript": "^5.5.2" }, "dependencies": { "zod": "^3.24.2" } -} +} \ No newline at end of file diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index ff3f6bec3..2334b4c7c 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -56,6 +56,11 @@ export const embedOptionsSchema = z.object({ }); export type EmbedOptions = z.infer; +export const chatOptionsSchema = z.object({ + baseSystemMessage: z.string().optional(), +}); +export type ChatOptions = z.infer; + /** Prompt templates use Handlebars syntax */ const promptTemplatesSchema = z.object({ apply: z.string().optional(), @@ -73,6 +78,7 @@ const baseModelFields = { defaultCompletionOptions: completionOptionsSchema.optional(), requestOptions: requestOptionsSchema.optional(), embedOptions: embedOptionsSchema.optional(), + chatOptions: chatOptionsSchema.optional(), promptTemplates: promptTemplatesSchema.optional(), env: z .record(z.string(), z.union([z.string(), z.boolean(), z.number()]))