diff --git a/.continue/rules/colors.yaml b/.continue/rules/colors.yaml new file mode 100644 index 000000000..8ca60672e --- /dev/null +++ b/.continue/rules/colors.yaml @@ -0,0 +1,27 @@ +name: GUI +version: 0.0.1 +schema: v1 +rules: + - name: Extension Color Themes + rule: | + When adding colors to components, use tailwind color classes. + Do NOT use explicit colors like text-gray-400. Instead, use theme colors. + + The common available theme colors are: + - For normal text: foreground, description, description-muted + - For other text, icons, etc: success, warning, error, accent, link + - For general components background, border, border-focus + - For specific components: + - Button: primary, primary-foreground, primary-hover, secondary, secondary-foreground, secondary-hover + - Input: input, input-foreground, input-border, input-placeholder + - Badge: badge, badge-foreground + - List/Dropdown items: list-hover, list-active, list-active-foreground + - Code Editor: editor, editor-foreground + + Any of these colors can be used in tailwind e.g. bg-primary, text-success, border-error, hover:bg-list-hover, etc. + globs: "gui/**/*.tsx" +# Excluding the following less-used colors: +# Command (only used by tip-tap): command, command-foreground, command-border, command-border-focus +# Find widget colors: find-match, find-match-selected +# table-oddRow + diff --git a/.github/workflows/metrics.yaml b/.github/workflows/metrics.yaml new file mode 100644 index 000000000..1ee476aaf --- /dev/null +++ b/.github/workflows/metrics.yaml @@ -0,0 +1,75 @@ +name: Monthly issue metrics +on: + workflow_dispatch: + schedule: + # Runs every Monday at 9:00 AM PST (17:00 UTC) + - cron: "0 17 * * 1" + + push: + branches: + - nate/metrics-action + +permissions: + contents: read + +jobs: + build: + name: issue metrics + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: read + steps: + - name: Get dates for last month + shell: bash + run: | + # Calculate the first day of the previous month + first_day=$(date -d "last month" +%Y-%m-01) + + # Calculate the last day of the previous month + last_day=$(date -d "$first_day +1 month -1 day" +%Y-%m-%d) + + #Set an environment variable with the date range + echo "$first_day..$last_day" + echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV" + + - name: Run issue-metrics tool + uses: github/issue-metrics@v3 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SEARCH_QUERY: 'repo:continuedev/continue created:${{ env.last_month }} -reason:"not planned"' + + - name: Read metrics file content + id: read-metrics + run: | + content=$(cat ./issue_metrics.md) + # This prepares the content in a way that can be used in GitHub Actions + content="${content//'%'/'%25'}" + content="${content//$'\n'/'%0A'}" + # content="${content//$'\r'/'%0D'}" + echo "metrics_content=$content" >> "$GITHUB_OUTPUT" + + - name: Post a message in a channel + uses: slackapi/slack-github-action@v2.1.0 + with: + webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }} + webhook-type: incoming-webhook + payload: | + text: "Issue / PR Metrics Report" + blocks: + - type: "header" + text: + type: "plain_text" + text: "Monthly Issue Metrics Report" + emoji: true + - type: "section" + text: + type: "mrkdwn" + text: | + ${{ steps.read-metrics.outputs.metrics_content }} + + - name: Upload metrics report as artifact + uses: actions/upload-artifact@v4 + with: + name: issue-metrics-report + path: ./issue_metrics.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4f30e3e00..1b981a612 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,35 +3,36 @@ ## Table of Contents - [Contributing to Continue](#contributing-to-continue) - - [Table of Contents](#table-of-contents) + - [Table of Contents](#table-of-contents) - [❤️ Ways to Contribute](#️-ways-to-contribute) - - [👋 Continue Contribution Ideas](#-continue-contribution-ideas) - - [🐛 Report Bugs](#-report-bugs) - - [✨ Suggest Enhancements](#-suggest-enhancements) - - [📖 Updating / Improving Documentation](#-updating--improving-documentation) - - [Running the Documentation Server Locally](#running-the-documentation-server-locally) - - [Method 1: NPM Script](#method-1-npm-script) - - [Method 2: VS Code Task](#method-2-vs-code-task) - - [🧑‍💻 Contributing Code](#-contributing-code) - - [Environment Setup](#environment-setup) - - [Pre-requisites](#pre-requisites) - - [Fork the Continue Repository](#fork-the-continue-repository) - - [VS Code](#vs-code) - - [Debugging](#debugging) - - [JetBrains](#jetbrains) - - [Our Git Workflow](#our-git-workflow) - - [Development workflow](#development-workflow) - - [Formatting](#formatting) - - [Testing](#testing) - - [Review Process](#review-process) - - [Getting help](#getting-help) - - [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels) - - [Adding an LLM Provider](#adding-an-llm-provider) - - [Adding Models](#adding-models) - - [📐 Continue Architecture](#-continue-architecture) - - [Continue VS Code Extension](#continue-vs-code-extension) - - [Continue JetBrains Extension](#continue-jetbrains-extension) - - [Contibutor License Agreement](#contributor-license-agreement-cla) + - [👋 Continue Contribution Ideas](#-continue-contribution-ideas) + - [🐛 Report Bugs](#-report-bugs) + - [✨ Suggest Enhancements](#-suggest-enhancements) + - [📖 Updating / Improving Documentation](#-updating--improving-documentation) + - [Running the Documentation Server Locally](#running-the-documentation-server-locally) + - [Method 1: NPM Script](#method-1-npm-script) + - [Method 2: VS Code Task](#method-2-vs-code-task) + - [🧑‍💻 Contributing Code](#-contributing-code) + - [Environment Setup](#environment-setup) + - [Pre-requisites](#pre-requisites) + - [Fork the Continue Repository](#fork-the-continue-repository) + - [VS Code](#vs-code) + - [Debugging](#debugging) + - [JetBrains](#jetbrains) + - [Our Git Workflow](#our-git-workflow) + - [Development workflow](#development-workflow) + - [Formatting](#formatting) + - [Theme Colors](#theme-colors) + - [Testing](#testing) + - [Review Process](#review-process) + - [Getting help](#getting-help) + - [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels) + - [Adding an LLM Provider](#adding-an-llm-provider) + - [Adding Models](#adding-models) + - [📐 Continue Architecture](#-continue-architecture) + - [Continue VS Code Extension](#continue-vs-code-extension) + - [Continue JetBrains Extension](#continue-jetbrains-extension) + - [Contibutor License Agreement](#contributor-license-agreement-cla) # ❤️ Ways to Contribute @@ -60,9 +61,9 @@ an enhancement are: - Create an issue - - First, check whether a similar proposal has already been made - - If not, [create an issue](https://github.com/continuedev/continue/issues) - - Please describe the enhancement in as much detail as you can, and why it would be useful + - First, check whether a similar proposal has already been made + - If not, [create an issue](https://github.com/continuedev/continue/issues) + - Please describe the enhancement in as much detail as you can, and why it would be useful - Join the [Continue Discord](https://discord.gg/NWtdYexhMs) and tell us about your idea in the `#feedback` channel @@ -140,12 +141,12 @@ nvm use 2. Start debugging: - 1. Switch to Run and Debug view - 2. Select `Launch extension` from drop down - 3. Hit play button - 4. This will start the extension in debug mode and open a new VS Code window with it installed - 1. The new VS Code window with the extension is referred to as the _Host VS Code_ - 2. The window you started debugging from is referred to as the _Main VS Code_ + 1. Switch to Run and Debug view + 2. Select `Launch extension` from drop down + 3. Hit play button + 4. This will start the extension in debug mode and open a new VS Code window with it installed + 1. The new VS Code window with the extension is referred to as the _Host VS Code_ + 2. The window you started debugging from is referred to as the _Main VS Code_ 3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which @@ -192,6 +193,22 @@ To keep the Continue codebase clean and maintainable, we expect the following fr Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings. +### Theme Colors + +Continue has a set of named theme colors that we map to extension colors and tailwind classes, which can be found in [gui/src/styles/theme.ts](gui/src/styles/theme.ts) + +Guidelines for using theme colors: + +- Use Tailwind colors whenever possible. If developing in VS Code, download the [Tailwind CSS Intellisense extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) for great suggestions +- Avoid using any explicit classes and CSS variables outside the theme (e.g. `text-yellow-400`) + +Guidelines for adding/updating theme colors: + +- Choose sensible VS Code variables to add/update in [gui/src/styles/theme.ts](gui/src/styles/theme.ts) (see [here](https://code.visualstudio.com/api/references/theme-color) and [here](https://www.notion.so/1fa1d55165f78097b551e3bc296fcf76?pvs=25) for inspiration) +- Choose sensible Jetbrains named colors to add/update in `GetTheme.kt` (flagship LLMs can give you good suggestions to try) +- Update `tailwind.config.js` if needed +- Use the Theme Test Page to check colors. This can be accessed by going to `Settings` -> `Help` -> `Theme Test Page` in dev/debug mode. + ### Testing We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on @@ -239,10 +256,10 @@ model: - [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the side bar model selection UI. To add a new model: - 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), - following the lead of the many examples near the top of the file - 2. Add the model within its provider's array - to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed) + 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), + following the lead of the many examples near the top of the file + 2. Add the model within its provider's array + to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed) - LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), @@ -264,4 +281,4 @@ We require all contributors to accept the CLA and have made it as easy as commen I have read the CLA Document and I hereby sign the CLA ``` -3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed. \ No newline at end of file +3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed. diff --git a/binary/package-lock.json b/binary/package-lock.json index bb15529ae..d12bcae7a 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -2589,9 +2589,9 @@ } }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", + "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index fb1be39bb..307368ce8 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -226,6 +226,7 @@ describe("Test Suite", () => { title: "Test Model", provider: "openai", model: "gpt-3.5-turbo", + underlyingProviderName: "openai", }; await messenger.request("config/addModel", { model, @@ -252,6 +253,7 @@ describe("Test Suite", () => { title: "Test Model", provider: "mock", model: "gpt-3.5-turbo", + underlyingProviderName: "mock", }; await messenger.request("config/addModel", { model, diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index fd9cf2923..171a6df98 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -244,7 +244,7 @@ export class CompletionProvider { prefix, suffix, prompt, - modelProvider: llm.providerName, + modelProvider: llm.underlyingProviderName, modelName: llm.model, completionOptions, cacheHit, diff --git a/core/commands/slash/http.ts b/core/commands/slash/http.ts index 7a662561c..e92c7c3f1 100644 --- a/core/commands/slash/http.ts +++ b/core/commands/slash/http.ts @@ -1,6 +1,6 @@ +import { streamResponse } from "@continuedev/fetch"; import { SlashCommand } from "../../index.js"; import { removeQuotesAndEscapes } from "../../util/index.js"; -import { streamResponse } from "../../llm/stream.js"; const HttpSlashCommand: SlashCommand = { name: "http", diff --git a/core/config/load.ts b/core/config/load.ts index de08ecfc7..e3d83a6b6 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -627,6 +627,7 @@ async function intermediateToFinalConfig({ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { return { provider: llm.providerName, + underlyingProviderName: llm.underlyingProviderName, model: llm.model, title: llm.title ?? llm.model, apiKey: llm.apiKey, diff --git a/core/config/util.ts b/core/config/util.ts index cc187fc55..9128fc0b5 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -77,6 +77,7 @@ export function addModel( model: model.model, apiKey: model.apiKey, apiBase: model.apiBase, + maxStopWords: model.maxStopWords, defaultCompletionOptions: model.completionOptions, }; if (model.systemMessage) { diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.test.ts index 7e909fe43..b9dae9ee2 100644 --- a/core/context/mcp/MCPConnection.test.ts +++ b/core/context/mcp/MCPConnection.test.ts @@ -4,7 +4,7 @@ import MCPConnection from "./MCPConnection"; describe("MCPConnection", () => { beforeEach(() => { - jest.clearAllMocks(); + jest.restoreAllMocks(); }); describe("constructor", () => { @@ -173,12 +173,11 @@ describe("MCPConnection", () => { }); it("should handle custom connection timeout", async () => { - const conn = new MCPConnection({ ...options, timeout: 50 }); - + const conn = new MCPConnection({ ...options, timeout: 1500 }); const mockConnect = jest .spyOn(Client.prototype, "connect") .mockImplementation( - () => new Promise((resolve) => setTimeout(resolve, 10)), + () => new Promise((resolve) => setTimeout(resolve, 1000)), ); const abortController = new AbortController(); @@ -230,6 +229,38 @@ describe("MCPConnection", () => { expect(conn.errors[0]).toContain('command "test-cmd" not found'); expect(mockConnect).toHaveBeenCalled(); }); + + it.skip("should include stderr output in error message when stdio command fails", async () => { + // Clear any existing mocks to ensure we get real behavior + jest.restoreAllMocks(); + + // Use a command that will definitely fail and produce stderr output + const failingOptions = { + name: "failing-mcp", + id: "failing-id", + transport: { + type: "stdio" as const, + command: "node", + args: [ + "-e", + "console.error('Custom error message from stderr'); process.exit(1);", + ], + }, + timeout: 5000, // Give enough time for the command to run and fail + }; + + const conn = new MCPConnection(failingOptions); + const abortController = new AbortController(); + + await conn.connectClient(false, abortController.signal); + + expect(conn.status).toBe("error"); + expect(conn.errors).toHaveLength(1); + expect(conn.errors[0]).toContain("Failed to connect"); + expect(conn.errors[0]).toContain("Process output:"); + expect(conn.errors[0]).toContain("STDERR:"); + expect(conn.errors[0]).toContain("Custom error message from stderr"); + }); }); describe.skip("actually connect to Filesystem MCP", () => { diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 9ffed6321..72de75f92 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -39,6 +39,10 @@ class MCPConnection { public resources: MCPResource[] = []; private transport: Transport; private connectionPromise: Promise | null = null; + private stdioOutput: { stdout: string; stderr: string } = { + stdout: "", + stderr: "", + }; constructor(public options: MCPOptions) { this.transport = this.constructTransport(options); @@ -92,6 +96,7 @@ class MCPConnection { this.prompts = []; this.resources = []; this.errors = []; + this.stdioOutput = { stdout: "", stderr: "" }; this.abortController.abort(); this.abortController = new AbortController(); @@ -216,6 +221,20 @@ class MCPConnection { } } + // Include stdio output if available for stdio transport + if ( + this.options.transport.type === "stdio" && + (this.stdioOutput.stdout || this.stdioOutput.stderr) + ) { + errorMessage += "\n\nProcess output:"; + if (this.stdioOutput.stdout) { + errorMessage += `\nSTDOUT:\n${this.stdioOutput.stdout}`; + } + if (this.stdioOutput.stderr) { + errorMessage += `\nSTDERR:\n${this.stdioOutput.stderr}`; + } + } + this.status = "error"; this.errors.push(errorMessage); } finally { @@ -285,11 +304,20 @@ class MCPConnection { options.transport.args || [], ); - return new StdioClientTransport({ + const transport = new StdioClientTransport({ command, args, env, + stderr: "pipe", }); + + // Capture stdio output for better error reporting + + transport.stderr?.on("data", (data: Buffer) => { + this.stdioOutput.stderr += data.toString(); + }); + + return transport; case "websocket": return new WebSocketClientTransport(new URL(options.transport.url)); case "sse": diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index 66b0837ab..c860d99ee 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -26,6 +26,7 @@ const modelDescriptionSchema = z.object({ apiKey: z.string().optional(), apiBase: z.string().optional(), contextLength: z.number().optional(), + maxStopWords: z.number().optional(), template: z .enum([ "llama2", diff --git a/core/core.ts b/core/core.ts index 9ca9108df..6b5f9814e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,7 +35,6 @@ import { TTS } from "./util/tts"; import { ContextItemWithId, - DiffLine, IdeSettings, ModelDescription, RangeInFile, @@ -62,61 +61,7 @@ import { LLMLogger } from "./llm/logger"; import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; - -// This function is used for jetbrains inline edit and apply -async function* streamDiffLinesGenerator( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, -): AsyncGenerator { - const { - highlighted, - prefix, - suffix, - input, - language, - modelTitle, - includeRulesInSystemMessage, - } = msg.data; - - const { config } = await configHandler.loadConfig(); - if (!config) { - throw new Error("Failed to load config"); - } - - // Title can be an edit, chat, or apply model - // Fall back to chat - const llm = - config.modelsByRole.edit.find((m) => m.title === modelTitle) ?? - config.modelsByRole.apply.find((m) => m.title === modelTitle) ?? - config.modelsByRole.chat.find((m) => m.title === modelTitle) ?? - config.selectedModelByRole.chat; - - if (!llm) { - throw new Error("No model selected"); - } - - // rules included for edit, NOT apply - const rules = includeRulesInSystemMessage ? config.rules : undefined; - - for await (const diffLine of streamDiffLines({ - highlighted, - prefix, - suffix, - llm, - rulesToInclude: rules, - input, - language, - onlyOneInsertion: false, - overridePrompt: undefined, - })) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - yield diffLine; - } -} +import { StreamAbortManager } from "./util/abortManager"; export class Core { configHandler: ConfigHandler; @@ -132,7 +77,18 @@ export class Core { this.globalContext.get("indexingPaused") === true, ); - private abortedMessageIds: Set = new Set(); + private messageAbortControllers = new Map(); + private addMessageAbortController(id: string): AbortController { + const controller = new AbortController(); + this.messageAbortControllers.set(id, controller); + controller.signal.addEventListener("abort", () => { + this.messageAbortControllers.delete(id); + }); + return controller; + } + private abortById(messageId: string) { + this.messageAbortControllers.get(messageId)?.abort(); + } invoke( messageType: T, @@ -301,7 +257,7 @@ export class Core { }); on("abort", (msg) => { - this.abortedMessageIds.add(msg.messageId); + this.abortById(msg.data ?? msg.messageId); }); on("ping", (msg) => { @@ -470,27 +426,28 @@ export class Core { } }); - on("llm/streamChat", (msg) => - llmStreamChat( + on("llm/streamChat", (msg) => { + const abortController = this.addMessageAbortController(msg.messageId); + return llmStreamChat( this.configHandler, - this.abortedMessageIds, + abortController, msg, this.ide, this.messenger, - ), - ); + ); + }); on("llm/complete", async (msg) => { - const model = (await this.configHandler.loadConfig()).config - ?.selectedModelByRole.chat; - + const { config } = await this.configHandler.loadConfig(); + const model = config?.selectedModelByRole.chat; if (!model) { throw new Error("No chat model selected"); } + const abortController = this.addMessageAbortController(msg.messageId); const completion = await model.complete( msg.data.prompt, - new AbortController().signal, + abortController.signal, msg.data.completionOptions, ); return completion; @@ -532,9 +489,47 @@ export class Core { this.completionProvider.cancel(); }); - on("streamDiffLines", (msg) => - streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg), - ); + on("streamDiffLines", async (msg) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Failed to load config"); + } + + const { data } = msg; + + // Title can be an edit, chat, or apply model + // Fall back to chat + const llm = + config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ?? + config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ?? + config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ?? + config.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No model selected"); + } + + return streamDiffLines({ + highlighted: data.highlighted, + prefix: data.prefix, + suffix: data.suffix, + llm, + // rules included for edit, NOT apply + rulesToInclude: data.includeRulesInSystemMessage + ? config.rules + : undefined, + input: data.input, + language: data.language, + onlyOneInsertion: false, + overridePrompt: undefined, + abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time + }); + }); + + on("cancelApply", async (msg) => { + const abortManager = StreamAbortManager.getInstance(); + abortManager.clear(); + }); on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index 9cb2db915..004563cdb 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -16,6 +16,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`; export async function* recursiveStream( llm: ILLM, + abortController: AbortController, prompt: ChatMessage[] | string, prediction: Prediction | undefined, currentBuffer = "", @@ -28,7 +29,7 @@ export async function* recursiveStream( // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries if (typeof prompt === "string") { - const generator = llm.streamComplete(prompt, new AbortController().signal, { + const generator = llm.streamComplete(prompt, abortController.signal, { raw: true, prediction: undefined, reasoning: false, @@ -50,6 +51,7 @@ export async function* recursiveStream( // // TODO - Prediction capabilities lost because of partial input // yield* recursiveStream( // llm, + // abortController, // continuationPrompt, // undefined, // buffer, @@ -60,7 +62,7 @@ export async function* recursiveStream( } } } else { - const generator = llm.streamChat(prompt, new AbortController().signal, { + const generator = llm.streamChat(prompt, abortController.signal, { prediction, reasoning: false, }); @@ -90,6 +92,7 @@ export async function* recursiveStream( // await generator.return(DUD_PROMPT_LOG); // yield* recursiveStream( // llm, + // abortController, // continuationPrompt, // undefined, // buffer, diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index ff1585520..096b31d7d 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -20,6 +20,7 @@ import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; +import { StreamAbortManager } from "../util/abortManager"; import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; import { recursiveStream } from "./recursiveStream"; @@ -63,6 +64,7 @@ export async function* streamDiffLines({ highlighted, suffix, llm, + abortControllerId, input, language, onlyOneInsertion, @@ -73,12 +75,15 @@ export async function* streamDiffLines({ highlighted: string; suffix: string; llm: ILLM; + abortControllerId: string; input: string; language: string | undefined; onlyOneInsertion: boolean; overridePrompt: ChatMessage[] | undefined; rulesToInclude: RuleWithSource[] | undefined; }): AsyncGenerator { + const abortManager = StreamAbortManager.getInstance(); + const abortController = abortManager.get(abortControllerId); void Telemetry.capture( "inlineEdit", { @@ -158,7 +163,7 @@ export async function* streamDiffLines({ content: highlighted, }; - const completion = recursiveStream(llm, prompt, prediction); + const completion = recursiveStream(llm, abortController, prompt, prediction); let lines = streamLines(completion); diff --git a/core/index.d.ts b/core/index.d.ts index 51769b591..dde7bc841 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -93,6 +93,7 @@ export interface ILLM extends Omit, Required> { get providerName(): string; + get underlyingProviderName(): string; complete( prompt: string, @@ -423,7 +424,7 @@ export interface PromptLog { completion: string; } -export type MessageModes = "chat" | "edit" | "agent"; +export type MessageModes = "chat" | "agent"; export type ToolStatus = | "generating" @@ -1035,6 +1036,7 @@ export interface ModelCapability { export interface ModelDescription { title: string; provider: string; + underlyingProviderName: string; model: string; apiKey?: string; @@ -1250,6 +1252,7 @@ export interface StreamDiffLinesPayload { language: string | undefined; modelTitle: string | undefined; includeRulesInSystemMessage: boolean; + fileUri?: string; } export interface HighlightedCodePayload { @@ -1342,6 +1345,7 @@ export interface AnalyticsConfig { export interface JSONModelDescription { title: string; provider: string; + underlyingProviderName: string; model: string; apiKey?: string; apiBase?: string; diff --git a/core/llm/index.ts b/core/llm/index.ts index 96fdb319c..0d25d882c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -88,6 +88,14 @@ export abstract class BaseLLM implements ILLM { return (this.constructor as typeof BaseLLM).providerName; } + /** + * This exists because for the continue-proxy, sometimes we want to get the value of the underlying provider that is used on the server + * For example, the underlying provider should always be sent with dev data + */ + get underlyingProviderName(): string { + return this.providerName; + } + supportsFim(): boolean { return false; } @@ -332,7 +340,7 @@ export abstract class BaseLLM implements ILLM { name: "tokensGenerated", data: { model: model, - provider: this.providerName, + provider: this.underlyingProviderName, promptTokens: promptTokens, generatedTokens: generatedTokens, }, @@ -382,6 +390,9 @@ export abstract class BaseLLM implements ILLM { // Error mapping to be more helpful if (!resp.ok) { + if (resp.status === 499) { + return resp; // client side cancellation + } let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { const error = JSON.parse(text)?.error?.replace(/"/g, "'"); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 5bec42d49..b5906590a 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,7 +1,7 @@ +import { streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { static providerName = "anthropic"; @@ -213,6 +213,10 @@ class Anthropic extends BaseLLM { signal, }); + if (response.status === 499) { + return; // Aborted by user + } + if (!response.ok) { const json = await response.json(); if (json.type === "error") { diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 59554efe5..988c57ac6 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -134,10 +134,8 @@ class Asksage extends BaseLLM { body: JSON.stringify(args), }); - if (!response.ok) { - throw new Error( - `API request failed with status ${response.status}: ${response.statusText}`, - ); + if (response.status === 499) { + return ""; // Aborted by user } const data = await response.json(); @@ -167,10 +165,8 @@ class Asksage extends BaseLLM { signal, }); - if (!response.ok) { - throw new Error( - `API request failed with status ${response.status}: ${response.statusText}`, - ); + if (response.status === 499) { + return; // Aborted by user } const data = await response.json(); diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 8d18c4e3a..cba4204ef 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -1,7 +1,7 @@ +import { streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; export default class Cloudflare extends BaseLLM { static providerName = "cloudflare"; diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index ecc9c5208..b4d2c3b41 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -1,3 +1,4 @@ +import { streamJSON } from "@continuedev/fetch"; import { ChatMessage, Chunk, @@ -6,7 +7,6 @@ import { } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamJSON } from "../stream.js"; class Cohere extends BaseLLM { static providerName = "cohere"; @@ -84,6 +84,10 @@ class Cohere extends BaseLLM { signal, }); + if (resp.status === 499) { + return; // Aborted by user + } + if (options.stream === false) { const data = await resp.json(); yield { role: "assistant", content: data.text }; diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index c1453d0db..305d177e7 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -1,5 +1,5 @@ +import { streamSse } from "@continuedev/fetch"; import { CompletionOptions, LLMOptions } from "../../index.js"; -import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index cdc4f8f77..57bb18ccc 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -132,12 +132,16 @@ class Flowise extends BaseLLM { ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); const { socket, socketInfo } = await this._initializeSocket(); - const request = this.fetch(this._getChatUrl(), { + const response = await this.fetch(this._getChatUrl(), { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), signal, - }).then((res) => res.json()); + }); + + if (response.status === 499) { + return; // Aborted by user + } while (await socketInfo.hasNextToken()) { yield { role: "assistant", content: socketInfo.getCurrentMessage() }; @@ -145,7 +149,7 @@ class Flowise extends BaseLLM { if (socketInfo.error) { socket.disconnect(); try { - yield { role: "assistant", content: (await request).text }; + yield { role: "assistant", content: await response.text() }; } catch (error: any) { yield { role: "assistant", content: (error as Error).message ?? error }; } diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index ab69aff70..6ca040db0 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -1,3 +1,4 @@ +import { streamResponse } from "@continuedev/fetch"; import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; import { getHeaders } from "../../continueServer/stubs/headers.js"; import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; @@ -8,7 +9,6 @@ import { LLMOptions, } from "../../index.js"; import { BaseLLM } from "../index.js"; -import { streamResponse } from "../stream.js"; class FreeTrial extends BaseLLM { static providerName = "free-trial"; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1e3c35449..044ee6b71 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,3 +1,4 @@ +import { streamResponse } from "@continuedev/fetch"; import { v4 as uuidv4 } from "uuid"; import { AssistantChatMessage, @@ -10,7 +11,6 @@ import { } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamResponse } from "../stream.js"; import { GeminiChatContent, GeminiChatContentPart, @@ -438,6 +438,9 @@ class Gemini extends BaseLLM { body: JSON.stringify(body), signal, }); + if (response.status === 499) { + return; // Aborted by user + } const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; } diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts index 40e67b3e5..208f6fd49 100644 --- a/core/llm/llms/HuggingFaceInferenceAPI.ts +++ b/core/llm/llms/HuggingFaceInferenceAPI.ts @@ -1,6 +1,6 @@ +import { streamSse } from "@continuedev/fetch"; import { CompletionOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; class HuggingFaceInferenceAPI extends BaseLLM { static providerName = "huggingface-inference-api"; diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index c9812cca3..8a86634c8 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -1,6 +1,6 @@ +import { streamSse } from "@continuedev/fetch"; import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; class HuggingFaceTGI extends BaseLLM { private static MAX_STOP_TOKENS = 4; diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts index 2d75ca86b..385dea23c 100644 --- a/core/llm/llms/Inception.ts +++ b/core/llm/llms/Inception.ts @@ -1,5 +1,5 @@ +import { streamSse } from "@continuedev/fetch"; import { CompletionOptions, LLMOptions } from "../../index.js"; -import { streamSse } from "../stream.js"; import OpenAI from "./OpenAI.js"; diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index 4833405ae..2d849f2d7 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -1,6 +1,6 @@ +import { streamSse } from "@continuedev/fetch"; import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; class LlamaCpp extends BaseLLM { static providerName = "llama.cpp"; diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts index 732ce81cd..2235b5ac2 100644 --- a/core/llm/llms/Moonshot.ts +++ b/core/llm/llms/Moonshot.ts @@ -1,5 +1,5 @@ +import { streamSse } from "@continuedev/fetch"; import { CompletionOptions, LLMOptions } from "../../index.js"; -import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index cd312c681..16d0e9542 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -2,6 +2,7 @@ import { Mutex } from "async-mutex"; import { JSONSchema7, JSONSchema7Object } from "json-schema"; import { v4 as uuidv4 } from "uuid"; +import { streamResponse } from "@continuedev/fetch"; import { ChatMessage, ChatMessageRole, @@ -12,7 +13,6 @@ import { import { renderChatMessage } from "../../util/messageContent.js"; import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; import { BaseLLM } from "../index.js"; -import { streamResponse } from "../stream.js"; type OllamaChatMessage = { role: ChatMessageRole; @@ -457,6 +457,9 @@ class Ollama extends BaseLLM implements ModelInstaller { } if (chatOptions.stream === false) { + if (response.status === 499) { + return; // Aborted by user + } const json = (await response.json()) as OllamaChatResponse; yield convertChatMessage(json); } else { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 2297f9efd..c48349f83 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -3,6 +3,7 @@ import { ChatCompletionMessageParam, } from "openai/resources/index"; +import { streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, @@ -16,7 +17,6 @@ import { LlmApiRequestType, toChatBody, } from "../openaiTypeConverters.js"; -import { streamSse } from "../stream.js"; const NON_CHAT_MODELS = [ "text-davinci-002", @@ -352,6 +352,9 @@ class OpenAI extends BaseLLM { // Handle non-streaming response if (body.stream === false) { + if (response.status === 499) { + return; // Aborted by user + } const data = await response.json(); yield data.choices[0].message; return; diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts index cddb22b0d..d0d3e901d 100644 --- a/core/llm/llms/SiliconFlow.ts +++ b/core/llm/llms/SiliconFlow.ts @@ -1,5 +1,5 @@ +import { streamSse } from "@continuedev/fetch"; import { Chunk, CompletionOptions, LLMOptions } from "../../index.js"; -import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; import OpenAI from "./OpenAI.js"; @@ -58,7 +58,7 @@ class SiliconFlow extends OpenAI { console.warn("[SiliconFlow] rerank: query is empty"); return []; } - + if (!chunks || chunks.length === 0) { console.warn("[SiliconFlow] rerank: chunks is empty"); return []; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index cc1b70b19..1a956cf76 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,9 +1,9 @@ import { GoogleAuth } from "google-auth-library"; +import { streamResponse, streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamResponse, streamSse } from "../stream.js"; import Anthropic from "./Anthropic.js"; import Gemini from "./Gemini.js"; @@ -95,6 +95,7 @@ class VertexAI extends BaseLLM { protected async *StreamChatAnthropic( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const systemMessage = stripImages( messages.filter((m) => m.role === "system")[0]?.content ?? "", @@ -128,8 +129,13 @@ class VertexAI extends BaseLLM { ] : systemMessage, }), + signal, }); + if (response.status === 499) { + return; // Aborted by user + } + if (options.stream === false) { const data = await response.json(); yield { role: "assistant", content: data.content[0].text }; @@ -150,6 +156,7 @@ class VertexAI extends BaseLLM { private async *streamChatGemini( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const apiURL = new URL( `publishers/google/models/${options.model}:streamGenerateContent`, @@ -160,6 +167,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal, }); for await (const message of this.geminiInstance.processGeminiResponse( streamResponse(response), @@ -171,6 +179,7 @@ class VertexAI extends BaseLLM { private async *streamChatBison( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const instances = messages.map((message) => ({ prompt: message.content })); @@ -193,7 +202,11 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal, }); + if (response.status === 499) { + return; // Aborted by user + } const data = await response.json(); yield { role: "assistant", content: data.predictions[0].content }; } @@ -203,6 +216,7 @@ class VertexAI extends BaseLLM { protected async *StreamChatMistral( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const apiBase = this.apiBase!; const apiURL = new URL( @@ -228,6 +242,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal, }); for await (const chunk of streamSse(response)) { @@ -304,6 +319,9 @@ class VertexAI extends BaseLLM { }), signal, }); + if (resp.status === 499) { + return; // Aborted by user + } // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. yield (await resp.json()).predictions[0].content; @@ -323,14 +341,14 @@ class VertexAI extends BaseLLM { ? this.geminiInstance.removeSystemMessage(messages) : messages; if (this.vertexProvider === "gemini") { - yield* this.streamChatGemini(convertedMsgs, options); + yield* this.streamChatGemini(convertedMsgs, options, signal); } else if (this.vertexProvider === "mistral") { - yield* this.StreamChatMistral(messages, options); + yield* this.StreamChatMistral(messages, options, signal); } else if (this.vertexProvider === "anthropic") { - yield* this.StreamChatAnthropic(messages, options); + yield* this.StreamChatAnthropic(messages, options, signal); } else { if (options.model.includes("bison")) { - yield* this.streamChatBison(convertedMsgs, options); + yield* this.streamChatBison(convertedMsgs, options, signal); } else { throw new Error(`Unsupported model: ${options.model}`); } diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index b237b4c7e..991b09c3e 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -12,6 +12,10 @@ class Vllm extends OpenAI { } } + supportsFim(): boolean { + return false; + } + private _setupCompletionOptions() { this.fetch(this._getEndpoint("models"), { method: "GET", diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 49b2f9ce8..0c700f439 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -1,15 +1,12 @@ +import { streamResponse, streamSse } from "@continuedev/fetch"; import { ChatMessage, Chunk, CompletionOptions, LLMOptions, } from "../../index.js"; -import { - fromChatCompletionChunk, -} from "../openaiTypeConverters.js"; -import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamResponse, streamSse } from "../stream.js"; +import { fromChatCompletionChunk } from "../openaiTypeConverters.js"; let watsonxToken = { expiration: 0, @@ -86,7 +83,7 @@ class WatsonX extends BaseLLM { } _getEndpoint(endpoint: string): string { - return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}` + return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`; } static providerName = "watsonx"; @@ -182,7 +179,6 @@ class WatsonX extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - await this.updateWatsonxToken(); const stopSequences = options.stop?.slice(0, 6) ?? []; @@ -214,44 +210,38 @@ class WatsonX extends BaseLLM { payload.project_id = this.projectId; } - var response = await this.fetch(url, { + const response = await this.fetch(url, { method: "POST", headers: headers, body: JSON.stringify(payload), signal, }); - if (!response.ok || response.body === null) { - throw new Error( - "Something went wrong. No response received, check your connection", - ); - } else { - for await (const value of streamResponse(response)) { - const lines = value.split("\n"); - let generatedChunk = ""; - let generatedTextIndex = undefined; - lines.forEach((el: string) => { - // console.log(`${el}`); - if (el.startsWith("id:")) { - generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); - if (isNaN(generatedTextIndex)) { - console.error(`Unable to parse stream chunk ID: ${el}`); - } - } else if (el.startsWith("data:")) { - const dataStr = el.replace(/^data:\s+/, ""); - try { - const data = JSON.parse(dataStr); - data.results.forEach((result: any) => { - generatedChunk += result.generated_text || ""; - }); - } catch (e) { - // parsing error is expected with streaming response - // console.error(`Error parsing JSON string: ${dataStr}`, e); - } + for await (const value of streamResponse(response)) { + const lines = value.split("\n"); + let generatedChunk = ""; + let generatedTextIndex = undefined; + lines.forEach((el: string) => { + // console.log(`${el}`); + if (el.startsWith("id:")) { + generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); + if (isNaN(generatedTextIndex)) { + console.error(`Unable to parse stream chunk ID: ${el}`); } - }); - yield generatedChunk - } + } else if (el.startsWith("data:")) { + const dataStr = el.replace(/^data:\s+/, ""); + try { + const data = JSON.parse(dataStr); + data.results.forEach((result: any) => { + generatedChunk += result.generated_text || ""; + }); + } catch (e) { + // parsing error is expected with streaming response + // console.error(`Error parsing JSON string: ${dataStr}`, e); + } + } + }); + yield generatedChunk; } } @@ -267,7 +257,7 @@ class WatsonX extends BaseLLM { const headers = this._getHeaders(); const payload: any = { - messages: messages, + messages: messages, max_tokens: options.maxTokens ?? 1024, stop: stopSequences, frequency_penalty: options.frequencyPenalty || 1, @@ -281,36 +271,30 @@ class WatsonX extends BaseLLM { if (!!options.temperature) { payload.temperature = options.temperature; - } + } if (!!options.topP) { payload.top_p = options.topP; } if (!!options.tools) { payload.tools = options.tools; if (options.toolChoice) { - payload.tool_choice = options.toolChoice; + payload.tool_choice = options.toolChoice; } else { - payload.tool_choice_option = "auto"; + payload.tool_choice_option = "auto"; } } - var response = await this.fetch(url, { + const response = await this.fetch(url, { method: "POST", headers: headers, body: JSON.stringify(payload), signal, }); - if (!response.ok || response.body === null) { - throw new Error( - "Something went wrong. No response received, check your connection", - ); - } else { - for await (const value of streamSse(response)) { - const chunk = fromChatCompletionChunk(value); - if (chunk) { - yield chunk; - } + for await (const value of streamSse(response)) { + const chunk = fromChatCompletionChunk(value); + if (chunk) { + yield chunk; } } } diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 29c892bc8..d512ec2ac 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,6 +1,7 @@ import { ContinueProperties, decodeSecretLocation, + parseProxyModelName, SecretType, } from "@continuedev/config-yaml"; @@ -47,6 +48,11 @@ class ContinueProxy extends OpenAI { useLegacyCompletionsEndpoint: false, }; + get underlyingProviderName(): string { + const { provider } = parseProxyModelName(this.model); + return provider; + } + protected extraBodyProperties(): Record { const continueProperties: ContinueProperties = { apiKeyLocation: this.apiKeyLocation, @@ -83,6 +89,10 @@ class ContinueProxy extends OpenAI { } supportsFim(): boolean { + const { provider } = parseProxyModelName(this.model); + if (provider === "vllm") { + return false; + } return true; } diff --git a/core/llm/llms/test/supportsFim.test.ts b/core/llm/llms/test/supportsFim.test.ts new file mode 100644 index 000000000..6cb7525ae --- /dev/null +++ b/core/llm/llms/test/supportsFim.test.ts @@ -0,0 +1,55 @@ +import { jest } from "@jest/globals"; +import Anthropic from "../Anthropic.js"; +import Deepseek from "../Deepseek.js"; +import FunctionNetwork from "../FunctionNetwork.js"; +import Mistral from "../Mistral.js"; +import OpenAI from "../OpenAI.js"; +import ContinueProxy from "../stubs/ContinueProxy.js"; +import Vllm from "../Vllm.js"; + +// Mock the parseProxyModelName function +const mockParseProxyModelName = jest.fn(); +jest.mock("@continuedev/config-yaml", () => ({ + parseProxyModelName: mockParseProxyModelName, + decodeSecretLocation: jest.fn(), + SecretType: { NotFound: "not-found" }, +})); + +// Test cases: [LLM class, model, expected supportsFim result, description] +const testCases: [any, string, boolean, string][] = [ + [ContinueProxy, "owner/package/vllm/some-model", false, "vllm provider"], + [ContinueProxy, "owner/package/openai/gpt-4", true, "openai provider"], + [ + ContinueProxy, + "owner/package/anthropic/claude-3", + true, + "anthropic provider", + ], + [ContinueProxy, "owner/package/cohere/command-r", true, "cohere provider"], + [ + ContinueProxy, + "owner/package/unknown-provider/some-model", + true, + "unknown provider", + ], + [ContinueProxy, "owner/package/groq/llama-model", true, "groq provider"], + [Vllm, "any-model", false, "Vllm"], + [Anthropic, "claude-3-5-sonnet-latest", false, "Anthropic"], + [FunctionNetwork, "any-model", false, "FunctionNetwork"], + [OpenAI, "codestral", false, "OpenAI"], + [Mistral, "codestral", true, "Mistral"], + [Deepseek, "deepseek-chat", true, "Deepseek"], +]; + +testCases.forEach(([LLMClass, model, expectedResult, description]) => { + test(`supportsFim returns ${expectedResult} for ${description}`, () => { + const llm = new LLMClass({ + model, + apiKey: "test-key", + }); + + const result = llm.supportsFim(); + + expect(result).toBe(expectedResult); + }); +}); diff --git a/core/llm/stream.test.ts b/core/llm/stream.test.ts deleted file mode 100644 index c42604a3e..000000000 --- a/core/llm/stream.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { Readable } from "stream"; -import { streamSse } from "./stream"; - -function createMockResponse(sseLines: string[]): Response { - // Create a Readable stream that emits the SSE lines - const stream = new Readable({ - read() { - for (const line of sseLines) { - this.push(line + "\n\n"); - } - this.push(null); // End of stream - } - }) as any; - - // Minimal Response mock - return { - status: 200, - body: stream, - text: async () => "", - } as unknown as Response; -} - -describe("streamSse", () => { - it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => { - const sseLines = [ - 'data: {"foo": "bar"}', - 'data: {"baz": 42}', - 'data:[DONE]' - ]; - const response = createMockResponse(sseLines); - - const results = []; - for await (const data of streamSse(response)) { - results.push(data); - } - - expect(results).toEqual([ - { foo: "bar" }, - { baz: 42 } - ]); - }); - - it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => { - const sseLines = [ - 'data: {"foo": "bar"}', - 'data: {"baz": 42}', - 'data: [DONE]' - ]; - const response = createMockResponse(sseLines); - - const results = []; - for await (const data of streamSse(response)) { - results.push(data); - } - - expect(results).toEqual([ - { foo: "bar" }, - { baz: 42 } - ]); - }); - - it("throws on malformed JSON", async () => { - const sseLines = [ - 'data: {"foo": "bar"', - 'data:[DONE]' - ]; - const response = createMockResponse(sseLines); - - const iterator = streamSse(response)[Symbol.asyncIterator](); - await expect(iterator.next()).rejects.toThrow(/Malformed JSON/); - }); -}); diff --git a/core/llm/stream.ts b/core/llm/stream.ts index 78a4b60e3..5902ec114 100644 --- a/core/llm/stream.ts +++ b/core/llm/stream.ts @@ -1,4 +1,4 @@ -async function* toAsyncIterable( +export async function* toAsyncIterable( nodeReadable: NodeJS.ReadableStream, ): AsyncGenerator { for await (const chunk of nodeReadable) { diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 223b5b20e..c899e437f 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -8,7 +8,7 @@ import { TTS } from "../util/tts"; export async function* llmStreamChat( configHandler: ConfigHandler, - abortedMessageIds: Set, + abortController: AbortController, msg: Message, ide: IDE, messenger: IMessenger, @@ -75,52 +75,44 @@ export async function* llmStreamChat( selectedCode, config, fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), + fetchwithRequestOptions( + url, + { + ...init, + signal: abortController.signal, + }, + config.requestOptions, + ), completionOptions, }); - const checkActiveInterval = setInterval(() => { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - clearInterval(checkActiveInterval); + let next = await gen.next(); + while (!next.done) { + if (abortController.signal.aborted) { + next = await gen.return(errorPromptLog); + break; } - }, 100); - try { - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - next = await gen.return(errorPromptLog); - clearInterval(checkActiveInterval); - break; - } - if (next.value) { - yield { - role: "assistant", - content: next.value, - }; - } - next = await gen.next(); + if (next.value) { + yield { + role: "assistant", + content: next.value, + }; } - if (!next.done) { - throw new Error("Will never happen"); - } - - return next.value; - } catch (e) { - throw e; - } finally { - clearInterval(checkActiveInterval); + next = await gen.next(); } + if (!next.done) { + throw new Error("Will never happen"); + } + + return next.value; } else { const gen = model.streamChat( messages, - new AbortController().signal, + abortController.signal, completionOptions, ); let next = await gen.next(); while (!next.done) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); + if (abortController.signal.aborted) { next = await gen.return(errorPromptLog); break; } diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts index 416a4c9eb..d3100a61b 100644 --- a/core/llm/toolSupport.test.ts +++ b/core/llm/toolSupport.test.ts @@ -6,39 +6,57 @@ describe("PROVIDER_TOOL_SUPPORT", () => { const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"]; it("should return true for Claude 3.5 models", () => { - expect(supportsFn("claude-3-5-sonnet")).toBe(true); - expect(supportsFn("claude-3.5-sonnet")).toBe(true); + expect( + supportsFn("ownerSlug/packageSlug/anthropic/claude-3-5-sonnet"), + ).toBe(true); + expect( + supportsFn("ownerSlug/packageSlug/anthropic/claude-3.5-sonnet"), + ).toBe(true); }); it("should return true for Claude 3.7 models", () => { - expect(supportsFn("claude-3-7-haiku")).toBe(true); - expect(supportsFn("claude-3.7-sonnet")).toBe(true); + expect( + supportsFn("ownerSlug/packageSlug/anthropic/claude-3-7-haiku"), + ).toBe(true); + expect( + supportsFn("ownerSlug/packageSlug/anthropic/claude-3.7-sonnet"), + ).toBe(true); }); it("should return true for GPT-4 models", () => { - expect(supportsFn("gpt-4-turbo")).toBe(true); - expect(supportsFn("gpt-4-1106-preview")).toBe(true); + expect(supportsFn("ownerSlug/packageSlug/openai/gpt-4-turbo")).toBe(true); + expect( + supportsFn("ownerSlug/packageSlug/openai/gpt-4-1106-preview"), + ).toBe(true); }); it("should return true for O3 models", () => { - expect(supportsFn("o3-preview")).toBe(true); + expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true); }); it("should return true for Gemini models", () => { - expect(supportsFn("gemini-pro")).toBe(true); - expect(supportsFn("gemini-1.5-pro")).toBe(true); + expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true); + expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe( + true, + ); }); it("should return false for unsupported models", () => { - expect(supportsFn("gpt-3.5-turbo")).toBe(false); - expect(supportsFn("claude-2")).toBe(false); - expect(supportsFn("llama-3")).toBe(false); + expect(supportsFn("ownerSlug/packageSlug/openai/gpt-3.5-turbo")).toBe( + false, + ); + expect(supportsFn("ownerSlug/packageSlug/anthropic/claude-2")).toBe( + false, + ); + expect(supportsFn("ownerSlug/packageSlug/together/llama-3")).toBe(false); }); it("should handle case insensitivity", () => { - expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true); - expect(supportsFn("GPT-4-turbo")).toBe(true); - expect(supportsFn("GEMINI-pro")).toBe(true); + expect( + supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"), + ).toBe(true); + expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true); + expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true); }); }); @@ -56,8 +74,8 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); it("should return undefined for unsupported models", () => { - expect(supportsFn("claude-2")).toBeUndefined(); - expect(supportsFn("claude-instant")).toBeUndefined(); + expect(supportsFn("claude-2")).toBe(false); + expect(supportsFn("claude-instant")).toBe(false); }); it("should handle case insensitivity", () => { @@ -81,8 +99,8 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); it("should return undefined for unsupported models", () => { - expect(supportsFn("gpt-3.5-turbo")).toBeUndefined(); - expect(supportsFn("davinci")).toBeUndefined(); + expect(supportsFn("gpt-3.5-turbo")).toBe(false); + expect(supportsFn("davinci")).toBe(false); }); it("should handle case insensitivity", () => { @@ -115,31 +133,49 @@ describe("PROVIDER_TOOL_SUPPORT", () => { const supportsFn = PROVIDER_TOOL_SUPPORT["bedrock"]; it("should return true for Claude 3.5 Sonnet models", () => { - expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(true); - expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(true); + expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe( + true, + ); + expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe( + true, + ); }); it("should return true for Claude 3.7 Sonnet models", () => { - expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(true); - expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(true); + expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe( + true, + ); + expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe( + true, + ); }); it("should return undefined for Claude Haiku and Opus models", () => { - expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBeUndefined(); - expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBeUndefined(); - expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBeUndefined(); - expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBeUndefined(); - expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBe( + false, + ); + expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBe( + false, + ); + expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBe( + false, + ); + expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBe(false); + expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBe(false); }); it("should return undefined for other unsupported models", () => { - expect(supportsFn("anthropic.claude-instant-v1")).toBeUndefined(); - expect(supportsFn("anthropic.titan-text-express-v1")).toBeUndefined(); + expect(supportsFn("anthropic.claude-instant-v1")).toBe(false); + expect(supportsFn("anthropic.titan-text-express-v1")).toBe(false); }); it("should handle case insensitivity", () => { - expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(true); - expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(true); + expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe( + true, + ); + expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe( + true, + ); }); }); @@ -206,9 +242,9 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); it("should return undefined for other models", () => { - expect(supportsFn("llama2")).toBeUndefined(); - expect(supportsFn("phi-2")).toBeUndefined(); - expect(supportsFn("falcon")).toBeUndefined(); + expect(supportsFn("llama2")).toBe(false); + expect(supportsFn("phi-2")).toBe(false); + expect(supportsFn("falcon")).toBe(false); }); it("should handle case insensitivity", () => { @@ -221,16 +257,16 @@ describe("PROVIDER_TOOL_SUPPORT", () => { describe("edge cases", () => { it("should handle empty model names", () => { expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false); - expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBeUndefined(); - expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBe(false); + expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBe(false); expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false); - expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBeUndefined(); - expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false); + expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false); }); it("should handle non-existent provider", () => { // @ts-ignore - Testing runtime behavior with invalid provider - expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBe(undefined); }); }); }); diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index f08e3cf8a..e6d4387ce 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -1,238 +1,274 @@ -export const PROVIDER_TOOL_SUPPORT: Record< - string, - (model: string) => boolean | undefined -> = { - "continue-proxy": (model) => { - // see getContinueProxyModelName - const provider = model.split("/")[2]; - const _model = model.split("/")[3]; - if (provider && _model && provider !== "continue-proxy") { - const fn = PROVIDER_TOOL_SUPPORT[provider]; - if (fn) { - return fn(_model); +import { parseProxyModelName } from "@continuedev/config-yaml"; + +export const PROVIDER_TOOL_SUPPORT: Record boolean> = + { + "continue-proxy": (model) => { + try { + const { provider, model: _model } = parseProxyModelName(model); + if (provider && _model && provider !== "continue-proxy") { + const fn = PROVIDER_TOOL_SUPPORT[provider]; + if (fn) { + return fn(_model); + } + } + } catch (e) {} + + return [ + "claude-3-5", + "claude-3.5", + "claude-3-7", + "claude-3.7", + "claude-sonnet-4", + "gpt-4", + "o3", + "gemini", + ].some((part) => model.toLowerCase().startsWith(part)); + }, + anthropic: (model) => { + if ( + [ + "claude-3-5", + "claude-3.5", + "claude-3-7", + "claude-3.7", + "claude-sonnet-4", + ].some((part) => model.toLowerCase().startsWith(part)) + ) { + return true; } - } - return [ - "claude-3-5", - "claude-3.5", - "claude-3-7", - "claude-3.7", - "claude-sonnet-4", - "gpt-4", - "o3", - "gemini", - ].some((part) => model.toLowerCase().startsWith(part)); - }, - anthropic: (model) => { - if ( - ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) => - model.toLowerCase().startsWith(part), + + return false; + }, + azure: (model) => { + if ( + model.toLowerCase().startsWith("gpt-4") || + model.toLowerCase().startsWith("o3") ) - ) { - return true; - } - }, - azure: (model) => { - if ( - model.toLowerCase().startsWith("gpt-4") || - model.toLowerCase().startsWith("o3") - ) - return true; - return false; - }, - openai: (model) => { - // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling - if ( - model.toLowerCase().startsWith("gpt-4") || - model.toLowerCase().startsWith("o3") - ) { - return true; - } - // firworks-ai https://docs.fireworks.ai/guides/function-calling - if (model.startsWith("accounts/fireworks/models/")) { - switch (model.substring(26)) { - case "llama-v3p1-405b-instruct": - case "llama-v3p1-70b-instruct": - case "qwen2p5-72b-instruct": - case "firefunction-v1": - case "firefunction-v2": + return true; + return false; + }, + openai: (model) => { + // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling + if ( + model.toLowerCase().startsWith("gpt-4") || + model.toLowerCase().startsWith("o3") + ) { + return true; + } + // firworks-ai https://docs.fireworks.ai/guides/function-calling + if (model.startsWith("accounts/fireworks/models/")) { + switch (model.substring(26)) { + case "llama-v3p1-405b-instruct": + case "llama-v3p1-70b-instruct": + case "qwen2p5-72b-instruct": + case "firefunction-v1": + case "firefunction-v2": + return true; + default: + return false; + } + } + + return false; + }, + gemini: (model) => { + // All gemini models support function calling + return model.toLowerCase().includes("gemini"); + }, + vertexai: (model) => { + // All gemini models except flash 2.0 lite support function calling + return ( + model.toLowerCase().includes("gemini") && + !model.toLowerCase().includes("lite") + ); + }, + bedrock: (model) => { + // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 + if ( + model.toLowerCase().includes("sonnet") && + [ + "claude-3-5", + "claude-3.5", + "claude-3-7", + "claude-3.7", + "claude-sonnet-4", + ].some((part) => model.toLowerCase().includes(part)) + ) { + return true; + } + + return false; + }, + mistral: (model) => { + // https://docs.mistral.ai/capabilities/function_calling/ + return ( + !model.toLowerCase().includes("mamba") && + [ + "devstral", + "codestral", + "mistral-large", + "mistral-small", + "pixtral", + "ministral", + "mistral-nemo", + "devstral", + ].some((part) => model.toLowerCase().includes(part)) + ); + }, + // https://ollama.com/search?c=tools + ollama: (model) => { + let modelName = ""; + // Extract the model name after the last slash to support other registries + if (model.includes("/")) { + let parts = model.split("/"); + modelName = parts[parts.length - 1]; + } else { + modelName = model; + } + + if ( + ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( + (part) => modelName.toLowerCase().includes(part), + ) + ) { + return false; + } + if ( + [ + "cogito", + "llama3.3", + "qwq", + "llama3.2", + "llama3.1", + "qwen2", + "qwen3", + "mixtral", + "command-r", + "smollm2", + "hermes3", + "athene-v2", + "nemotron", + "llama3-groq", + "granite3", + "granite-3", + "aya-expanse", + "firefunction-v2", + "mistral", + "devstral", + ].some((part) => modelName.toLowerCase().includes(part)) + ) { + return true; + } + + return false; + }, + sambanova: (model) => { + // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling + if ( + model.toLowerCase().startsWith("meta-llama-3") || + model.toLowerCase().includes("llama-4") || + model.toLowerCase().includes("deepseek") + ) { + return true; + } + + return false; + }, + deepseek: (model) => { + if (model !== "deepseek-reasoner") { + return true; + } + + return false; + }, + watsonx: (model) => { + if (model.toLowerCase().includes("guard")) { + return false; + } + if ( + [ + "llama-3", + "llama-4", + "mistral", + "codestral", + "granite-3", + "devstral", + ].some((part) => model.toLowerCase().includes(part)) + ) { + return true; + } + + return false; + }, + openrouter: (model) => { + // https://openrouter.ai/models?fmt=cards&supported_parameters=tools + if ( + ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( + (part) => model.toLowerCase().includes(part), + ) + ) { + return false; + } + + const supportedPrefixes = [ + "openai/gpt-3.5", + "openai/gpt-4", + "openai/o1", + "openai/o3", + "openai/o4", + "anthropic/claude-3", + "anthropic/claude-4", + "microsoft/phi-3", + "google/gemini-flash-1.5", + "google/gemini-2", + "google/gemini-pro", + "x-ai/grok", + "qwen/qwen3", + "qwen/qwen-", + "cohere/command-r", + "ai21/jamba-1.6", + "mistralai/mistral", + "mistralai/ministral", + "mistralai/codestral", + "mistralai/mixtral", + "mistral/ministral", + "mistral/devstral", + "mistralai/pixtral", + "meta-llama/llama-3.3", + "amazon/nova", + "deepseek/deepseek-r1", + "deepseek/deepseek-chat", + "meta-llama/llama-4", + "all-hands/openhands-lm-32b", + ]; + for (const prefix of supportedPrefixes) { + if (model.toLowerCase().startsWith(prefix)) { return true; - default: - return false; + } + } + + const specificModels = [ + "qwen/qwq-32b", + "qwen/qwen-2.5-72b-instruct", + "meta-llama/llama-3.2-3b-instruct", + "meta-llama/llama-3-8b-instruct", + "meta-llama/llama-3-70b-instruct", + "arcee-ai/caller-large", + "nousresearch/hermes-3-llama-3.1-70b", + ]; + for (const model of specificModels) { + if (model.toLowerCase() === model) { + return true; + } + } + + const supportedContains = ["llama-3.1"]; + for (const model of supportedContains) { + if (model.toLowerCase().includes(model)) { + return true; + } } - } - }, - gemini: (model) => { - // All gemini models support function calling - return model.toLowerCase().includes("gemini"); - }, - vertexai: (model) => { - // All gemini models except flash 2.0 lite support function calling - return ( - model.toLowerCase().includes("gemini") && - !model.toLowerCase().includes("lite") - ); - }, - bedrock: (model) => { - // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 - if ( - model.toLowerCase().includes("sonnet") && - ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) => - model.toLowerCase().includes(part), - ) - ) { - return true; - } - }, - mistral: (model) => { - // https://docs.mistral.ai/capabilities/function_calling/ - return ( - !model.toLowerCase().includes("mamba") && - [ - "devstral", - "codestral", - "mistral-large", - "mistral-small", - "pixtral", - "ministral", - "mistral-nemo", - ].some((part) => model.toLowerCase().includes(part)) - ); - }, - // https://ollama.com/search?c=tools - ollama: (model) => { - let modelName = ""; - // Extract the model name after the last slash to support other registries - if (model.includes("/")) { - let parts = model.split("/"); - modelName = parts[parts.length - 1]; - } else { - modelName = model; - } - if ( - ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( - (part) => modelName.toLowerCase().includes(part), - ) - ) { return false; - } - if ( - [ - "cogito", - "llama3.3", - "qwq", - "llama3.2", - "llama3.1", - "qwen2", - "qwen3", - "mixtral", - "command-r", - "smollm2", - "hermes3", - "athene-v2", - "nemotron", - "llama3-groq", - "granite3", - "granite-3", - "aya-expanse", - "firefunction-v2", - "mistral", - "devstral", - ].some((part) => modelName.toLowerCase().includes(part)) - ) { - return true; - } - }, - sambanova: (model) => { - // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling - if ( - model.toLowerCase().startsWith("meta-llama-3") || - model.toLowerCase().includes("llama-4") || - model.toLowerCase().includes("deepseek") - ) { - return true; - } - }, - deepseek: (model) => { - if (model !== "deepseek-reasoner") { - return true; - } - }, - watsonx: (model) => { - if (model.toLowerCase().includes("guard")) return false; - if ( - ["llama-3", "llama-4", "mistral", "codestral", "granite-3"].some((part) => - model.toLowerCase().includes(part), - ) - ) - return true; - }, - openrouter: (model) => { - // https://openrouter.ai/models?fmt=cards&supported_parameters=tools - if ( - ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( - (part) => model.toLowerCase().includes(part), - ) - ) { - return false; - } - - const supportedPrefixes = [ - "openai/gpt-3.5", - "openai/gpt-4", - "openai/o1", - "openai/o3", - "openai/o4", - "anthropic/claude-3", - "microsoft/phi-3", - "google/gemini-flash-1.5", - "google/gemini-2", - "google/gemini-pro", - "x-ai/grok", - "qwen/qwen3", - "qwen/qwen-", - "cohere/command-r", - "ai21/jamba-1.6", - "mistralai/mistral", - "mistralai/ministral", - "mistralai/codestral", - "mistralai/mixtral", - "mistral/ministral", - "mistralai/pixtral", - "meta-llama/llama-3.3", - "amazon/nova", - "deepseek/deepseek-r1", - "deepseek/deepseek-chat", - "meta-llama/llama-4", - "all-hands/openhands-lm-32b", - ]; - for (const prefix of supportedPrefixes) { - if (model.toLowerCase().startsWith(prefix)) { - return true; - } - } - - const specificModels = [ - "qwen/qwq-32b", - "qwen/qwen-2.5-72b-instruct", - "meta-llama/llama-3.2-3b-instruct", - "meta-llama/llama-3-8b-instruct", - "meta-llama/llama-3-70b-instruct", - "arcee-ai/caller-large", - "nousresearch/hermes-3-llama-3.1-70b", - ]; - for (const model of specificModels) { - if (model.toLowerCase() === model) { - return true; - } - } - - const supportedContains = ["llama-3.1"]; - for (const model of supportedContains) { - if (model.toLowerCase().includes(model)) { - return true; - } - } - }, -}; + }, + }; diff --git a/core/package-lock.json b/core/package-lock.json index 16f7f8991..b2da9407e 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -14,10 +14,10 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.6", + "@continuedev/fetch": "^1.0.10", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.19", - "@modelcontextprotocol/sdk": "^1.11.4", + "@continuedev/openai-adapters": "^1.0.25", + "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -2927,9 +2927,10 @@ "link": true }, "node_modules/@continuedev/fetch": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.6.tgz", - "integrity": "sha512-QpB9cHgEw5avoouFR0qm7/XTo44SrVfkGAmzbDTui2P9djj+DYvj+0yaJ8e/Ubyc5PUjFTUS2YnRar7NfYpHIg==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz", + "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==", + "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", @@ -2944,14 +2945,15 @@ "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" }, "node_modules/@continuedev/openai-adapters": { - "version": "1.0.19", - "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz", - "integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==", + "version": "1.0.25", + "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.25.tgz", + "integrity": "sha512-YG7bcAlUk3BnqIOZw+ClmxmZU6G3OaaZqbhfqgiCnJem5i7oDy0pkAVHjig4iRTQkpvDokKmBXCH9wmQNRbWNw==", + "license": "Apache-2.0", "dependencies": { "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.3", + "@continuedev/fetch": "^1.0.10", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", @@ -3742,7 +3744,6 @@ "version": "1.12.0", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.12.0.tgz", "integrity": "sha512-m//7RlINx1F3sz3KqwY1WWzVgTcYX52HYk4bJ1hkBXV3zccAEth+jRvG8DBRrdaQuRsPAJOx2MH3zaHNCKL7Zg==", - "license": "MIT", "dependencies": { "ajv": "^6.12.6", "content-type": "^1.0.5", @@ -5318,7 +5319,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "license": "MIT", "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" @@ -5331,7 +5331,6 @@ "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -5340,7 +5339,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", - "license": "MIT", "dependencies": { "mime-db": "^1.54.0" }, @@ -5352,7 +5350,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -6092,7 +6089,6 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", - "license": "MIT", "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", @@ -6112,7 +6108,6 @@ "version": "6.14.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", - "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" }, @@ -6355,7 +6350,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" @@ -6368,7 +6362,6 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" @@ -6766,7 +6759,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", - "license": "MIT", "dependencies": { "safe-buffer": "5.2.1" }, @@ -6792,7 +6784,6 @@ "version": "0.7.2", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -6801,7 +6792,6 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "license": "MIT", "engines": { "node": ">=6.6.0" } @@ -6828,7 +6818,6 @@ "version": "2.8.5", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "license": "MIT", "dependencies": { "object-assign": "^4", "vary": "^1" @@ -7349,7 +7338,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", @@ -7389,8 +7377,7 @@ "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "node_modules/eight-colors": { "version": "1.3.1", @@ -7444,7 +7431,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", "engines": { "node": ">= 0.8" } @@ -7647,7 +7633,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "license": "MIT", "dependencies": { "es-errors": "^1.3.0" }, @@ -7743,8 +7728,7 @@ "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" }, "node_modules/escape-string-regexp": { "version": "4.0.0", @@ -8125,7 +8109,6 @@ "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -8225,7 +8208,6 @@ "version": "5.1.0", "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", - "license": "MIT", "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.0", @@ -8267,7 +8249,6 @@ "version": "7.5.0", "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz", "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==", - "license": "MIT", "engines": { "node": ">= 16" }, @@ -8282,7 +8263,6 @@ "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -8291,7 +8271,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", - "license": "MIT", "dependencies": { "mime-db": "^1.54.0" }, @@ -8303,7 +8282,6 @@ "version": "6.14.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", - "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" }, @@ -8544,7 +8522,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", - "license": "MIT", "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", @@ -8728,7 +8705,6 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -8737,7 +8713,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "license": "MIT", "engines": { "node": ">= 0.8" } @@ -8947,7 +8922,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", @@ -8980,7 +8954,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" @@ -9665,7 +9638,6 @@ "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "license": "MIT", "engines": { "node": ">= 0.10" } @@ -9957,8 +9929,7 @@ "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "license": "MIT" + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==" }, "node_modules/is-property": { "version": "1.0.2", @@ -11802,7 +11773,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", "engines": { "node": ">= 0.4" } @@ -11811,7 +11781,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", - "license": "MIT", "engines": { "node": ">= 0.8" } @@ -11820,7 +11789,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "license": "MIT", "engines": { "node": ">=18" }, @@ -12502,7 +12470,6 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -12628,7 +12595,6 @@ "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", "dependencies": { "ee-first": "1.1.1" }, @@ -13009,7 +12975,6 @@ "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", "engines": { "node": ">= 0.8" } @@ -13080,7 +13045,6 @@ "version": "8.2.0", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", - "license": "MIT", "engines": { "node": ">=16" } @@ -13283,7 +13247,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.0.tgz", "integrity": "sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==", - "license": "MIT", "engines": { "node": ">=16.20.0" } @@ -13655,7 +13618,6 @@ "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "license": "MIT", "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" @@ -13910,7 +13872,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -14276,7 +14237,6 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", - "license": "MIT", "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", @@ -14410,7 +14370,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", - "license": "MIT", "dependencies": { "debug": "^4.3.5", "encodeurl": "^2.0.0", @@ -14432,7 +14391,6 @@ "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -14441,7 +14399,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", - "license": "MIT", "dependencies": { "mime-db": "^1.54.0" }, @@ -14458,7 +14415,6 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", - "license": "MIT", "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", @@ -14567,7 +14523,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", @@ -14586,7 +14541,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3" @@ -14602,7 +14556,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -14620,7 +14573,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -15706,7 +15658,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", - "license": "MIT", "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", @@ -15720,7 +15671,6 @@ "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "license": "MIT", "engines": { "node": ">= 0.6" } @@ -15729,7 +15679,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", - "license": "MIT", "dependencies": { "mime-db": "^1.54.0" }, @@ -16076,7 +16025,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "license": "MIT", "engines": { "node": ">= 0.8" } diff --git a/core/package.json b/core/package.json index 4d17b4de4..5622cc903 100644 --- a/core/package.json +++ b/core/package.json @@ -49,10 +49,10 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.6", + "@continuedev/fetch": "^1.0.10", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.19", - "@modelcontextprotocol/sdk": "^1.11.4", + "@continuedev/openai-adapters": "^1.0.25", + "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 8936cb3eb..142764d19 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -46,6 +46,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { // Special ping: [string, string]; abort: [undefined, void]; + cancelApply: [undefined, void]; // History "history/list": [ListHistoryOptions, SessionMetadata[]]; diff --git a/core/util/abortManager.ts b/core/util/abortManager.ts new file mode 100644 index 000000000..e7de53bca --- /dev/null +++ b/core/util/abortManager.ts @@ -0,0 +1,37 @@ +export class StreamAbortManager { + private static instance: StreamAbortManager; + private controllers: Map; + + private constructor() { + this.controllers = new Map(); + } + + public static getInstance(): StreamAbortManager { + if (!StreamAbortManager.instance) { + StreamAbortManager.instance = new StreamAbortManager(); + } + return StreamAbortManager.instance; + } + + public get(id: string): AbortController { + let controller = this.controllers.get(id); + if (!controller) { + controller = new AbortController(); + this.controllers.set(id, controller); + } + return controller; + } + + public abort(id: string): void { + const controller = this.controllers.get(id); + if (controller) { + controller.abort(); + this.controllers.delete(id); + } + } + + public clear(): void { + this.controllers.forEach((controller) => controller.abort()); + this.controllers.clear(); + } +} diff --git a/core/vendor/.gitignore b/core/vendor/.gitignore index 736e8ae58..b512c09d4 100644 --- a/core/vendor/.gitignore +++ b/core/vendor/.gitignore @@ -1 +1 @@ -!node_modules \ No newline at end of file +node_modules \ No newline at end of file diff --git a/core/vendor/package-lock.json b/core/vendor/package-lock.json index 3f8229af6..2a59b297b 100644 --- a/core/vendor/package-lock.json +++ b/core/vendor/package-lock.json @@ -10,6 +10,9 @@ "license": "Apache-2.0", "dependencies": { "@xenova/transformers": "^2.14.0" + }, + "engines": { + "node": ">=20.19.0" } }, "node_modules/@huggingface/jinja": { @@ -105,6 +108,78 @@ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz", "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==" }, + "node_modules/bare-events": { + "version": "2.5.4", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz", + "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/bare-fs": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz", + "integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "bare-events": "^2.5.4", + "bare-path": "^3.0.0", + "bare-stream": "^2.6.4" + }, + "engines": { + "bare": ">=1.16.0" + }, + "peerDependencies": { + "bare-buffer": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + } + } + }, + "node_modules/bare-os": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz", + "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "bare": ">=1.14.0" + } + }, + "node_modules/bare-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz", + "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "bare-os": "^3.0.1" + } + }, + "node_modules/bare-stream": { + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz", + "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "streamx": "^2.21.0" + }, + "peerDependencies": { + "bare-buffer": "*", + "bare-events": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + }, + "bare-events": { + "optional": true + } + } + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -444,9 +519,10 @@ } }, "node_modules/prebuild-install/node_modules/tar-fs": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", - "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz", + "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==", + "license": "MIT", "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", @@ -503,11 +579,6 @@ "once": "^1.3.1" } }, - "node_modules/queue-tick": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", - "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==" - }, "node_modules/rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", @@ -642,12 +713,16 @@ } }, "node_modules/streamx": { - "version": "2.15.6", - "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz", - "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==", + "version": "2.22.0", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz", + "integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==", + "license": "MIT", "dependencies": { - "fast-fifo": "^1.1.0", - "queue-tick": "^1.0.1" + "fast-fifo": "^1.3.2", + "text-decoder": "^1.1.0" + }, + "optionalDependencies": { + "bare-events": "^2.2.0" } }, "node_modules/string_decoder": { @@ -667,13 +742,17 @@ } }, "node_modules/tar-fs": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz", - "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==", + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz", + "integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==", + "license": "MIT", "dependencies": { - "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^3.1.5" + }, + "optionalDependencies": { + "bare-fs": "^4.0.1", + "bare-path": "^3.0.0" } }, "node_modules/tar-stream": { @@ -686,6 +765,15 @@ "streamx": "^2.15.0" } }, + "node_modules/text-decoder": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz", + "integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==", + "license": "Apache-2.0", + "dependencies": { + "b4a": "^1.6.4" + } + }, "node_modules/tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 7773afbfc..f4ec4ea73 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -188,6 +188,7 @@ chat, editing, and summarizing. 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`. +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [ `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [ diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt index a11dbdfd5..417fbb8d4 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt @@ -108,7 +108,7 @@ class DiffManager(private val project: Project) : DumbAware { ) continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex) continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex) - + continuePluginService.coreMessenger?.request("cancelApply", null, null) {} cleanUpFile(file) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 5593ebba6..67e49a87f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -111,7 +111,8 @@ class DiffStreamHandler( suffix = suffix, language = virtualFile?.fileType?.name, modelTitle = modelTitle, - includeRulesInSystemMessage = includeRulesInSystemMessage + includeRulesInSystemMessage = includeRulesInSystemMessage, + fileUri = virtualFile?.url ), null ) { response -> @@ -289,7 +290,6 @@ class DiffStreamHandler( } } - private fun handleFinishedResponse() { ApplicationManager.getApplication().invokeLater { // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index ed38e4726..86862a096 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -244,7 +244,8 @@ data class StreamDiffLinesPayload( val input: String, val language: String?, val modelTitle: String?, - val includeRulesInSystemMessage: Boolean + val includeRulesInSystemMessage: Boolean, + val fileUri: String? ) data class AcceptOrRejectDiffPayload( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index fe7b07bb4..5634027da 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -10,7 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", - "@continuedev/fetch": "^1.0.3", + "@continuedev/fetch": "^1.0.10", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", "@types/node-fetch": "^2.6.11", @@ -107,10 +107,10 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.6", + "@continuedev/fetch": "^1.0.10", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.19", - "@modelcontextprotocol/sdk": "^1.11.4", + "@continuedev/openai-adapters": "^1.0.25", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -708,9 +708,10 @@ } }, "node_modules/@continuedev/fetch": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz", - "integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz", + "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==", + "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", @@ -1457,13 +1458,13 @@ } }, "node_modules/@nestjs/common": { - "version": "11.0.20", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.20.tgz", - "integrity": "sha512-/GH8NDCczjn6+6RNEtSNAts/nq/wQE8L1qZ9TRjqjNqEsZNE1vpFuRIhmcO2isQZ0xY5rySnpaRdrOAul3gQ3A==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.1.tgz", + "integrity": "sha512-crzp+1qeZ5EGL0nFTPy9NrVMAaUWewV5AwtQyv6SQ9yQPXwRl9W9hm1pt0nAtUu5QbYMbSuo7lYcF81EjM+nCA==", "dev": true, "license": "MIT", "dependencies": { - "file-type": "20.4.1", + "file-type": "20.5.0", "iterare": "1.2.1", "load-esm": "1.0.2", "tslib": "2.8.1", @@ -1474,8 +1475,8 @@ "url": "https://opencollective.com/nest" }, "peerDependencies": { - "class-transformer": "*", - "class-validator": "*", + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, @@ -1489,9 +1490,9 @@ } }, "node_modules/@nestjs/core": { - "version": "11.0.20", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.0.20.tgz", - "integrity": "sha512-yUkEzBGiRNSEThVl6vMCXgoA9sDGWoRbJsTLdYdCC7lg7PE1iXBnna1FiBfQjT995pm0fjyM1e3WsXmyWeJXbw==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.1.tgz", + "integrity": "sha512-UFoUAgLKFT+RwHTANJdr0dF7p0qS9QjkaUPjg8aafnjM/qxxxrUVDB49nVvyMlk+Hr1+vvcNaOHbWWQBxoZcHA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -1722,18 +1723,18 @@ } }, "node_modules/@openapitools/openapi-generator-cli": { - "version": "2.20.0", - "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.20.0.tgz", - "integrity": "sha512-Amtd7/9Lodaxnmfsru8R5n0CW9lyWOI40UsppGMfuNFkFFbabq51/VAJFsOHkNnDRwVUc7AGKWjN5icphDGlTQ==", + "version": "2.20.2", + "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.20.2.tgz", + "integrity": "sha512-dNFwQcQu6+rmEWSJj4KUx468+p6Co7nfpVgi5QEfVhzKj7wBytz9GEhCN2qmVgtg3ZX8H6nxbXI8cjh7hAxAqg==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { "@nestjs/axios": "4.0.0", - "@nestjs/common": "11.0.20", - "@nestjs/core": "11.0.20", + "@nestjs/common": "11.1.1", + "@nestjs/core": "11.1.1", "@nuxtjs/opencollective": "0.3.2", - "axios": "1.8.4", + "axios": "1.9.0", "chalk": "4.1.2", "commander": "8.3.0", "compare-versions": "4.1.4", @@ -1980,9 +1981,9 @@ } }, "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==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", "dev": true, "license": "MIT", "dependencies": { @@ -3381,9 +3382,9 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", - "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", + "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", @@ -6055,9 +6056,9 @@ } }, "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==", + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.5.0.tgz", + "integrity": "sha512-BfHZtG/l9iMm4Ecianu7P8HRD2tBHLtjXinm4X62XBOYzi7CYA7jyqfJzOvXHqzVrVPYqBo2/GvbARMaaJkKVg==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 56fc1e80a..101b3de67 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.39", + "version": "1.1.40", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -661,7 +661,7 @@ }, "dependencies": { "@continuedev/config-types": "^1.0.14", - "@continuedev/fetch": "^1.0.3", + "@continuedev/fetch": "^1.0.10", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", "@types/node-fetch": "^2.6.11", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index b85d377cc..84885f757 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -97,6 +97,7 @@ async function processDiff( action: "accept" | "reject", sidebar: ContinueGUIWebviewViewProvider, ide: VsCodeIde, + core: Core, verticalDiffManager: VerticalDiffManager, newFileUri?: string, streamId?: string, @@ -121,6 +122,9 @@ async function processDiff( // Clear vertical diffs depending on action verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); + if (action === "reject") { + core.invoke("cancelApply", undefined); + } if (streamId) { const fileContent = await ide.readFile(newOrCurrentUri); @@ -236,18 +240,20 @@ const getCommandsMap: ( "accept", sidebar, ide, + core, verticalDiffManager, newFileUri, streamId, ), - "continue.rejectDiff": async (newFilepath?: string, streamId?: string) => + "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => processDiff( "reject", sidebar, ide, + core, verticalDiffManager, - newFilepath, + newFileUri, streamId, ), "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => { @@ -573,11 +579,15 @@ const getCommandsMap: ( await addEntireFileToContext( vscode.Uri.parse(fileUri), sidebar.webviewProtocol, - ide.ideUtils + ide.ideUtils, ); } } else { - await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils); + await addEntireFileToContext( + uri, + sidebar.webviewProtocol, + ide.ideUtils, + ); } } }, diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index bb09ac588..104db10c6 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,5 +1,4 @@ import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core"; -import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; @@ -31,7 +30,6 @@ export class VerticalDiffManager { logDiffs: DiffLine[] | undefined; constructor( - private readonly configHandler: ConfigHandler, private readonly webviewProtocol: VsCodeWebviewProtocol, private readonly editDecorationManager: EditDecorationManager, ) { @@ -43,12 +41,12 @@ export class VerticalDiffManager { startLine: number, endLine: number, options: VerticalDiffHandlerOptions, - ) { + ): VerticalDiffHandler | undefined { if (this.fileUriToHandler.has(fileUri)) { this.fileUriToHandler.get(fileUri)?.clear(false); this.fileUriToHandler.delete(fileUri); } - const editor = vscode.window.activeTextEditor; // TODO + const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files if (editor && URI.equal(editor.document.uri.toString(), fileUri)) { const handler = new VerticalDiffHandler( startLine, @@ -453,6 +451,7 @@ export class VerticalDiffManager { language: getMarkdownLanguageTagForFile(fileUri), onlyOneInsertion: !!onlyOneInsertion, overridePrompt, + abortControllerId: fileUri, }); for await (const line of stream) { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index bcdb88edd..78cd0c24d 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -130,7 +130,6 @@ export class VsCodeExtension { this.configHandler.loadConfig(); this.verticalDiffManager = new VerticalDiffManager( - this.configHandler, this.sidebar.webviewProtocol, this.editDecorationManager, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 9008969c2..e5f054caa 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -236,8 +236,9 @@ export class VsCodeMessenger { data: { prompt: stripImages(prompt), completion: fileAfterEdit ?? "", - modelProvider: model.providerName, + modelProvider: model.underlyingProviderName, modelTitle: model.title ?? "", + filepath: msg.data.range.filepath, }, }); diff --git a/gui/package-lock.json b/gui/package-lock.json index 2d62eb384..8ab34dbe7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -111,10 +111,10 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.6", + "@continuedev/fetch": "^1.0.10", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.19", - "@modelcontextprotocol/sdk": "^1.11.4", + "@continuedev/openai-adapters": "^1.0.25", + "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index 675f9147f..0f3bd97ea 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -3,7 +3,7 @@ import { ApplyState } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { getMetaKeyLabel } from "../util"; -import { useFontSize } from "./ui/font"; +import { ToolTip } from "./gui/Tooltip"; export interface AcceptRejectAllButtonsProps { applyStates: ApplyState[]; @@ -21,8 +21,6 @@ export default function AcceptRejectAllButtons({ ); const ideMessenger = useContext(IdeMessengerContext); - const tinyFont = useFontSize(-3); - async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { for (const { filepath = "", streamId } of pendingApplyStates) { ideMessenger.post(status, { @@ -36,54 +34,43 @@ export default function AcceptRejectAllButtons({ } } - if (!pendingApplyStates.length) { - return null; - } + const rejectShortcut = `${getMetaKeyLabel()}⇧⌫`; + const acceptShortcut = `${getMetaKeyLabel()}⇧⏎`; return (
+ + +
); } diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 91854a274..9b037a068 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -6,7 +6,7 @@ import { useNavigate } from "react-router-dom"; import { Input } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { exitEditMode } from "../../redux/thunks/editMode"; +import { exitEdit } from "../../redux/thunks/edit"; import { deleteSession, getSession, @@ -69,7 +69,7 @@ export function HistoryTableRow({ data-testid={`history-row-${index}`} className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { - await dispatch(exitEditMode({})); + await dispatch(exitEdit({})); if (sessionMetadata.sessionId !== currentSessionId) { await dispatch( loadSession({ diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index a6368eab4..b5e4ebda6 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -7,9 +7,9 @@ import { IdeMessengerContext } from "../context/IdeMessenger"; import { LocalStorageProvider } from "../context/LocalStorage"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { setCodeToEdit } from "../redux/slices/editModeState"; +import { setCodeToEdit } from "../redux/slices/editState"; import { setShowDialog } from "../redux/slices/uiSlice"; -import { enterEditMode, exitEditMode } from "../redux/thunks/editMode"; +import { enterEdit, exitEdit } from "../redux/thunks/edit"; import { saveCurrentSession } from "../redux/thunks/session"; import { fontSize, isMetaEquivalentKeyPressed } from "../util"; import { incrementFreeTrialCount } from "../util/freeTrial"; @@ -48,14 +48,14 @@ const Layout = () => { const dialogMessage = useAppSelector((state) => state.ui.dialogMessage); const showDialog = useAppSelector((state) => state.ui.showDialog); - const mode = useAppSelector((state) => state.session.mode); + const isInEdit = useAppSelector((store) => store.session.isInEdit); useWebviewListener( "newSession", async () => { navigate(ROUTES.HOME); - if (mode === "edit") { - await dispatch(exitEditMode({})); + if (isInEdit) { + await dispatch(exitEdit({})); } else { await dispatch( saveCurrentSession({ @@ -65,7 +65,7 @@ const Layout = () => { ); } }, - [mode], + [isInEdit], ); useWebviewListener( @@ -81,9 +81,9 @@ const Layout = () => { "focusContinueInputWithNewSession", async () => { navigate(ROUTES.HOME); - if (mode === "edit") { + if (isInEdit) { await dispatch( - exitEditMode({ + exitEdit({ openNewSession: true, }), ); @@ -96,7 +96,7 @@ const Layout = () => { ); } }, - [location.pathname, mode], + [location.pathname, isInEdit], location.pathname === ROUTES.HOME, ); @@ -148,7 +148,7 @@ const Layout = () => { "focusEdit", async () => { await ideMessenger.request("edit/addCurrentSelection", undefined); - await dispatch(enterEditMode({})); + await dispatch(enterEdit({ editorContent: mainEditor?.getJSON() })); mainEditor?.commands.focus(); }, [ideMessenger, mainEditor], @@ -169,7 +169,7 @@ const Layout = () => { useWebviewListener( "exitEditMode", async () => { - await dispatch(exitEditMode({})); + await dispatch(exitEdit({})); }, [], ); @@ -181,7 +181,7 @@ const Layout = () => { if (selection) { // Copy to clipboard setTimeout(() => { - navigator.clipboard.writeText(selection); + void navigator.clipboard.writeText(selection); }, 100); } } diff --git a/gui/src/components/ModeSelect/ModeIcon.tsx b/gui/src/components/ModeSelect/ModeIcon.tsx new file mode 100644 index 000000000..83201d5ae --- /dev/null +++ b/gui/src/components/ModeSelect/ModeIcon.tsx @@ -0,0 +1,19 @@ +import { ChatBubbleLeftIcon, SparklesIcon } from "@heroicons/react/24/outline"; +import { MessageModes } from "core"; + +interface ModeIconProps { + mode: MessageModes; + className?: string; +} + +export function ModeIcon({ + mode, + className = "xs:h-3 xs:w-3 h-3 w-3", +}: ModeIconProps) { + switch (mode) { + case "agent": + return ; + case "chat": + return ; + } +} diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx similarity index 51% rename from gui/src/components/modelSelection/ModeSelect.tsx rename to gui/src/components/ModeSelect/ModeSelect.tsx index 23caef356..22a9975ca 100644 --- a/gui/src/components/modelSelection/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -1,21 +1,11 @@ -// A dropdown menu for selecting between Chat, Edit, and Agent modes with keyboard shortcuts -import { - ChatBubbleLeftIcon, - CheckIcon, - ChevronDownIcon, - PencilIcon, - SparklesIcon, -} from "@heroicons/react/24/outline"; +import { CheckIcon, ChevronDownIcon } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { useCallback, useEffect, useMemo } from "react"; -import styled from "styled-components"; -import { lightGray } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; -import { enterEditMode, exitEditMode } from "../../redux/thunks/editMode"; -import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util"; +import { getFontSize, getMetaKeyLabel } from "../../util"; import { useMainEditor } from "../mainInput/TipTapEditor"; import { Listbox, @@ -23,14 +13,9 @@ import { ListboxOption, ListboxOptions, } from "../ui/Listbox"; +import { ModeIcon } from "./ModeIcon"; -const ShortcutText = styled.span` - color: ${lightGray}; - font-size: ${getFontSize() - 3}px; - margin-right: auto; -`; - -function ModeSelect() { +export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); @@ -38,24 +23,10 @@ function ModeSelect() { return selectedModel && modelSupportsTools(selectedModel); }, [selectedModel]); const { mainEditor } = useMainEditor(); - const jetbrains = useMemo(() => { - return isJetBrains(); - }, []); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); }, []); - const getModeIcon = (mode: MessageModes) => { - switch (mode) { - case "agent": - return ; - case "chat": - return ; - case "edit": - return ; - } - }; - // Switch to chat mode if agent mode is selected but not supported useEffect(() => { if (!selectedModel) { @@ -66,55 +37,18 @@ function ModeSelect() { } }, [mode, agentModeSupported, dispatch, selectedModel]); - const cycleMode = useCallback(async () => { - const modes: MessageModes[] = jetbrains - ? ["chat", "agent"] - : ["chat", "agent", "edit"]; - const currentIndex = modes.indexOf(mode); - const nextMode = modes[(currentIndex + 1) % modes.length]; - - if (mode === "edit") { - await dispatch( - exitEditMode({ - goToMode: nextMode, - }), - ); - } else { - if (nextMode === "edit") { - await dispatch( - enterEditMode({ - returnToMode: mode, - }), - ); - } else { - dispatch(setMode(nextMode)); - } - } + const cycleMode = useCallback(() => { + dispatch(setMode(mode === "chat" ? "agent" : "chat")); mainEditor?.commands.focus(); - }, [jetbrains, mode, mainEditor]); + }, [mode, mainEditor]); const selectMode = useCallback( - async (newMode: MessageModes) => { + (newMode: MessageModes) => { if (newMode === mode) { return; } - if (newMode === "edit") { - await dispatch( - enterEditMode({ - returnToMode: mode, - }), - ); - } else { - if (mode === "edit") { - await dispatch( - exitEditMode({ - goToMode: newMode, - }), - ); - } else { - dispatch(setMode(newMode)); - } - } + + dispatch(setMode(newMode)); mainEditor?.commands.focus(); }, @@ -138,13 +72,9 @@ function ModeSelect() {
- {getModeIcon(mode)} + {mode.charAt(0).toUpperCase() + mode.slice(1)} @@ -154,21 +84,15 @@ function ModeSelect() { /> - {!jetbrains && ( - -
- - Edit - {getMetaKeyLabel()}I -
- {mode === "edit" && } -
- )}
- + Chat - {getMetaKeyLabel()}L + + {getMetaKeyLabel()}L +
{mode === "chat" && }
@@ -179,7 +103,7 @@ function ModeSelect() { className={"gap-1"} >
- + Agent
{agentModeSupported ? ( @@ -189,7 +113,7 @@ function ModeSelect() { )} -
+
{`${metaKeyLabel} . for next mode`}
@@ -197,5 +121,3 @@ function ModeSelect() { ); } - -export default ModeSelect; diff --git a/gui/src/components/ModeSelect/index.ts b/gui/src/components/ModeSelect/index.ts new file mode 100644 index 000000000..04cc20156 --- /dev/null +++ b/gui/src/components/ModeSelect/index.ts @@ -0,0 +1 @@ +export * from "./ModeSelect"; diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index d739a8434..0929aad8b 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -40,6 +40,7 @@ function BestExperienceConfigForm({ const chatModelConfig = { model: chatModel.params.model, provider: chatProvider.provider, + underlyingProviderName: chatProvider.provider, apiKey: chatApiKey, title: chatModel.params.title, }; @@ -47,6 +48,7 @@ function BestExperienceConfigForm({ const repoMapConfig = { model: repoMapModel.params.model, provider: chatProvider.provider, + underlyingProviderName: chatProvider.provider, apiKey: chatApiKey, title: repoMapModel.params.title, }; @@ -54,6 +56,7 @@ function BestExperienceConfigForm({ const autocompleteModelConfig = { title: autocompleteModel.params.title, provider: autocompleteProvider.provider, + underlyingProviderName: autocompleteProvider.provider, model: autocompleteModel.params.model, apiKey: autocompleteApiKey, }; diff --git a/gui/src/components/mainInput/CodeToEditCard.tsx b/gui/src/components/mainInput/CodeToEditCard.tsx deleted file mode 100644 index 1c22f5ddf..000000000 --- a/gui/src/components/mainInput/CodeToEditCard.tsx +++ /dev/null @@ -1,181 +0,0 @@ -import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { SetCodeToEditPayload } from "core"; -import { getMarkdownLanguageTagForFile } from "core/util"; -import { getUriPathBasename } from "core/util/uri"; -import { useContext, useMemo, useState } from "react"; -import { useDispatch } from "react-redux"; -import styled from "styled-components"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; -import { clearCodeToEdit } from "../../redux/slices/editModeState"; -import { getMetaKeyLabel } from "../../util"; -import FileIcon from "../FileIcon"; -import StyledMarkdownPreview from "../StyledMarkdownPreview"; -import { useFontSize } from "../ui/font"; - -const NoPaddingWrapper = styled.div` - > * { - margin: 0 !important; - padding: 0 !important; - } - - pre { - margin: 0 !important; - padding: 0px 0px 0px 10px !important; - } -`; - -interface CodeToEditItemProps { - code: SetCodeToEditPayload; -} - -function CodeToEditItem({ code }: CodeToEditItemProps) { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const [showCodeSnippet, setShowCodeSnippet] = useState(false); - - function onDelete() { - dispatch(clearCodeToEdit()); - ideMessenger.post("edit/clearDecorations", undefined); - } - - const fileName = getUriPathBasename(code.filepath); - - let isInsertion = false; - let title = fileName; - - if ("range" in code) { - const start = code.range.start.line + 1; - const end = code.range.end.line + 1; - - isInsertion = start === end; - - title += isInsertion - ? ` - Inserting at line ${start}` - : ` (${start} - ${end})`; - } - - const source = - "```" + - getMarkdownLanguageTagForFile(code.filepath) + - "\n" + - code.contents + - "\n" + - "```"; - - async function onClickFilename() { - if ("range" in code) { - await ideMessenger.ide.showLines( - code.filepath, - code.range.start.line, - code.range.end.line, - ); - } else { - await ideMessenger.ide.openFile(code.filepath); - } - } - - const smallFont = useFontSize(-3); - - const iconClass = - "text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"; - - return ( -
-
- - Code to edit - - {/* */} -
{ - if (!isInsertion) { - setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet); - } - }} - > -
- - { - e.stopPropagation(); - void onClickFilename(); - }} - > - {title} - -
- -
- { - e.stopPropagation(); - setShowCodeSnippet((val) => !val); - }} - className={`text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20 ${showCodeSnippet ? "rotate-90" : ""} ${isInsertion ? "hidden" : ""}`} - /> -
- { - e.stopPropagation(); - void onDelete(); - }} - className={iconClass} - /> -
-
-
-
- {showCodeSnippet && ( -
- - - -
- )} -
- ); -} - -export default function CodeToEditCard() { - // Array from previous multi-file edit - const codeToEditArray = useAppSelector( - (state) => state.editModeState.codeToEdit, - ); - const codeToEdit = useMemo(() => { - return codeToEditArray[0]; - }, [codeToEditArray]); - - const metaKeyLabel = useMemo(() => { - return getMetaKeyLabel(); - }, []); - - const tinyFont = useFontSize(-3); - - return ( -
- {codeToEdit ? ( - - ) : ( - <> - - {`To edit code, highlight it and press `} - {metaKeyLabel} I - - - )} -
- ); -} diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index f3880249e..b50edfdbb 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -83,15 +83,15 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const availableContextProviders = useAppSelector( (state) => state.config.config.contextProviders, ); - const mode = useAppSelector((store) => store.session.mode); + const isInEdit = useAppSelector((store) => store.session.isInEdit); const editModeState = useAppSelector((state) => state.editModeState); const filteredSlashCommands = useMemo(() => { - return mode === "edit" ? [] : availableSlashCommands; - }, [mode, availableSlashCommands]); + return isInEdit ? [] : availableSlashCommands; + }, [isInEdit, availableSlashCommands]); const filteredContextProviders = useMemo(() => { - if (mode === "edit") { + if (isInEdit) { return ( availableContextProviders?.filter( (provider) => @@ -101,22 +101,21 @@ function ContinueInputBox(props: ContinueInputBoxProps) { } return availableContextProviders ?? []; - }, [availableContextProviders, mode]); + }, [availableContextProviders, isInEdit]); - const historyKey = mode === "edit" ? "edit" : "chat"; - const placeholder = mode === "edit" ? "Describe changes" : undefined; + const historyKey = isInEdit ? "edit" : "chat"; + const placeholder = isInEdit ? "Edit selected code" : undefined; - const toolbarOptions: ToolbarOptions = - mode === "edit" - ? { - hideAddContext: false, - hideImageUpload: false, - hideUseCodebase: true, - hideSelectModel: false, - enterText: - editModeState.applyState.status === "done" ? "Retry" : "Edit", - } - : {}; + const toolbarOptions: ToolbarOptions = isInEdit + ? { + hideAddContext: false, + hideImageUpload: false, + hideUseCodebase: true, + hideSelectModel: false, + enterText: + editModeState.applyState.status === "done" ? "Retry" : "Edit", + } + : {}; const { appliedRules = [], contextItems = [] } = props; diff --git a/gui/src/components/mainInput/EditModeDetails.tsx b/gui/src/components/mainInput/EditModeDetails.tsx deleted file mode 100644 index 69746bcc2..000000000 --- a/gui/src/components/mainInput/EditModeDetails.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { exitEditMode } from "../../redux/thunks/editMode"; -import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons"; -import { useMainEditor } from "./TipTapEditor"; - -const EditModeDetails = () => { - const isStreaming = useAppSelector((store) => store.session.isStreaming); - const mode = useAppSelector((store) => store.session.mode); - const dispatch = useAppDispatch(); - const editApplyState = useAppSelector( - (store) => store.editModeState.applyState, - ); - const { mainEditor } = useMainEditor(); - const ideMessenger = useContext(IdeMessengerContext); - - if (mode !== "edit") { - return null; - } - if (isStreaming) { - return null; - } - if (editApplyState.status === "done") { - const plural = editApplyState.numDiffs === 1 ? "" : "s"; - return ( - <> -
- {`${editApplyState.numDiffs} diff${plural} remaining`} -
- { - if (outcome === "acceptDiff") { - await dispatch(exitEditMode({})); - ideMessenger.post("focusEditor", undefined); - } else { - mainEditor?.commands.focus(); - } - }} - /> - - ); - } - - // Will only still show if not all accepted - if (editApplyState.status === "closed") { - return ( -
- -
- ); - } - - // Not started/streaming - return null; -}; - -export default EditModeDetails; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 1dca2e6bc..fe3cd83f0 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -10,7 +10,7 @@ import { selectCurrentToolCallApplyState, } from "../../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; -import { exitEditMode } from "../../redux/thunks/editMode"; +import { exitEdit } from "../../redux/thunks/edit"; import { getAltKeyLabel, getMetaKeyLabel, @@ -18,7 +18,7 @@ import { } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; -import ModeSelect from "../modelSelection/ModeSelect"; +import { ModeSelect } from "../ModeSelect"; import { useFontSize } from "../ui/font"; import { EnterButton } from "./InputToolbar/EnterButton"; import HoverItem from "./InputToolbar/HoverItem"; @@ -49,7 +49,7 @@ function InputToolbar(props: InputToolbarProps) { const fileInputRef = useRef(null); const defaultModel = useAppSelector(selectSelectedChatModel); const useActiveFile = useAppSelector(selectUseActiveFile); - const mode = useAppSelector((store) => store.session.mode); + const isInEdit = useAppSelector((store) => store.session.isInEdit); const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); const currentToolCallApplyState = useAppSelector( @@ -58,7 +58,7 @@ function InputToolbar(props: InputToolbarProps) { const isEnterDisabled = props.disabled || - (mode === "edit" && codeToEdit.length === 0) || + (isInEdit && codeToEdit.length === 0) || toolCallState?.status === "generated" || (currentToolCallApplyState && currentToolCallApplyState.status !== "closed"); @@ -87,19 +87,21 @@ function InputToolbar(props: InputToolbarProps) { }} >
- - - - Select Mode - - + {!isInEdit && ( + + + + Select Mode + + + )} Select Model -
+
{props.toolbarOptions?.hideImageUpload || (supportsImages && ( <> @@ -149,12 +151,12 @@ function InputToolbar(props: InputToolbarProps) {
- {!props.toolbarOptions?.hideUseCodebase && mode !== "edit" && ( + {!props.toolbarOptions?.hideUseCodebase && !isInEdit && ( )} - {mode === "edit" && ( + {isInEdit && ( { - dispatch(exitEditMode({})); + void dispatch(exitEdit({})); ideMessenger.post("focusEditor", undefined); }} > - Esc to exit + Esc to exit Edit )} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx deleted file mode 100644 index f8953cbf7..000000000 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ /dev/null @@ -1,139 +0,0 @@ -import { useContext, useEffect } from "react"; -import { useSelector } from "react-redux"; -import styled from "styled-components"; -import { AnimatedEllipsis } from "../.."; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; -import { callCurrentTool } from "../../../redux/thunks/callCurrentTool"; -import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall"; -import { cancelStream } from "../../../redux/thunks/cancelStream"; -import { - getAltKeyLabel, - getFontSize, - getMetaKeyLabel, - isJetBrains, -} from "../../../util"; -import { EnterButton } from "../InputToolbar/EnterButton"; -import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; - -const Container = styled.div` - display: flex; - justify-content: space-between; - align-items: center; - width: 100%; -`; - -const StopButton = styled.div` - font-size: ${getFontSize() - 3}px; - padding: 2px; - padding-right: 4px; - cursor: pointer; -`; - -function GeneratingIndicator() { - return ( -
- Generating - -
- ); -} - -export function LumpToolbar() { - const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const ttsActive = useAppSelector((state) => state.ui.ttsActive); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const jetbrains = isJetBrains(); - - const toolCallState = useSelector(selectCurrentToolCall); - - const handleKeyDown = (event: KeyboardEvent) => { - if (toolCallState?.status === "generated") { - const metaKey = event.metaKey || event.ctrlKey; - const altKey = event.altKey; - - if (metaKey && event.key === "Enter") { - event.preventDefault(); - event.stopPropagation(); - dispatch(callCurrentTool()); - } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { - event.preventDefault(); - event.stopPropagation(); - dispatch(cancelCurrentToolCall()); - } - } - }; - - useEffect(() => { - document.addEventListener("keydown", handleKeyDown); - return () => { - document.removeEventListener("keydown", handleKeyDown); - }; - }, [toolCallState]); - - if (ttsActive) { - return ( - - - { - ideMessenger.post("tts/kill", undefined); - }} - > - ■ Stop TTS - - - ); - } - - if (isStreaming) { - return ( - - - { - dispatch(cancelStream()); - }} - > - {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} - {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel - - - ); - } - - if (toolCallState?.status === "generated") { - return ( - -
- Pending tool call -
- -
- dispatch(cancelCurrentToolCall())} - data-testid="reject-tool-call-button" - > - {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} - {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel - - dispatch(callCurrentTool())} - data-testid="accept-tool-call-button" - > - {getMetaKeyLabel()} ⏎ Continue - -
-
- ); - } - - return ; -} diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx similarity index 87% rename from gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx rename to gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx index eaf3771f8..8fe721155 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx @@ -10,16 +10,16 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { ReactNode } from "react"; -import { vscBadgeForeground } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; -import { ToolTip } from "../../gui/Tooltip"; -import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; -import { useFontSize } from "../../ui/font"; -import HoverItem from "../InputToolbar/HoverItem"; -import { useLump } from "./LumpContext"; -import { ErrorsSectionTooltip } from "./sections/errors/ErrorsSectionTooltip"; -import { McpSectionTooltip } from "./sections/mcp/MCPTooltip"; -import { ToolsSectionTooltip } from "./sections/tool-policies/ToolPoliciesSectionTooltip"; +import { vscBadgeForeground } from "../../.."; +import { useAppSelector } from "../../../../redux/hooks"; +import { ToolTip } from "../../../gui/Tooltip"; +import AssistantSelect from "../../../modelSelection/platform/AssistantSelect"; +import { useFontSize } from "../../../ui/font"; +import HoverItem from "../../InputToolbar/HoverItem"; +import { useLump } from "../LumpContext"; +import { ErrorsSectionTooltip } from "../sections/errors/ErrorsSectionTooltip"; +import { McpSectionTooltip } from "../sections/mcp/MCPTooltip"; +import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSectionTooltip"; interface BlockSettingsToolbarIcon { title: string; @@ -96,14 +96,14 @@ function BlockSettingsToolbarIcon( className={`${ props.isSelected ? isErrorSection - ? "bg-red-600" + ? "bg-error" : "bg-badge" : undefined } relative flex select-none items-center rounded-full px-[3px] transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 sm:px-1 ${props.className || ""}`} >
-
+
store.editModeState.applyState, + ); + const { mainEditor } = useMainEditor(); + const ideMessenger = useContext(IdeMessengerContext); + + return ( +
+
+ {`${editApplyState.numDiffs} diff${editApplyState.numDiffs !== 1 ? "s" : ""}`} +
+ { + if (outcome === "acceptDiff") { + await dispatch(exitEdit({})); + ideMessenger.post("focusEditor", undefined); + } else { + mainEditor?.commands.focus(); + } + }} + /> +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx new file mode 100644 index 000000000..10f441be4 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx @@ -0,0 +1,38 @@ +import { ArrowLeftIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { exitEdit } from "../../../../redux/thunks"; +import { getEditFilenameAndRangeText } from "../../util"; + +export function EditToolbar() { + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const mode = useAppSelector((state) => state.session.mode); + const codeToEdit = useAppSelector( + (state) => state.editModeState.codeToEdit[0], + ); + + const handleBackClick = async () => { + void dispatch(exitEdit({})); + ideMessenger.post("focusEditor", undefined); + }; + + return ( +
+ + + Back to {mode.charAt(0).toUpperCase() + mode.slice(1)} + + + Editing{" "} + + {getEditFilenameAndRangeText(codeToEdit)} + + +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx new file mode 100644 index 000000000..48c1571b4 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx @@ -0,0 +1,14 @@ +import { AnimatedEllipsis } from "../../.."; + +export function GeneratingIndicator({ + text = "Generating", +}: { + text?: string; +}) { + return ( +
+ {text} + +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx new file mode 100644 index 000000000..0faf43e0e --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx @@ -0,0 +1,29 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { getAltKeyLabel, getMetaKeyLabel } from "../../../../util"; +import { Container, StopButton } from "./components"; +import { GeneratingIndicator } from "./GeneratingIndicator"; + +export const IsApplyingToolbar = () => { + const ideMessenger = useContext(IdeMessengerContext); + + const jetbrains = window.location.protocol === "jb-api:"; + + return ( + + + { + // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option + // Apply is prioritized because it can be more catastrophic + // Intentional to be more WYSIWYG for now + ideMessenger.post("cancelApply", undefined); + }} + > + {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel + + + ); +}; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx new file mode 100644 index 000000000..6b4fdb5ba --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -0,0 +1,96 @@ +import { useEffect } from "react"; +import { useSelector } from "react-redux"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; +import { + callCurrentTool, + cancelCurrentToolCall, +} from "../../../../redux/thunks"; +import { isJetBrains } from "../../../../util"; +import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; +import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; +import { EditToolbar } from "./EditToolbar"; +import { IsApplyingToolbar } from "./IsApplyingToolbar"; +import { PendingApplyStatesToolbar } from "./PendingApplyStatesToolbar"; +import { PendingToolCallToolbar } from "./PendingToolCallToolbar"; +import { StreamingToolbar } from "./StreamingToolbar"; +import { TtsActiveToolbar } from "./TtsActiveToolbar"; + +export function LumpToolbar() { + const dispatch = useAppDispatch(); + const ttsActive = useAppSelector((state) => state.ui.ttsActive); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const isInEdit = useAppSelector((state) => state.session.isInEdit); + const jetbrains = isJetBrains(); + const toolCallState = useSelector(selectCurrentToolCall); + const editApplyState = useAppSelector( + (state) => state.editModeState.applyState, + ); + const applyStates = useAppSelector( + (state) => state.session.codeBlockApplyStates.states, + ); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + + const isApplying = applyStates.some((state) => state.status === "streaming"); + + useEffect(() => { + if (toolCallState?.status !== "generated") { + return; + } + + const handleKeyDown = (event: KeyboardEvent) => { + const metaKey = event.metaKey || event.ctrlKey; + const altKey = event.altKey; + + if (metaKey && event.key === "Enter") { + event.preventDefault(); + event.stopPropagation(); + void dispatch(callCurrentTool()); + } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { + event.preventDefault(); + event.stopPropagation(); + void dispatch(cancelCurrentToolCall()); + } + }; + + document.addEventListener("keydown", handleKeyDown); + return () => { + document.removeEventListener("keydown", handleKeyDown); + }; + }, [toolCallState]); + + if (isApplying) { + return ; + } + + if (isInEdit) { + if (editApplyState.status === "done") { + return ; + } + + return ; + } + + if (ttsActive) { + return ; + } + + if (isStreaming) { + return ; + } + + if (toolCallState?.status === "generated") { + return ; + } + + if (pendingApplyStates.length > 0) { + return ( + + ); + } + + return ; +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/PendingApplyStatesToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/PendingApplyStatesToolbar.tsx new file mode 100644 index 000000000..22d03dda1 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/PendingApplyStatesToolbar.tsx @@ -0,0 +1,44 @@ +import { ApplyState } from "core"; +import { getUriPathBasename } from "core/util/uri"; +import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons"; +import FileIcon from "../../../FileIcon"; + +interface PendingApplyStatesToolbarProps { + pendingApplyStates: ApplyState[]; +} + +export function PendingApplyStatesToolbar({ + pendingApplyStates, +}: PendingApplyStatesToolbarProps) { + // Group apply states by filepath + const applyStatesByFilepath = pendingApplyStates.reduce( + (acc, state) => { + const filepath = state.filepath || ""; // Use empty string as fallback + if (!acc[filepath]) { + acc[filepath] = []; + } + acc[filepath].push(state); + return acc; + }, + {} as Record, + ); + + return ( +
+ {Object.entries(applyStatesByFilepath).map(([filepath, states]) => ( +
+ {filepath && ( + + + {getUriPathBasename(filepath)} + + )} + {}} + /> +
+ ))} +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx new file mode 100644 index 000000000..3a7da10d1 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx @@ -0,0 +1,59 @@ +import styled from "styled-components"; +import { useAppDispatch } from "../../../../redux/hooks"; +import { + callCurrentTool, + cancelCurrentToolCall, +} from "../../../../redux/thunks"; +import { + getAltKeyLabel, + getFontSize, + getMetaKeyLabel, + isJetBrains, +} from "../../../../util"; +import { EnterButton } from "../../InputToolbar/EnterButton"; + +const Container = styled.div` + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; +`; + +const StopButton = styled.div` + font-size: ${getFontSize() - 3}px; + padding: 2px; + padding-right: 4px; + cursor: pointer; +`; + +export function PendingToolCallToolbar() { + const dispatch = useAppDispatch(); + const jetbrains = isJetBrains(); + + return ( + +
+ Pending tool call +
+ +
+ dispatch(cancelCurrentToolCall())} + data-testid="reject-tool-call-button" + > + {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel + + dispatch(callCurrentTool())} + data-testid="accept-tool-call-button" + > + {getMetaKeyLabel()} ⏎ Continue + +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx new file mode 100644 index 000000000..aa3a6cdaf --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx @@ -0,0 +1,24 @@ +import { useAppDispatch } from "../../../../redux/hooks"; +import { cancelStream } from "../../../../redux/thunks"; +import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util"; +import { Container, StopButton } from "./components"; +import { GeneratingIndicator } from "./GeneratingIndicator"; + +export function StreamingToolbar() { + const dispatch = useAppDispatch(); + const jetbrains = isJetBrains(); + + return ( + + + { + void dispatch(cancelStream()); + }} + > + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel + + + ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/TtsActiveToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/TtsActiveToolbar.tsx new file mode 100644 index 000000000..034bbf281 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/TtsActiveToolbar.tsx @@ -0,0 +1,37 @@ +import { useContext } from "react"; +import styled from "styled-components"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { getFontSize } from "../../../../util"; +import { GeneratingIndicator } from "./GeneratingIndicator"; + +const Container = styled.div` + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; +`; + +const StopButton = styled.div` + font-size: ${getFontSize() - 3}px; + padding: 2px; + padding-right: 4px; + cursor: pointer; +`; + +export function TtsActiveToolbar() { + const ideMessenger = useContext(IdeMessengerContext); + + return ( + + + { + ideMessenger.post("tts/kill", undefined); + }} + > + ■ Stop TTS + + + ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/components.ts b/gui/src/components/mainInput/Lump/LumpToolbar/components.ts new file mode 100644 index 000000000..7b4764f19 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/components.ts @@ -0,0 +1,18 @@ +// TODO: Convert these to tailwind + +import styled from "styled-components"; +import { getFontSize } from "../../../../util"; + +export const Container = styled.div` + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; +`; + +export const StopButton = styled.div` + font-size: ${getFontSize() - 3}px; + padding: 2px; + padding-right: 4px; + cursor: pointer; +`; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/index.ts b/gui/src/components/mainInput/Lump/LumpToolbar/index.ts new file mode 100644 index 000000000..a62e11c02 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar/index.ts @@ -0,0 +1 @@ +export * from "./LumpToolbar"; diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index 218c23b68..bdd77fdf1 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -37,7 +37,7 @@ export function Lump() { return ( -
+
void>; } -const MainEditorContext = createContext( - undefined, -); +const initialState: MainEditorContextType = { + mainEditor: null, + setMainEditor: () => {}, + inputId: null, + setInputId: () => {}, + onEnterRef: { current: () => {} }, +}; + +const MainEditorContext = createContext(initialState); /** * Provider component that maintains a reference to the main editor @@ -38,8 +44,10 @@ export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { const dispatch = useAppDispatch(); - const [mainEditor, setMainEditorInternal] = useState(null); - const [inputId, setInputId] = useState(null); + const [mainEditor, setMainEditorInternal] = useState( + initialState.mainEditor, + ); + const [inputId, setInputId] = useState(initialState.inputId); const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {}); const editorFocusedRef = useRef(false); const historyLength = useAppSelector((store) => store.session.history.length); @@ -108,10 +116,5 @@ export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({ /** * Hook to access the main editor context */ -export const useMainEditor = (): MainEditorContextType => { - const context = useContext(MainEditorContext); - if (context === undefined) { - throw new Error("useMainEditor must be used within a MainEditorProvider"); - } - return context; -}; +export const useMainEditor = (): MainEditorContextType => + useContext(MainEditorContext); diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index e9222bcbc..8948a7e46 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -42,14 +42,13 @@ export function TipTapEditor(props: TipTapEditorProps) { const mainEditorContext = useMainEditor(); const ideMessenger = useContext(IdeMessengerContext); - const isOSREnabled = useIsOSREnabled(); const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const historyLength = useAppSelector((store) => store.session.history.length); + const isInEdit = useAppSelector((store) => store.session.isInEdit); - const mode = useAppSelector((store) => store.session.mode); const { editor, onEnterRef } = createEditorConfig({ props, ideMessenger, @@ -87,10 +86,10 @@ export function TipTapEditor(props: TipTapEditorProps) { }, [editor, props.isMainInput]); useEffect(() => { - if (mode === "edit") { + if (isInEdit) { setShouldHideToolbar(false); } - }, [mode]); + }, [isInEdit]); const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); @@ -150,7 +149,7 @@ export function TipTapEditor(props: TipTapEditorProps) { const handleBlur = useCallback( (e: React.FocusEvent) => { - if (mode === "edit") { + if (isInEdit) { return; } // Check if the new focus target is within our InputBoxDiv @@ -165,7 +164,7 @@ export function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(true); }, 100); }, - [mode, blurTimeout], + [isInEdit, blurTimeout], ); const handleFocus = useCallback(() => { @@ -213,7 +212,7 @@ export function TipTapEditor(props: TipTapEditorProps) { } setShowDragOverMsg(false); let file = event.dataTransfer.files[0]; - handleImageFile(ideMessenger, file).then((result) => { + void handleImageFile(ideMessenger, file).then((result) => { if (!editor) { return; } @@ -245,7 +244,7 @@ export function TipTapEditor(props: TipTapEditorProps) { onAddContextItem={() => insertCharacterWithWhitespace("@")} onEnter={onEnterRef.current} onImageFileSelected={(file) => { - handleImageFile(ideMessenger, file).then((result) => { + void handleImageFile(ideMessenger, file).then((result) => { if (!editor) { return; } diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 1e6651e5f..12eef0717 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -3,7 +3,7 @@ import { InputModifiers } from "core"; import { rifWithContentsToContextItem } from "core/commands/util"; import { MutableRefObject } from "react"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { clearCodeToEdit } from "../../../redux/slices/editModeState"; +import { clearCodeToEdit } from "../../../redux/slices/editState"; import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 3fea17ad4..774a95446 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -23,7 +23,7 @@ import { useAppSelector } from "../../../../redux/hooks"; import { selectUseActiveFile } from "../../../../redux/selectors"; import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; import { AppDispatch } from "../../../../redux/store"; -import { exitEditMode } from "../../../../redux/thunks/editMode"; +import { exitEdit } from "../../../../redux/thunks/edit"; import { getFontSize, isJetBrains } from "../../../../util"; import * as ContinueExtensions from "../extensions"; import { TipTapEditorProps } from "../TipTapEditor"; @@ -81,9 +81,9 @@ export function createEditorConfig(options: { const isStreaming = useAppSelector((state) => state.session.isStreaming); const useActiveFile = useAppSelector(selectUseActiveFile); const historyLength = useAppSelector((store) => store.session.history.length); - const mode = useAppSelector((store) => store.session.mode); - const modeRef = useUpdatingRef(mode); const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); + const isInEdit = useAppSelector((store) => store.session.isInEdit); + const isInEditRef = useUpdatingRef(isInEdit); const inSubmenuRef = useRef(undefined); const inDropdownRef = useRef(false); @@ -157,7 +157,7 @@ export function createEditorConfig(options: { for (const item of items) { const file = item.getAsFile(); file && - modelSupportsImages( + void modelSupportsImages( model.provider, model.model, model.title, @@ -269,9 +269,9 @@ export function createEditorConfig(options: { return true; } - if (modeRef.current === "edit") { - dispatch( - exitEditMode({ + if (isInEditRef.current) { + void dispatch( + exitEdit({ openNewSession: false, }), ); @@ -345,7 +345,7 @@ export function createEditorConfig(options: { if (!editor) { return; } - if (isStreaming || (codeToEdit.length === 0 && mode === "edit")) { + if (isStreaming || (codeToEdit.length === 0 && isInEdit)) { return; } @@ -362,7 +362,7 @@ export function createEditorConfig(options: { props.onEnter(json, modifiers, editor); }, - [props.onEnter, editor, props.isMainInput, codeToEdit, mode], + [props.onEnter, editor, props.isMainInput, codeToEdit, isInEdit], ); return { editor, onEnterRef }; diff --git a/gui/src/components/mainInput/util/index.ts b/gui/src/components/mainInput/util/index.ts new file mode 100644 index 000000000..5f8b4fd77 --- /dev/null +++ b/gui/src/components/mainInput/util/index.ts @@ -0,0 +1,20 @@ +import { SetCodeToEditPayload } from "core"; +import { getUriPathBasename } from "core/util/uri"; + +export * from "./handleMetaKeyIssues"; + +export function getEditFilenameAndRangeText(code: SetCodeToEditPayload) { + const fileName = getUriPathBasename(code.filepath); + let title = `${fileName}`; + + if ("range" in code) { + const start = code.range.start.line + 1; + const end = code.range.end.line + 1; + const isInsertion = start === end; + title += isInsertion + ? ` - Inserting at line ${start}` + : ` (${start} - ${end})`; + } + + return title; +} diff --git a/gui/src/components/mainInput/util/inputModifiers.ts b/gui/src/components/mainInput/util/inputModifiers.ts deleted file mode 100644 index cd16b1532..000000000 --- a/gui/src/components/mainInput/util/inputModifiers.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { InputModifiers } from "core"; - -export const defaultInputModifiers: InputModifiers = { - useCodebase: false, - noContext: true, -}; diff --git a/gui/src/components/mainInput/utils.ts b/gui/src/components/mainInput/utils.ts deleted file mode 100644 index 71565a429..000000000 --- a/gui/src/components/mainInput/utils.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { JSONContent } from "@tiptap/core"; - -export function getParagraphNodeFromString(str: string): JSONContent { - return { - type: "doc", - content: [ - { - type: "paragraph", - content: [ - { - type: "text", - text: str, - }, - ], - }, - ], - }; -} diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 3e39d6315..390d7f893 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -6,8 +6,7 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; -import styled from "styled-components"; -import { defaultBorderRadius, lightGray } from ".."; +import { lightGray } from ".."; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; @@ -30,21 +29,6 @@ interface Option { apiKey?: string; } -const IconBase = styled.div<{ $hovered: boolean }>` - width: 1.2em; - height: 1.2em; - cursor: pointer; - padding: 4px; - border-radius: ${defaultBorderRadius}; - opacity: ${(props) => (props.$hovered ? 0.75 : 0)}; - visibility: ${(props) => (props.$hovered ? "visible" : "hidden")}; - - &:hover { - opacity: 1; - background-color: ${lightGray}33; - } -`; - function modelSelectTitle(model: any): string { if (model?.title) return model?.title; if (model?.model !== undefined && model?.model.trim() !== "") { @@ -120,12 +104,12 @@ function ModelOption({ function ModelSelect() { const dispatch = useAppDispatch(); - const mode = useAppSelector((store) => store.session.mode); + const isInEdit = useAppSelector((store) => store.session.isInEdit); const config = useAppSelector((state) => state.config.config); let selectedModel = null; let allModels = null; - if (mode === "edit") { + if (isInEdit) { allModels = config.modelsByRole.edit; selectedModel = config.selectedModelByRole.edit; } @@ -226,7 +210,7 @@ function ModelSelect() { void dispatch( updateSelectedModelByRole({ selectedProfile, - role: mode === "edit" ? "edit" : "chat", + role: isInEdit ? "edit" : "chat", modelTitle: val, }), ); @@ -236,7 +220,7 @@ function ModelSelect() { {modelSelectTitle(selectedModel) || "Select model"} diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index dae2136df..63254cc11 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -126,7 +126,7 @@ const AssistantSelectOption = ({ )} {isLocalProfile(profile) ? ( { e.stopPropagation(); e.preventDefault(); @@ -135,7 +135,7 @@ const AssistantSelectOption = ({ /> ) : ( { e.stopPropagation(); e.preventDefault(); @@ -242,12 +242,12 @@ export default function AssistantSelect() { return (
{ - ideMessenger.request("controlPlane/openUrl", { + void ideMessenger.request("controlPlane/openUrl", { path: "/new?type=assistant", orgSlug: currentOrg?.slug, }); }} - className="flex cursor-pointer select-none items-center gap-1 text-gray-400" + className="text-description flex cursor-pointer select-none items-center gap-1" style={{ fontSize: smallFont }} > @@ -266,7 +266,7 @@ export default function AssistantSelect() {
@@ -301,7 +301,7 @@ export default function AssistantSelect() { > @@ -339,7 +339,7 @@ export default function AssistantSelect() { onClick={session ? onNewAssistant : () => login(false)} >
store.session.history); + const isInEdit = useAppSelector((store) => store.session.isInEdit); const selectedProfileId = useAppSelector( (store) => store.profiles.selectedProfileId, ); const hasDoneInitialConfigLoad = useRef(false); + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, + ); + + const { mainEditor } = useMainEditor(); const handleConfigUpdate = useCallback( async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => { @@ -99,18 +106,18 @@ function ParallelListeners() { // Load config from the IDE useEffect(() => { - initialLoadAuthAndConfig(true); + void initialLoadAuthAndConfig(true); const interval = setInterval(() => { if (hasDoneInitialConfigLoad.current) { // Init to run on initial config load ideMessenger.post("docs/initStatuses", undefined); - dispatch(updateFileSymbolsFromHistory()); - dispatch(refreshSessionMetadata({})); + void dispatch(updateFileSymbolsFromHistory()); + void dispatch(refreshSessionMetadata({})); // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); } else { - initialLoadAuthAndConfig(true); + void initialLoadAuthAndConfig(true); } }, 2_000); @@ -132,39 +139,43 @@ function ParallelListeners() { const sessionId = useAppSelector((state) => state.session.id); useEffect(() => { if (sessionId) { - dispatch(updateFileSymbolsFromHistory()); + void dispatch(updateFileSymbolsFromHistory()); } }, [sessionId]); // ON LOAD useEffect(() => { // Override persisted state - dispatch(cancelStream()); + void dispatch(cancelStream()); const jetbrains = isJetBrains(); setDocumentStylesFromLocalStorage(jetbrains); if (jetbrains) { // Save theme colors to local storage for immediate loading in JetBrains - ideMessenger.request("jetbrains/getColors", undefined).then((result) => { - if (result.status === "success") { - setDocumentStylesFromTheme(result.content); - } - }); + void ideMessenger + .request("jetbrains/getColors", undefined) + .then((result) => { + if (result.status === "success") { + setDocumentStylesFromTheme(result.content); + } + }); // Tell JetBrains the webview is ready - ideMessenger.request("jetbrains/onLoad", undefined).then((result) => { - if (result.status === "error") { - return; - } + void ideMessenger + .request("jetbrains/onLoad", undefined) + .then((result) => { + if (result.status === "error") { + return; + } - const msg = result.content; - (window as any).windowId = msg.windowId; - (window as any).serverUrl = msg.serverUrl; - (window as any).workspacePaths = msg.workspacePaths; - (window as any).vscMachineId = msg.vscMachineId; - (window as any).vscMediaUrl = msg.vscMediaUrl; - }); + const msg = result.content; + (window as any).windowId = msg.windowId; + (window as any).serverUrl = msg.serverUrl; + (window as any).workspacePaths = msg.workspacePaths; + (window as any).vscMachineId = msg.vscMachineId; + (window as any).vscMediaUrl = msg.vscMediaUrl; + }); } }, []); @@ -194,7 +205,7 @@ function ParallelListeners() { ); useWebviewListener("setInactive", async () => { - dispatch(cancelStream()); + void dispatch(cancelStream()); }); useWebviewListener("setTTSActive", async (status) => { @@ -203,7 +214,7 @@ function ParallelListeners() { // TODO - remove? useWebviewListener("submitMessage", async (data) => { - dispatch( + void dispatch( streamResponseThunk({ editorState: data.message, modifiers: { useCodebase: false, noContext: true }, @@ -224,14 +235,15 @@ function ParallelListeners() { dispatch(updateIndexingStatus(data)); }); - const currentToolCallApplyState = useAppSelector( - selectCurrentToolCallApplyState, - ); useWebviewListener( "updateApplyState", async (state) => { if (state.streamId === EDIT_MODE_STREAM_ID) { dispatch(updateEditStateApplyState(state)); + + if (state.status === "closed") { + dispatch(exitEdit({})); + } } else { // chat or agent dispatch(updateApplyState(state)); @@ -253,7 +265,7 @@ function ParallelListeners() { }), ); // dispatch(setToolCallOutput([])); - dispatch( + void dispatch( streamResponseAfterToolCall({ toolCallId: currentToolCallApplyState.toolCallId!, }), @@ -264,12 +276,12 @@ function ParallelListeners() { [currentToolCallApplyState, history], ); - const mode = useAppSelector((store) => store.session.mode); useEffect(() => { - if (mode !== "edit") { + if (!isInEdit) { dispatch(setLastNonEditSessionEmpty(history.length === 0)); } - }, [mode, history]); + }, [isInEdit, history]); + return <>; } diff --git a/gui/src/pages/gui/Chat.test.tsx b/gui/src/pages/gui/Chat.test.tsx index 292266ab0..626438350 100644 --- a/gui/src/pages/gui/Chat.test.tsx +++ b/gui/src/pages/gui/Chat.test.tsx @@ -35,8 +35,8 @@ describe("Chat page test", () => { ); }); - // Check that it switched to Edit mode - expect(await screen.findByText("Edit")).toBeInTheDocument(); + // Check that it switched back to Chat mode + expect(await screen.findByText("Chat")).toBeInTheDocument(); }); it.skip("should send a message and receive a response", async () => { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 7b3c383f3..75fb48c4b 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -46,7 +46,7 @@ import { } from "../../redux/slices/uiSlice"; import { streamResponseThunk } from "../../redux/thunks"; import { cancelStream } from "../../redux/thunks/cancelStream"; -import { streamEditThunk } from "../../redux/thunks/editMode"; +import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { @@ -54,9 +54,6 @@ import { incrementFreeTrialCount, } from "../../util/freeTrial"; -import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; -import CodeToEditCard from "../../components/mainInput/CodeToEditCard"; -import EditModeDetails from "../../components/mainInput/EditModeDetails"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; @@ -121,9 +118,7 @@ export function Chat() { const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); const mode = useAppSelector((store) => store.session.mode); - const applyStates = useAppSelector( - (state) => state.session.codeBlockApplyStates.states, - ); + const isInEdit = useAppSelector((store) => store.session.isInEdit); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const hasDismissedExploreDialog = useAppSelector( @@ -144,6 +139,7 @@ export function Chat() { !e.shiftKey ) { dispatch(cancelStream()); + ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter } }; window.addEventListener("keydown", listener); @@ -184,15 +180,14 @@ export function Chat() { ); } - const model = - mode === "edit" - ? (selectedModels?.edit ?? selectedModels?.chat) - : selectedModels?.chat; + const model = isInEdit + ? (selectedModels?.edit ?? selectedModels?.chat) + : selectedModels?.chat; if (!model) { return; } - if (mode === "edit" && codeToEdit.length === 0) { + if (isInEdit && codeToEdit.length === 0) { return; } @@ -223,15 +218,15 @@ export function Chat() { } } - if (mode === "edit") { - dispatch( + if (isInEdit) { + void dispatch( streamEditThunk({ editorState, codeToEdit, }), ); } else { - dispatch(streamResponseThunk({ editorState, modifiers, index })); + void dispatch(streamResponseThunk({ editorState, modifiers, index })); if (editorToClearOnSend) { editorToClearOnSend.commands.clearContent(); @@ -251,7 +246,15 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [history, selectedModels, streamResponse, mode, codeToEdit, toolCallState], + [ + history, + selectedModels, + streamResponse, + mode, + isInEdit, + codeToEdit, + toolCallState, + ], ); useWebviewListener( @@ -291,7 +294,7 @@ export function Chat() { return ( <> - {!!showSessionTabs && mode !== "edit" && } + {!!showSessionTabs && !isInEdit && } {widget}
- <> - {!isStreaming && mode !== "edit" && ( - {}} - /> - )} - {mode === "edit" && } - - sendInput(editorState, modifiers, undefined, editor) - } - inputId={MAIN_EDITOR_INPUT_ID} - /> - - + + sendInput(editorState, modifiers, undefined, editor) + } + inputId={MAIN_EDITOR_INPUT_ID} + />
- {history.length === 0 && lastSessionId && mode !== "edit" && ( + {history.length === 0 && lastSessionId && !isInEdit && (
{ diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editState.ts similarity index 73% rename from gui/src/redux/slices/editModeState.ts rename to gui/src/redux/slices/editState.ts index 05b41a15b..74379b29f 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editState.ts @@ -1,14 +1,16 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { ApplyState, SetCodeToEditPayload, MessageModes } from "core"; +import { JSONContent } from "@tiptap/core"; +import { ApplyState, MessageModes, SetCodeToEditPayload } from "core"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; -export interface EditModeState { +export interface EditState { // Array because of previous multi-file edit functionality // Keeping array to not break persisted redux for now codeToEdit: SetCodeToEditPayload[]; applyState: ApplyState; returnToMode: MessageModes; lastNonEditSessionWasEmpty: boolean; + previousModeEditorContent: JSONContent | undefined; } export const INITIAL_EDIT_APPLY_STATE: ApplyState = { @@ -16,15 +18,16 @@ export const INITIAL_EDIT_APPLY_STATE: ApplyState = { status: "not-started", }; -const initialState: EditModeState = { +const initialState: EditState = { applyState: INITIAL_EDIT_APPLY_STATE, codeToEdit: [], returnToMode: "chat", lastNonEditSessionWasEmpty: false, + previousModeEditorContent: undefined, }; -export const editModeStateSlice = createSlice({ - name: "editModeState", +export const editStateSlice = createSlice({ + name: "editState", initialState, reducers: { setReturnToModeAfterEdit: ( @@ -63,6 +66,12 @@ export const editModeStateSlice = createSlice({ ) => { state.lastNonEditSessionWasEmpty = payload; }, + setPreviousModeEditorContent: ( + state, + { payload }: PayloadAction, + ) => { + state.previousModeEditorContent = payload; + }, }, selectors: {}, }); @@ -73,5 +82,6 @@ export const { setCodeToEdit, updateEditStateApplyState, setLastNonEditSessionEmpty, -} = editModeStateSlice.actions; -export default editModeStateSlice.reducer; + setPreviousModeEditorContent, +} = editStateSlice.actions; +export default editStateSlice.reducer; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 627829da4..d9965920b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -47,6 +47,7 @@ type SessionState = { mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; + isInEdit: boolean; codeBlockApplyStates: { states: ApplyState[]; curIndex: number; @@ -63,6 +64,7 @@ const initialState: SessionState = { streamAborter: new AbortController(), symbols: {}, mode: "chat", + isInEdit: false, codeBlockApplyStates: { states: [], curIndex: 0, @@ -645,6 +647,9 @@ export const sessionSlice = createSlice({ setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, + setIsInEdit: (state, action: PayloadAction) => { + state.isInEdit = action.payload; + }, setNewestToolbarPreviewForInput: ( state, { @@ -741,6 +746,7 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestToolbarPreviewForInput, + setIsInEdit, } = sessionSlice.actions; export const { selectIsGatheringContext } = sessionSlice.selectors; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 983f7bb6c..1e0d098f3 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -17,7 +17,7 @@ import storage from "redux-persist/lib/storage"; import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger"; import { profilesReducer } from "./slices"; import configReducer from "./slices/configSlice"; -import editModeStateReducer from "./slices/editModeState"; +import editModeStateReducer from "./slices/editState"; import indexingReducer from "./slices/indexingSlice"; import sessionReducer from "./slices/sessionSlice"; import tabsReducer from "./slices/tabsSlice"; diff --git a/gui/src/redux/thunks/editMode.ts b/gui/src/redux/thunks/edit.ts similarity index 61% rename from gui/src/redux/thunks/editMode.ts rename to gui/src/redux/thunks/edit.ts index 8a7771a24..4471cc0b4 100644 --- a/gui/src/redux/thunks/editMode.ts +++ b/gui/src/redux/thunks/edit.ts @@ -1,19 +1,26 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; import { - SetCodeToEditPayload, MessageModes, RangeInFileWithContents, + SetCodeToEditPayload, } from "core"; import { stripImages } from "core/util/messageContent"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; import { clearCodeToEdit, INITIAL_EDIT_APPLY_STATE, + setPreviousModeEditorContent, setReturnToModeAfterEdit, updateEditStateApplyState, -} from "../slices/editModeState"; -import { newSession, setActive, setMode } from "../slices/sessionSlice"; +} from "../slices/editState"; +import { + newSession, + setActive, + setIsInEdit, + setMainEditorContentTrigger, + setMode, +} from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { loadLastSession, saveCurrentSession } from "./session"; import { streamThunkWrapper } from "./streamThunkWrapper"; @@ -27,7 +34,7 @@ export const streamEditThunk = createAsyncThunk< ThunkApiType >( "chat/streamResponse", - async ({ editorState, codeToEdit }, { dispatch, extra, getState }) => { + async ({ editorState, codeToEdit }, { dispatch, extra }) => { await dispatch( streamThunkWrapper(async () => { dispatch(setActive()); @@ -62,17 +69,20 @@ export const streamEditThunk = createAsyncThunk< }, ); -export const exitEditMode = createAsyncThunk< +export const exitEdit = createAsyncThunk< void, { goToMode?: MessageModes; openNewSession?: boolean }, ThunkApiType >( - "edit/exitMode", + "edit/exit", async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => { const state = getState(); const codeToEdit = state.editModeState.codeToEdit; + const isInEdit = state.session.isInEdit; + const previousModeEditorContent = + state.editModeState.previousModeEditorContent; - if (state.session.mode !== "edit") { + if (!isInEdit) { return; } @@ -86,6 +96,13 @@ export const exitEditMode = createAsyncThunk< dispatch(clearCodeToEdit()); dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); + dispatch(setIsInEdit(false)); + + // Restore the previous editor content if available + if (previousModeEditorContent) { + dispatch(setMainEditorContentTrigger(previousModeEditorContent)); + dispatch(setPreviousModeEditorContent(undefined)); + } if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) { dispatch(newSession()); @@ -101,30 +118,38 @@ export const exitEditMode = createAsyncThunk< }, ); -export const enterEditMode = createAsyncThunk< +export const enterEdit = createAsyncThunk< void, - { returnToMode?: MessageModes }, + { returnToMode?: MessageModes; editorContent?: JSONContent }, ThunkApiType ->("edit/enterMode", async ({ returnToMode }, { dispatch, extra, getState }) => { - const state = getState(); +>( + "edit/enter", + async ({ returnToMode, editorContent }, { dispatch, extra, getState }) => { + const state = getState(); + const isInEdit = state.session.isInEdit; - if (state.session.mode === "edit") { - return; - } + if (isInEdit) { + return; + } - dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode)); + dispatch(setMainEditorContentTrigger({})); + dispatch(setPreviousModeEditorContent(editorContent)); - await dispatch( - saveCurrentSession({ - openNewSession: true, - // Because this causes a lag before Edit mode is focused. TODO just have that happen in background - generateTitle: false, - }), - ); - dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); - dispatch(setMode("edit")); + dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode)); + dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); - if (!state.editModeState.codeToEdit[0]) { - extra.ideMessenger.post("edit/addCurrentSelection", undefined); - } -}); + await dispatch( + saveCurrentSession({ + openNewSession: true, + // Because this causes a lag before Edit is focused. TODO just have that happen in background + generateTitle: false, + }), + ); + + dispatch(setIsInEdit(true)); + + if (!state.editModeState.codeToEdit[0]) { + extra.ideMessenger.post("edit/addCurrentSelection", undefined); + } + }, +); diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index 7fe098e70..81c3e937c 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -1,7 +1,11 @@ -export { gatherContext } from "./gatherContext"; -export { resetStateForNewMessage } from "./resetStateForNewMessage"; -export { streamNormalInput } from "./streamNormalInput"; -export { streamResponseThunk } from "./streamResponse"; -export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; -export { streamThunkWrapper } from "./streamThunkWrapper"; -export { updateSelectedModelByRole } from "./updateSelectedModelByRole"; +export * from "./callCurrentTool"; +export * from "./cancelCurrentToolCall"; +export * from "./cancelStream"; +export * from "./edit"; +export * from "./gatherContext"; +export * from "./resetStateForNewMessage"; +export * from "./streamNormalInput"; +export * from "./streamResponse"; +export * from "./streamResponseAfterToolCall"; +export * from "./streamThunkWrapper"; +export * from "./updateSelectedModelByRole"; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 43e431271..8776aa1a6 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -79,7 +79,7 @@ export const streamNormalInput = createAsyncThunk< data: { prompt: next.value.prompt, completion: next.value.completion, - modelProvider: selectedChatModel.provider, + modelProvider: selectedChatModel.underlyingProviderName, modelTitle: selectedChatModel.title, sessionId: state.session.id, }, diff --git a/manual-testing-sandbox/AdvancedPage.tsx b/manual-testing-sandbox/AdvancedPage.tsx index 9f7d321ec..e75004bb1 100644 --- a/manual-testing-sandbox/AdvancedPage.tsx +++ b/manual-testing-sandbox/AdvancedPage.tsx @@ -13,10 +13,7 @@ const AdvancedPage = () => { className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`} >
- I apologize, but there seems to be a misunderstanding. The user's - request doesn't appear to be related to rewriting the code section you - provided. The request mentions editing a readme.md file, which is not - part of the React component code you've shown. + {" "}