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/.gitignore b/.gitignore index 95cd177a9..3f3671e74 100644 --- a/.gitignore +++ b/.gitignore @@ -166,4 +166,5 @@ extensions/.continue-debug/ *.iml .continuerules -**/.continue/assistants/ \ No newline at end of file +**/.continue/assistants/ +keys \ No newline at end of file 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 acb5b9fea..abb11ce8e 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -52,10 +52,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.5.0", + "@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", @@ -93,6 +93,7 @@ "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", + "plist": "^3.1.0", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", "puppeteer-chromium-resolver": "^23.0.0", @@ -129,6 +130,7 @@ "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", + "@types/plist": "^3.0.5", "@types/request": "^2.48.12", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", @@ -2587,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/ConfigHandler.ts b/core/config/ConfigHandler.ts index 76ccceb81..0d4d81b30 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,10 +1,6 @@ import { ConfigResult } from "@continuedev/config-yaml"; -import { - ControlPlaneClient, - ControlPlaneSessionInfo, -} from "../control-plane/client.js"; -import { getControlPlaneEnv } from "../control-plane/env.js"; +import { ControlPlaneClient } from "../control-plane/client.js"; import { BrowserSerializedContinueConfig, ContinueConfig, @@ -15,10 +11,15 @@ import { } from "../index.js"; import { GlobalContext } from "../util/GlobalContext.js"; +import { + AuthType, + ControlPlaneSessionInfo, +} from "../control-plane/AuthTypes.js"; +import { getControlPlaneEnv } from "../control-plane/env.js"; import { logger } from "../util/logger.js"; import { ASSISTANTS, - getAllDotContinueYamlFiles, + getAllDotContinueDefinitionFiles, LoadAssistantFilesOptions, } from "./loadLocalAssistants.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; @@ -136,8 +137,7 @@ export class ConfigHandler { } private async getOrgs(): Promise { - const userId = await this.controlPlaneClient.userId; - if (userId) { + if (await this.controlPlaneClient.isSignedIn()) { const orgDescs = await this.controlPlaneClient.listOrganizations(); const personalHubOrg = await this.getPersonalHubOrg(); const hubOrgs = await Promise.all( @@ -270,6 +270,13 @@ export class ConfigHandler { /** * Users can define as many local assistants as they want in a `.continue/assistants` folder */ + + // Local customization disabled for on-premise deployments + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + if (env.AUTH_TYPE === AuthType.OnPrem) { + return []; + } + const localProfiles: ProfileLifecycleManager[] = []; if (options.includeGlobal) { @@ -277,7 +284,7 @@ export class ConfigHandler { } if (options.includeWorkspace) { - const assistantFiles = await getAllDotContinueYamlFiles( + const assistantFiles = await getAllDotContinueDefinitionFiles( this.ide, options, ASSISTANTS, diff --git a/core/config/load.ts b/core/config/load.ts index 5a74aa6bb..e3d83a6b6 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -101,7 +101,14 @@ export function resolveSerializedConfig( const configMergeKeys = { models: (a: any, b: any) => a.title === b.title, - contextProviders: (a: any, b: any) => a.name === b.name, + contextProviders: (a: any, b: any) => { + // If not HTTP providers, use the name only + if (a.name !== "http" || b.name !== "http") { + return a.name === b.name; + } + // For HTTP providers, consider them different if they have different URLs + return a.name === b.name && a.params?.url === b.params?.url; + }, slashCommands: (a: any, b: any) => a.name === b.name, customCommands: (a: any, b: any) => a.name === b.name, }; @@ -620,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, @@ -970,6 +978,5 @@ export { finalToBrowserConfig, intermediateToFinalConfig, loadContinueConfigFromJson, - type BrowserSerializedContinueConfig + type BrowserSerializedContinueConfig, }; - diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 18e24f58d..90c5922a2 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -13,7 +13,7 @@ export const ASSISTANTS = "assistants"; export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; export function isLocalAssistantFile(uri: string): boolean { - if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) { + if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { return false; } @@ -21,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean { return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); } -export async function listYamlFilesInDir( +async function getDefinitionFilesInDir( ide: IDE, dir: string, ): Promise<{ path: string; content: string }[]> { @@ -41,7 +41,7 @@ export async function listYamlFilesInDir( source: "get assistant files", }); const assistantFilePaths = uris.filter( - (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), ); const results = assistantFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch @@ -86,7 +86,7 @@ export function getDotContinueSubDirs( * This method searches in both ~/.continue and workspace .continue * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts */ -export async function getAllDotContinueYamlFiles( +export async function getAllDotContinueDefinitionFiles( ide: IDE, options: LoadAssistantFilesOptions, subDirName: string, @@ -103,7 +103,7 @@ export async function getAllDotContinueYamlFiles( // Get all assistant files from the directories const assistantFiles = ( - await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir))) + await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir))) ).flat(); return await Promise.all( diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts new file mode 100644 index 000000000..b0bbb8005 --- /dev/null +++ b/core/config/markdown/loadMarkdownRules.ts @@ -0,0 +1,47 @@ +import { ConfigValidationError } from "@continuedev/config-yaml"; +import { IDE, RuleWithSource } from "../.."; +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; +import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; + +/** + * Loads rules from markdown files in the .continue/rules directory + */ +export async function loadMarkdownRules(ide: IDE): Promise<{ + rules: RuleWithSource[]; + errors: ConfigValidationError[]; +}> { + const errors: ConfigValidationError[] = []; + const rules: RuleWithSource[] = []; + + try { + // Get all .md files from .continue/rules + const markdownFiles = await getAllDotContinueDefinitionFiles( + ide, + { includeGlobal: true, includeWorkspace: true }, + "rules", + ); + + // Filter to just .md files + const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); + + // Process each markdown file + for (const file of mdFiles) { + try { + const rule = convertMarkdownRuleToContinueRule(file.path, file.content); + rules.push(rule); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, + }); + } + } + } catch (e) { + errors.push({ + fatal: false, + message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`, + }); + } + + return { rules, errors }; +} diff --git a/core/config/markdown/parseMarkdownRule.test.ts b/core/config/markdown/parseMarkdownRule.test.ts new file mode 100644 index 000000000..33d2c9901 --- /dev/null +++ b/core/config/markdown/parseMarkdownRule.test.ts @@ -0,0 +1,174 @@ +import { + convertMarkdownRuleToContinueRule, + parseMarkdownRule, +} from "./parseMarkdownRule"; + +describe("parseMarkdownRule", () => { + it("should correctly parse markdown with YAML frontmatter", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +# Test Rule + +This is a test rule.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); + }); + + it("should handle missing frontmatter", () => { + const content = `# Test Rule + +This is a test rule without frontmatter.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({}); + expect(result.markdown).toBe(content); + }); + + it("should handle empty frontmatter", () => { + const content = `--- +--- + +# Test Rule + +This is a test rule with empty frontmatter.`; + + const result = parseMarkdownRule(content); + + // Log exact strings for debugging + console.log("Actual:", JSON.stringify(result.markdown)); + console.log( + "Expected:", + JSON.stringify( + "# Test Rule\n\nThis is a test rule with empty frontmatter.", + ), + ); + + expect(result.frontmatter).toEqual({}); + expect(result.markdown).toBe( + "# Test Rule\n\nThis is a test rule with empty frontmatter.", + ); + }); + + it("should handle frontmatter with whitespace", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +# Test Rule + +This is a test rule.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); + }); + + it("should handle Windows line endings (CRLF)", () => { + // Using \r\n for CRLF line endings + const content = `---\r +globs: "**/test/**/*.kt"\r +---\r +\r +# Test Rule\r +\r +This is a test rule.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); + // The result should be normalized to \n + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); + }); + + it("should handle malformed frontmatter", () => { + const content = `--- +globs: - "**/test/**/*.kt" +invalid: yaml: content +--- + +# Test Rule + +This is a test rule.`; + + // Should treat as only markdown when frontmatter is malformed + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({}); + expect(result.markdown).toBe(content); + }); +}); + +describe("convertMarkdownRuleToContinueRule", () => { + it("should convert markdown with frontmatter to a rule", () => { + const content = `--- +globs: "**/test/**/*.kt" +name: Custom Name +--- + +# Test Rule + +This is a test rule.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/rule.md", + content, + ); + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); + expect(result.globs).toBe("**/test/**/*.kt"); + expect(result.name).toBe("Custom Name"); + expect(result.source).toBe("rules-block"); + expect(result.ruleFile).toBe("/path/to/rule.md"); + }); + + it("should use the first heading as name if not in frontmatter", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +# Test Rule Title + +This is a test rule.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/rule.md", + content, + ); + expect(result.name).toBe("Test Rule Title"); + }); + + it("should use filename as name if no heading or frontmatter name", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +This is a test rule without a heading.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/custom-rule.md", + content, + ); + expect(result.name).toBe("custom-rule"); + }); + + it("should include description from frontmatter", () => { + const content = `--- +globs: "**/test/**/*.kt" +name: Test Rule +description: This is a rule description from frontmatter +--- + +# Test Rule + +This is the content of the rule.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/rule.md", + content, + ); + expect(result.description).toBe( + "This is a rule description from frontmatter", + ); + }); +}); diff --git a/core/config/markdown/parseMarkdownRule.ts b/core/config/markdown/parseMarkdownRule.ts new file mode 100644 index 000000000..9dbbc6003 --- /dev/null +++ b/core/config/markdown/parseMarkdownRule.ts @@ -0,0 +1,69 @@ +import { basename } from "path"; +import * as YAML from "yaml"; +import { RuleWithSource } from "../.."; + +/** + * Parses markdown content with YAML frontmatter + */ +export function parseMarkdownRule(content: string): { + frontmatter: Record; + markdown: string; +} { + // Normalize line endings to \n + const normalizedContent = content.replace(/\r\n/g, "\n"); + + // More reliable frontmatter detection + const parts = normalizedContent.split(/^---\s*$/m); + + // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter + if (parts.length >= 3) { + const frontmatterStr = parts[1]; + // Join the remaining parts back together (in case there are more --- in the markdown) + const markdownContent = parts.slice(2).join("---"); + + try { + // Parse YAML frontmatter + const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter + return { frontmatter, markdown: markdownContent.trim() }; + } catch (e) { + // Error parsing frontmatter, treat as markdown only + console.warn("Error parsing markdown frontmatter:", e); + return { frontmatter: {}, markdown: normalizedContent }; + } + } + + // No frontmatter found + return { frontmatter: {}, markdown: normalizedContent }; +} + +/** + * Converts a markdown file with YAML frontmatter to a RuleWithSource object + */ +export function convertMarkdownRuleToContinueRule( + path: string, + content: string, +): RuleWithSource { + const { frontmatter, markdown } = parseMarkdownRule(content); + + // Try to extract title from first heading if no name in frontmatter + let name = frontmatter.name; + if (!name) { + // Look for a heading in the markdown + const headingMatch = markdown.match(/^#\s+(.+)$/m); + if (headingMatch) { + name = headingMatch[1].trim(); + } else { + // Fall back to filename + name = basename(path).replace(/\.md$/, ""); + } + } + + return { + name, + rule: markdown, + globs: frontmatter.globs, + description: frontmatter.description, + source: "rules-block", + ruleFile: path, + }; +} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 1308ca2a0..cc1b98e49 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -32,6 +32,7 @@ import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; import { loadContinueConfigFromJson } from "../load"; +import { loadMarkdownRules } from "../markdown/loadMarkdownRules"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; @@ -128,6 +129,12 @@ export default async function doLoadConfig(options: { newConfig.rules.unshift(...rules); errors.push(...continueRulesErrors); + // Add rules from markdown files in .continue/rules + const { rules: markdownRules, errors: markdownRulesErrors } = + await loadMarkdownRules(ide); + newConfig.rules.unshift(...markdownRules); + errors.push(...markdownRulesErrors); + // Rectify model selections for each role newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); 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/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index e667415d2..0a0dd03fc 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -41,9 +41,8 @@ import { GlobalContext } from "../../util/GlobalContext"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { getControlPlaneEnvSync } from "../../control-plane/env"; -import { logger } from "../../util/logger"; import { getCleanUriPath } from "../../util/uri"; -import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; @@ -72,7 +71,7 @@ function convertYamlMcpToContinueMcp( command: server.command, args: server.args ?? [], env: server.env, - }, + } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) timeout: server.connectionTimeout, }; } @@ -97,7 +96,7 @@ async function loadConfigYaml(options: { // Add local .continue blocks const allLocalBlocks: PackageIdentifier[] = []; for (const blockType of BLOCK_TYPES) { - const localBlocks = await getAllDotContinueYamlFiles( + const localBlocks = await getAllDotContinueDefinitionFiles( ide, { includeGlobal: true, includeWorkspace: true }, blockType, @@ -115,9 +114,9 @@ async function loadConfigYaml(options: { ? dirname(getCleanUriPath(packageIdentifier.filePath)) : undefined; - logger.info( - `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, - ); + // logger.info( + // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, + // ); let config = overrideConfigYaml ?? @@ -459,7 +458,7 @@ async function configYamlToContinueConfig(options: { transport: { type: "stdio", args: [], - ...server, + ...(server as any), // TODO: fix the types on mcpServers in config-yaml }, timeout: server.connectionTimeout, })), diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.test.ts index acfc6618a..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,11 +173,11 @@ describe("MCPConnection", () => { }); it("should handle custom connection timeout", async () => { - const conn = new MCPConnection({ ...options, timeout: 11 }); + 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(); @@ -229,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 875f20f78..72de75f92 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -4,6 +4,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { MCPConnectionStatus, @@ -38,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); @@ -91,6 +96,7 @@ class MCPConnection { this.prompts = []; this.resources = []; this.errors = []; + this.stdioOutput = { stdout: "", stderr: "" }; this.abortController.abort(); this.abortController = new AbortController(); @@ -215,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 { @@ -284,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": @@ -307,6 +336,10 @@ class MCPConnection { }, requestInit: { headers: options.transport.requestOptions?.headers }, }); + case "streamable-http": + return new StreamableHTTPClientTransport(new URL(options.transport.url), { + requestInit: { headers: options.transport.requestOptions?.headers }, + }); default: throw new Error( `Unsupported transport type: ${(options.transport as any).type}`, diff --git a/core/control-plane/AuthTypes.ts b/core/control-plane/AuthTypes.ts new file mode 100644 index 000000000..c926efac1 --- /dev/null +++ b/core/control-plane/AuthTypes.ts @@ -0,0 +1,55 @@ +export interface HubSessionInfo { + AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging; + accessToken: string; + account: { + label: string; + id: string; + }; +} + +export interface OnPremSessionInfo { + AUTH_TYPE: AuthType.OnPrem; +} + +export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo; + +export function isHubSession( + sessionInfo: ControlPlaneSessionInfo | undefined, +): sessionInfo is HubSessionInfo { + return ( + sessionInfo !== undefined && + (sessionInfo.AUTH_TYPE === AuthType.WorkOsProd || + sessionInfo.AUTH_TYPE === AuthType.WorkOsStaging) + ); +} + +export enum AuthType { + WorkOsProd = "continue", + WorkOsStaging = "continue-staging", + OnPrem = "on-prem", +} + +export interface HubEnv { + DEFAULT_CONTROL_PLANE_PROXY_URL: string; + CONTROL_PLANE_URL: string; + AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging; + WORKOS_CLIENT_ID: string; + APP_URL: string; +} + +export interface OnPremEnv { + AUTH_TYPE: AuthType.OnPrem; + DEFAULT_CONTROL_PLANE_PROXY_URL: string; + CONTROL_PLANE_URL: string; + APP_URL: string; +} + +export type ControlPlaneEnv = HubEnv | OnPremEnv; + +export function isHubEnv(env: ControlPlaneEnv): env is HubEnv { + return ( + "AUTH_TYPE" in env && + env.AUTH_TYPE !== "on-prem" && + "WORKOS_CLIENT_ID" in env + ); +} diff --git a/core/control-plane/auth/index.ts b/core/control-plane/auth/index.ts index a3441ab65..5e8748ab9 100644 --- a/core/control-plane/auth/index.ts +++ b/core/control-plane/auth/index.ts @@ -1,5 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import { IdeSettings } from "../.."; +import { isHubEnv } from "../AuthTypes"; import { getControlPlaneEnv } from "../env"; export async function getAuthUrlForTokenPage( @@ -7,6 +8,11 @@ export async function getAuthUrlForTokenPage( useOnboarding: boolean, ): Promise { const env = await getControlPlaneEnv(ideSettingsPromise); + + if (!isHubEnv(env)) { + throw new Error("Sign in disabled"); + } + const url = new URL("https://api.workos.com/user_management/authorize"); const params = { response_type: "code", diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 77a3dc108..e3513ac2d 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -12,16 +12,9 @@ import fetch, { RequestInit, Response } from "node-fetch"; import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; import { IdeSettings, ModelDescription } from "../index.js"; +import { ControlPlaneSessionInfo, isHubSession } from "./AuthTypes.js"; import { getControlPlaneEnv } from "./env.js"; -export interface ControlPlaneSessionInfo { - accessToken: string; - account: { - label: string; - id: string; - }; -} - export interface ControlPlaneWorkspace { id: string; name: string; @@ -45,8 +38,7 @@ export class ControlPlaneClient { fqsns: FQSN[], orgScopeId: string | null, ): Promise<(SecretResult | undefined)[]> { - const userId = await this.userId; - if (!userId) { + if (!(await this.isSignedIn())) { return fqsns.map((fqsn) => ({ found: false, fqsn, @@ -64,19 +56,24 @@ export class ControlPlaneClient { return (await resp.json()) as any; } - get userId(): Promise { - return this.sessionInfoPromise.then( - (sessionInfo) => sessionInfo?.account.id, - ); + async isSignedIn(): Promise { + const sessionInfo = await this.sessionInfoPromise; + return !!sessionInfo; } async getAccessToken(): Promise { - return (await this.sessionInfoPromise)?.accessToken; + const sessionInfo = await this.sessionInfoPromise; + return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined; } private async request(path: string, init: RequestInit): Promise { - const accessToken = await this.getAccessToken(); - if (!accessToken) { + const sessionInfo = await this.sessionInfoPromise; + const hubSession = isHubSession(sessionInfo); + + const accessToken = hubSession ? sessionInfo.accessToken : undefined; + + // Bearer token not necessary for on-prem auth type + if (!accessToken && hubSession) { throw new Error("No access token"); } @@ -99,22 +96,6 @@ export class ControlPlaneClient { return resp; } - public async listWorkspaces(): Promise { - const userId = await this.userId; - if (!userId) { - return []; - } - - try { - const resp = await this.request("workspaces", { - method: "GET", - }); - return (await resp.json()) as any; - } catch (e) { - return []; - } - } - public async listAssistants(organizationId: string | null): Promise< { configResult: ConfigResult; @@ -124,8 +105,7 @@ export class ControlPlaneClient { rawYaml: string; }[] > { - const userId = await this.userId; - if (!userId) { + if (!(await this.isSignedIn())) { return []; } @@ -144,9 +124,7 @@ export class ControlPlaneClient { } public async listOrganizations(): Promise> { - const userId = await this.userId; - - if (!userId) { + if (!(await this.isSignedIn())) { return []; } @@ -164,8 +142,7 @@ export class ControlPlaneClient { public async listAssistantFullSlugs( organizationId: string | null, ): Promise { - const userId = await this.userId; - if (!userId) { + if (!(await this.isSignedIn())) { return null; } @@ -183,16 +160,4 @@ export class ControlPlaneClient { return null; } } - - async getSettingsForWorkspace(workspaceId: string): Promise { - const userId = await this.userId; - if (!userId) { - throw new Error("No user id"); - } - - const resp = await this.request(`workspaces/${workspaceId}`, { - method: "GET", - }); - return ((await resp.json()) as any).settings; - } } diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index acbc20b59..2d76017d2 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -4,27 +4,18 @@ import { getLocalEnvironmentDotFilePath, getStagingEnvironmentDotFilePath, } from "../util/paths"; - -export interface ControlPlaneEnv { - DEFAULT_CONTROL_PLANE_PROXY_URL: string; - CONTROL_PLANE_URL: string; - AUTH_TYPE: string; - WORKOS_CLIENT_ID: string; - APP_URL: string; -} +import { AuthType, ControlPlaneEnv } from "./AuthTypes"; +import { getMdmKeys } from "./mdm"; export const EXTENSION_NAME = "continue"; const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; -const WORKOS_ENV_ID_PRODUCTION = "continue"; -const WORKOS_ENV_ID_STAGING = "continue-staging"; - const PRODUCTION_HUB_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", CONTROL_PLANE_URL: "https://api.continue.dev/", - AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, + AUTH_TYPE: AuthType.WorkOsProd, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, APP_URL: "https://hub.continue.dev/", }; @@ -32,7 +23,7 @@ const PRODUCTION_HUB_ENV: ControlPlaneEnv = { const STAGING_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/", CONTROL_PLANE_URL: "https://api.continue-stage.tools/", - AUTH_TYPE: WORKOS_ENV_ID_STAGING, + AUTH_TYPE: AuthType.WorkOsStaging, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, APP_URL: "https://hub.continue-stage.tools/", }; @@ -40,7 +31,7 @@ const STAGING_ENV: ControlPlaneEnv = { const TEST_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/", CONTROL_PLANE_URL: "https://api-test.continue.dev/", - AUTH_TYPE: WORKOS_ENV_ID_STAGING, + AUTH_TYPE: AuthType.WorkOsStaging, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, APP_URL: "https://app-test.continue.dev/", }; @@ -48,7 +39,7 @@ const TEST_ENV: ControlPlaneEnv = { const LOCAL_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/", CONTROL_PLANE_URL: "http://localhost:3001/", - AUTH_TYPE: WORKOS_ENV_ID_STAGING, + AUTH_TYPE: AuthType.WorkOsStaging, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, APP_URL: "http://localhost:3000/", }; @@ -67,6 +58,18 @@ export async function getControlPlaneEnv( export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], ): ControlPlaneEnv { + // MDM override + const mdmKeys = getMdmKeys(); + if (mdmKeys) { + const { apiUrl } = mdmKeys; + return { + AUTH_TYPE: AuthType.OnPrem, + DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl, + CONTROL_PLANE_URL: apiUrl, + APP_URL: "https://hub.continue.dev/", + }; + } + // Note .local overrides .staging if (fs.existsSync(getLocalEnvironmentDotFilePath())) { return LOCAL_ENV; diff --git a/core/control-plane/mdm.test.ts b/core/control-plane/mdm.test.ts new file mode 100644 index 000000000..18fbe846a --- /dev/null +++ b/core/control-plane/mdm.test.ts @@ -0,0 +1,127 @@ +import * as crypto from "crypto"; +import { LicenseData, validateLicenseKey } from "./mdm"; + +// We'll create a real key pair once for all tests +const testKeyPair = crypto.generateKeyPairSync("rsa", { + modulusLength: 2048, + publicKeyEncoding: { + type: "spki", + format: "pem", + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem", + }, +}); + +// Custom function to create test licenses (replaces the original mock-dependent one) +function createTestLicense( + licenseData: LicenseData, + useValidSignature: boolean = true, +): string { + // Convert license data to a string + const licenseDataStr = JSON.stringify(licenseData); + + // Create a signature with our generated private key + const sign = crypto.createSign("SHA256"); + sign.update(licenseDataStr); + sign.end(); + + let signature: string; + if (useValidSignature) { + signature = sign.sign(testKeyPair.privateKey, "base64"); + } else { + // For invalid tests, create an intentionally wrong signature by signing different data + const wrongSign = crypto.createSign("SHA256"); + wrongSign.update(licenseDataStr + "tampered"); + wrongSign.end(); + signature = wrongSign.sign(testKeyPair.privateKey, "base64"); + } + // Combine data and signature into a license key + const licenseKeyObj = { + data: licenseDataStr, + signature: signature, + }; + + return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64"); +} + +// We need to test the actual implementation - which we can't mock with ESM +// Instead, we'll have tests that bypass validation or are expected to fail +// depending on what we're testing + +test("validateLicenseKey returns false for malformed license key", () => { + // Test with a completely invalid license key + const invalidLicenseKey = "not-a-valid-license-key"; + + // Test - no mocks, real validation + const result = validateLicenseKey(invalidLicenseKey); + + // Assert + expect(result).toBe(false); +}); + +test("validateLicenseKey returns false for invalid JSON in license key", () => { + // Create a malformed but base64-encoded string + const malformedLicenseKey = Buffer.from("this is not valid JSON").toString( + "base64", + ); + + // Test - no mocks, real validation + const result = validateLicenseKey(malformedLicenseKey); + + // Assert + expect(result).toBe(false); +}); + +test("validateLicenseKey returns false for expired license", () => { + // Without mocking, we expect this to fail signature verification + // We're testing the date logic by itself + const licenseData: LicenseData = { + customerId: "customer123", + createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago + expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago + }; + + // Create a license key - will fail verification but test logic still works + const expiredLicenseKey = createTestLicense(licenseData); + + // Test - expect false, either due to signature or expiration - both are valid test cases + const result = validateLicenseKey(expiredLicenseKey); + + // Assert + expect(result).toBe(false); +}); + +test("validateLicenseKey returns false for invalid signature", () => { + // Create license data with valid dates + const licenseData: LicenseData = { + customerId: "customer123", + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day + }; + + // Create a license with an invalid signature + const invalidSignatureKey = createTestLicense(licenseData, false); + + // Test - no mocks, real validation + const result = validateLicenseKey(invalidSignatureKey); + + // Assert + expect(result).toBe(false); +}); + +test("validateLicenseKey handles JSON parsing errors gracefully", () => { + // Create a base64 string that decodes to valid JSON but lacks required fields + const invalidStructureKey = Buffer.from( + JSON.stringify({ + notTheRightField: "wrong structure", + }), + ).toString("base64"); + + // Test - no mocks, real validation + const result = validateLicenseKey(invalidStructureKey); + + // Assert + expect(result).toBe(false); +}); diff --git a/core/control-plane/mdm.ts b/core/control-plane/mdm.ts new file mode 100644 index 000000000..81599fea0 --- /dev/null +++ b/core/control-plane/mdm.ts @@ -0,0 +1,262 @@ +import * as crypto from "crypto"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import * as plist from "plist"; + +export interface MdmKeys { + licenseKey: string; + apiUrl: string; +} + +const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp +93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7 +HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA +zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn +U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP +LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar +FQIDAQAB +-----END PUBLIC KEY-----`; + +export interface LicenseData { + customerId: string; + createdAt: string; + expiresAt: string; +} + +export function validateLicenseKey(licenseKey: string): boolean { + try { + // Decode the base64 license key + const decodedString = Buffer.from(licenseKey, "base64").toString("utf8"); + const { data, signature } = JSON.parse(decodedString); + + // Verify the signature + const verify = crypto.createVerify("SHA256"); + verify.update(data); + verify.end(); + + const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64"); + + if (!isValid) return false; + + // Check license expiration + const licenseData: LicenseData = JSON.parse(data); + const expirationDate = new Date(licenseData.expiresAt); + const now = new Date(); + + return expirationDate > now; + } catch (error) { + console.error("License validation error:", error); + return false; + } +} + +function extractConfigFromArray(config: any[]): Record { + const configObj: Record = {}; + + for (let i = 0; i < config.length; i += 2) { + if (i + 1 < config.length) { + const key = config[i]; + const value = config[i + 1]; + if (typeof key === "string") { + configObj[key] = value as string; + } + } + } + + return configObj; +} + +const MACOS_MDM_PATHS = [ + // Organization-specific MDM plist + "/Library/Managed Preferences/dev.continue.app.plist", + // User-specific MDM plist + path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"), +]; + +function readMdmKeysMacOS(): MdmKeys | undefined { + try { + // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS + // The filename is often the bundle identifier of the application + + // Try to find a valid MDM configuration file + for (const mdmPath of MACOS_MDM_PATHS) { + if (fs.existsSync(mdmPath)) { + // Read the file content + const fileContent = fs.readFileSync(mdmPath, "utf8"); + + try { + // Parse the plist file using the plist package + const config = plist.parse(fileContent); + + // Extract the relevant fields from the config + // Config is an array of alternating keys and values + if (Array.isArray(config)) { + const configObj = extractConfigFromArray(config); + + // Check if required keys are present + if (configObj.licenseKey && configObj.apiUrl) { + return { + licenseKey: configObj.licenseKey, + apiUrl: configObj.apiUrl, + }; + } + } + } catch (parseError) { + console.error(`Error parsing MDM configuration: ${parseError}`); + } + } + } + + return undefined; + } catch (error) { + console.error("Error reading macOS MDM keys:", error); + return undefined; + } +} + +function readMdmKeysWindows(): MdmKeys | undefined { + try { + // For Windows, we need to read from the registry + // Using regedit or another synchronous registry access module + const { execSync } = require("child_process"); + + // Path to the registry where MDM configuration is stored + const regPath = "HKLM\\Software\\Continue\\MDM"; + const userRegPath = "HKCU\\Software\\Continue\\MDM"; + + // Try to read from HKEY_LOCAL_MACHINE first + try { + // Use REG QUERY command to read registry values + const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`; + const apiUrlCmd = `reg query "${regPath}" /v apiUrl`; + + const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); + const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" }); + + // Extract values from command output + const licenseKey = extractRegValue(licenseKeyOutput); + const apiUrl = extractRegValue(apiUrlOutput); + + if (licenseKey && apiUrl) { + return { licenseKey, apiUrl }; + } + } catch (error) { + // Registry key might not exist, fallback to HKEY_CURRENT_USER + } + + // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE + try { + const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`; + const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`; + + const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); + const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" }); + + // Extract values from command output + const licenseKey = extractRegValue(licenseKeyOutput); + const apiUrl = extractRegValue(apiUrlOutput); + + if (licenseKey && apiUrl) { + return { licenseKey, apiUrl }; + } + } catch (error) { + // Registry key might not exist in HKCU either + } + + return undefined; + } catch (error) { + console.error("Error reading Windows MDM keys:", error); + return undefined; + } +} + +// Helper function to extract registry values from reg query output +function extractRegValue(output: string): string | undefined { + const match = output.match(/REG_SZ\s+(.+)$/m); + return match ? match[1].trim() : undefined; +} + +// Common locations for MDM configurations in Linux systems +const LINUX_MDM_PATHS = [ + // System-wide configuration + "/etc/continue/mdm.json", + "/var/lib/continue/mdm.json", + // User-specific configuration + path.join(os.homedir(), ".config/continue/mdm.json"), +]; + +function readMdmKeysLinux(): MdmKeys | undefined { + try { + // Try to find a valid MDM configuration file + for (const mdmPath of LINUX_MDM_PATHS) { + if (fs.existsSync(mdmPath)) { + // Read the file content + const fileContent = fs.readFileSync(mdmPath, "utf8"); + + try { + // Parse the JSON configuration file + const config = JSON.parse(fileContent); + + // Check if required keys are present + if (config.licenseKey && config.apiUrl) { + return { + licenseKey: config.licenseKey, + apiUrl: config.apiUrl, + }; + } + } catch (parseError) { + console.error(`Error parsing Linux MDM configuration: ${parseError}`); + } + } + } + + return undefined; + } catch (error) { + console.error("Error reading Linux MDM keys:", error); + return undefined; + } +} + +function readMdmKeys(): MdmKeys | undefined { + const platform = os.platform(); + + switch (platform) { + case "darwin": + return readMdmKeysMacOS(); + + case "win32": + return readMdmKeysWindows(); + + case "linux": + return readMdmKeysLinux(); + + default: + console.error(`MDM keys not supported on platform: ${platform}`); + return undefined; + } +} + +/** + * Read and validate MDM keys from the operating system's configuration files or registry. + */ +export function getMdmKeys(): MdmKeys | undefined { + try { + const mdmKeys = readMdmKeys(); + + if (mdmKeys) { + if (!validateLicenseKey(mdmKeys.licenseKey)) { + console.error("Invalid license key found: ", mdmKeys.licenseKey); + return undefined; + } + + return mdmKeys; + } + + return undefined; + } catch (e) { + console.warn("Error reading MDM keys: ", e); + return undefined; + } +} 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 4cba92608..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", { @@ -122,6 +127,7 @@ export async function* streamDiffLines({ (msg) => msg.role === "user" || msg.role === "tool", ) as UserChatMessage | ToolResultChatMessage | undefined), baseSystemMessage: undefined, + contextItems: [], }) : undefined; @@ -157,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 9bc413331..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" @@ -842,7 +843,7 @@ export interface SlashCommand { description: string; prompt?: string; params?: { [key: string]: any }; - promptFile?: string + promptFile?: string; run: (sdk: ContinueSDK) => AsyncGenerator; } @@ -1035,6 +1036,7 @@ export interface ModelCapability { export interface ModelDescription { title: string; provider: string; + underlyingProviderName: string; model: string; apiKey?: string; @@ -1133,7 +1135,17 @@ export interface SSEOptions { requestOptions?: RequestOptions; } -export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; +export interface StreamableHTTPOptions { + type: "streamable-http"; + url: string; + requestOptions?: RequestOptions; +} + +export type TransportOptions = + | StdioOptions + | WebSocketOptions + | SSEOptions + | StreamableHTTPOptions; export interface MCPOptions { name: string; @@ -1240,6 +1252,7 @@ export interface StreamDiffLinesPayload { language: string | undefined; modelTitle: string | undefined; includeRulesInSystemMessage: boolean; + fileUri?: string; } export interface HighlightedCodePayload { @@ -1253,6 +1266,10 @@ export interface AcceptOrRejectDiffPayload { streamId?: string; } +export interface ShowFilePayload { + filepath: string; +} + export interface RangeInFileWithContents { filepath: string; range: { @@ -1328,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/constructMessages.ts b/core/llm/constructMessages.ts index 309429d4b..5358deee5 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,6 +1,7 @@ import { ChatHistoryItem, ChatMessage, + ContextItemWithId, RuleWithSource, TextMessagePart, ToolResultChatMessage, @@ -58,7 +59,7 @@ const EDIT_MESSAGE = `\ at the beginning, middle, or end of files using these "lazy" comments. Only provide the complete file when explicitly requested. Include a concise explanation of changes unless the user specifically asks for code only. -` +`; export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ @@ -77,6 +78,31 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ ${EDIT_MESSAGE} `; +/** + * Helper function to get the context items for a user message + */ +function getUserContextItems( + userMsg: UserChatMessage | ToolResultChatMessage | undefined, + history: ChatHistoryItem[], +): ContextItemWithId[] { + if (!userMsg) return []; + + // Find the history item that contains the userMsg + const historyItem = history.find((item) => { + // Check if the message ID matches + if ("id" in userMsg && "id" in item.message) { + return (item.message as any).id === (userMsg as any).id; + } + // Fallback to content comparison + return ( + item.message.content === userMsg.content && + item.message.role === userMsg.role + ); + }); + + return historyItem?.contextItems || []; +} + export function constructMessages( messageMode: string, history: ChatHistoryItem[], @@ -92,7 +118,8 @@ export function constructMessages( const historyItem = filteredHistory[i]; if (messageMode === "chat") { - const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage; + const toolMessage: ToolResultChatMessage = + historyItem.message as ToolResultChatMessage; if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { // remove all tool calls from the history continue; @@ -127,10 +154,16 @@ export function constructMessages( | ToolResultChatMessage | undefined; + // Get context items for the last user message + const lastUserContextItems = getUserContextItems( + lastUserMsg, + filteredHistory, + ); const systemMessage = getSystemMessageWithRules({ baseSystemMessage: baseChatOrAgentSystemMessage, rules, userMessage: lastUserMsg, + contextItems: lastUserContextItems, }); if (systemMessage.trim()) { 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/Bedrock.ts b/core/llm/llms/Bedrock.ts index 7ca0f801c..3b44e1f61 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -306,7 +306,7 @@ class Bedrock extends BaseLLM { } const supportsTools = - PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; + (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false; let toolConfig = supportsTools && options.tools ? { 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.test.ts b/core/llm/llms/OpenAI.test.ts new file mode 100644 index 000000000..46c8b4e23 --- /dev/null +++ b/core/llm/llms/OpenAI.test.ts @@ -0,0 +1,34 @@ +import OpenAI from "./OpenAI"; + +describe("OpenAI", () => { + test("should identify correct o-series models", () => { + const openai = new OpenAI({ + model: "o3-mini", + }); + expect(openai.isOSeriesModel("o4-mini")).toBeTruthy(); + expect(openai.isOSeriesModel("o3-mini")).toBeTruthy(); + expect(openai.isOSeriesModel("o1-mini")).toBeTruthy(); + expect(openai.isOSeriesModel("o1")).toBeTruthy(); + expect(openai.isOSeriesModel("o3")).toBeTruthy(); + + // artificially correct samples for future models + expect(openai.isOSeriesModel("o5-mini")).toBeTruthy(); + expect(openai.isOSeriesModel("o6")).toBeTruthy(); + expect(openai.isOSeriesModel("o77")).toBeTruthy(); + expect(openai.isOSeriesModel("o54-mini")).toBeTruthy(); + }); + test("should identify incorrect o-series models", () => { + const openai = new OpenAI({ + model: "o3-mini", + }); + expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy(); + expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy(); + expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy(); + + // artificially wrong samples + expect(openai.isOSeriesModel("os1")).toBeFalsy(); + expect(openai.isOSeriesModel("so1")).toBeFalsy(); + expect(openai.isOSeriesModel("ao31")).toBeFalsy(); + expect(openai.isOSeriesModel("1os")).toBeFalsy(); + }); +}); diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index f6dbc2bf3..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", @@ -77,8 +77,8 @@ class OpenAI extends BaseLLM { return model; } - private isO3orO1Model(model?: string): boolean { - return !!model && (model.startsWith("o1") || model.startsWith("o3")); + public isOSeriesModel(model?: string): boolean { + return !!model && !!model.match(/^o[0-9]+/); } private isFireworksAiModel(model?: string): boolean { @@ -139,7 +139,7 @@ class OpenAI extends BaseLLM { finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini or o3-mini: - if (this.isO3orO1Model(options.model)) { + if (this.isOSeriesModel(options.model)) { // a) use max_completion_tokens instead of max_tokens finalOptions.max_completion_tokens = options.maxTokens; finalOptions.max_tokens = undefined; @@ -241,7 +241,7 @@ class OpenAI extends BaseLLM { body.stop = body.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini or o3-mini: - if (this.isO3orO1Model(body.model)) { + if (this.isOSeriesModel(body.model)) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; @@ -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 e43e2bfe2..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"; @@ -27,8 +28,12 @@ class ContinueProxy extends OpenAI { // to call whatever LLM API is chosen private actualApiBase?: string; + // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions + private configEnv?: Record; + constructor(options: LLMOptions) { super(options); + this.configEnv = options.env; this.actualApiBase = options.apiBase; this.apiKeyLocation = options.apiKeyLocation; this.orgScopeId = options.orgScopeId; @@ -43,11 +48,17 @@ 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, apiBase: this.actualApiBase, orgScopeId: this.orgScopeId ?? null, + env: this.configEnv, }; return { continueProperties, @@ -78,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/rules/getSystemMessageWithRules.test.ts b/core/llm/rules/getSystemMessageWithRules.test.ts index c1a7765ee..8f576247c 100644 --- a/core/llm/rules/getSystemMessageWithRules.test.ts +++ b/core/llm/rules/getSystemMessageWithRules.test.ts @@ -1,4 +1,4 @@ -import { RuleWithSource, UserChatMessage } from "../.."; +import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../.."; import { getSystemMessageWithRules } from "./getSystemMessageWithRules"; describe("getSystemMessageWithRules", () => { @@ -25,11 +25,48 @@ describe("getSystemMessageWithRules", () => { source: "rules-block", }; + // JavaScript rule + const jsRule: RuleWithSource = { + name: "JavaScript Rule", + rule: "Follow JavaScript best practices", + globs: "**/*.js", + source: "rules-block", + }; + + // Empty context items + const emptyContextItems: ContextItemWithId[] = []; + + // Context items with file paths + const tsContextItem: ContextItemWithId = { + content: "TypeScript file content", + name: "Component.tsx", + description: "A TypeScript component", + id: { providerTitle: "file", itemId: "src/Component.tsx" }, + uri: { type: "file", value: "src/Component.tsx" }, + }; + + const pyContextItem: ContextItemWithId = { + content: "Python file content", + name: "utils.py", + description: "A Python utility file", + id: { providerTitle: "file", itemId: "utils.py" }, + uri: { type: "file", value: "utils.py" }, + }; + + const jsContextItem: ContextItemWithId = { + content: "JavaScript file content", + name: "utils.js", + description: "A JavaScript utility file", + id: { providerTitle: "file", itemId: "src/utils.js" }, + uri: { type: "file", value: "src/utils.js" }, + }; + it("should not include pattern-matched rules when no file paths are mentioned", () => { const result = getSystemMessageWithRules({ baseSystemMessage, userMessage: undefined, rules: [tsRule], + contextItems: emptyContextItems, }); expect(result).toBe(baseSystemMessage); @@ -40,12 +77,13 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage: undefined, rules: [generalRule], + contextItems: emptyContextItems, }); expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`); }); - it("should include only matching rules based on file paths", () => { + it("should include only matching rules based on file paths in message", () => { const userMessage: UserChatMessage = { role: "user", content: @@ -56,6 +94,7 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [tsRule, pythonRule, generalRule], + contextItems: emptyContextItems, }); // Should include TS rule and general rule, but not Python rule @@ -63,7 +102,38 @@ describe("getSystemMessageWithRules", () => { expect(result).toBe(expected); }); - it("should include multiple matching rules", () => { + it("should include matching rules based on file paths in context items", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [tsRule, pythonRule, generalRule], + contextItems: [tsContextItem], + }); + + // Should include TS rule and general rule, but not Python rule + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include matching rules from both message and context items", () => { + const userMessage: UserChatMessage = { + role: "user", + content: "```python test.py\nprint('hello')\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + contextItems: [tsContextItem], + }); + + // Should include TS rule, Python rule, and general rule + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include multiple matching rules from message", () => { const userMessage: UserChatMessage = { role: "user", content: @@ -74,6 +144,20 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [tsRule, pythonRule, generalRule], + contextItems: emptyContextItems, + }); + + // Should include all rules + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include multiple matching rules from context items", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [tsRule, pythonRule, generalRule], + contextItems: [tsContextItem, pyContextItem], }); // Should include all rules @@ -91,6 +175,7 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [tsRule, pythonRule, generalRule], + contextItems: emptyContextItems, }); // Should only include the general rule @@ -117,6 +202,7 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [commaRule], + contextItems: emptyContextItems, }); // With the current implementation, the comma-separated pattern is treated as a single string, @@ -143,6 +229,7 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [arrayGlobRule], + contextItems: emptyContextItems, }); // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts @@ -168,6 +255,7 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [arrayGlobRule], + contextItems: emptyContextItems, }); // Should match src/main.ts but not config/settings.ts @@ -193,9 +281,125 @@ describe("getSystemMessageWithRules", () => { baseSystemMessage, userMessage, rules: [arrayGlobRule], + contextItems: emptyContextItems, }); // Should not match any file paths expect(result).toBe(baseSystemMessage); }); + + // New test for code block with filename only (no language) + it("should handle code blocks with filename only (no language identifier)", () => { + const userMessage: UserChatMessage = { + role: "user", + content: "```test.js\nclass Calculator { /* code */ }\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [jsRule, tsRule, generalRule], + contextItems: emptyContextItems, + }); + + // Should include JS rule and general rule + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + // New test for code blocks with line ranges + it("should handle code blocks with line ranges", () => { + const userMessage: UserChatMessage = { + role: "user", + content: "```js test.js (19-25)\ndivide(number) { /* code */ }\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [jsRule, tsRule, generalRule], + contextItems: emptyContextItems, + }); + + // Should include JS rule and general rule + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + // New test for mixed code block formats + it("should handle mixed code block formats in the same message", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```test.js\nclass Calculator { /* code */ }\n```\n" + + "```js utils.js (19-25)\ndivide(number) { /* code */ }\n```\n" + + "```ts config/settings.ts\nconst config = {};\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [jsRule, tsRule, generalRule], + contextItems: emptyContextItems, + }); + + // Should include JS rule, TS rule, and general rule + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + // Test for context items when there's no message + it("should apply rules based on context items only when no message is present", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [jsRule, tsRule, generalRule], + contextItems: [jsContextItem], + }); + + // Should include JS rule and general rule + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + // Test for non-file context items + it("should ignore non-file context items", () => { + const nonFileContextItem: ContextItemWithId = { + content: "Some search result", + name: "Search result", + description: "A search result", + id: { providerTitle: "search", itemId: "search-result" }, + // No uri with type "file" + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [jsRule, tsRule, generalRule], + contextItems: [nonFileContextItem], + }); + + // Should only include general rule + const expected = `${baseSystemMessage}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + // Test combining context items with message + it("should match rules from both message code blocks and context items", () => { + const userMessage: UserChatMessage = { + role: "user", + content: "```ts src/main.ts\nconsole.log('hello');\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [jsRule, tsRule, pythonRule, generalRule], + contextItems: [jsContextItem, pyContextItem], + }); + + // Should include JS, TS, Python rules and general rule + const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); }); diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 3d7372fef..19870a6da 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -1,5 +1,10 @@ import { minimatch } from "minimatch"; -import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; +import { + ContextItemWithId, + RuleWithSource, + ToolResultChatMessage, + UserChatMessage, +} from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; @@ -24,21 +29,34 @@ const matchesGlobs = ( }; /** - * Filters rules that apply to the given message + * Filters rules that apply to the given message and/or context items + * + * @param userMessage - The user or tool message to check for file paths in code blocks + * @param rules - The list of rules to filter + * @param contextItems - Context items to check for file paths + * @returns List of applicable rules */ export const getApplicableRules = ( userMessage: UserChatMessage | ToolResultChatMessage | undefined, rules: RuleWithSource[], + contextItems: ContextItemWithId[], ): RuleWithSource[] => { const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) : []; + // Extract file paths from context items + const filePathsFromContextItems = contextItems + .filter((item) => item.uri?.type === "file" && item.uri?.value) + .map((item) => item.uri!.value); + // Combine file paths from both sources + const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems]; + return rules.filter((rule) => { // A rule is active if it has no globs (applies to all files) // or if at least one file path matches its globs const hasNoGlobs = !rule.globs; - const matchesAnyFilePath = filePathsFromMessage.some((path) => + const matchesAnyFilePath = allFilePaths.some((path) => matchesGlobs(path, rule.globs), ); @@ -46,16 +64,27 @@ export const getApplicableRules = ( }); }; +/** + * Creates a system message string with applicable rules appended + * + * @param baseSystemMessage - The base system message to start with + * @param userMessage - The user message to check for file paths + * @param rules - The list of rules to filter + * @param contextItems - Context items to check for file paths + * @returns System message with applicable rules appended + */ export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, rules, + contextItems, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; rules: RuleWithSource[]; + contextItems: ContextItemWithId[]; }) => { - const applicableRules = getApplicableRules(userMessage, rules); + const applicableRules = getApplicableRules(userMessage, rules, contextItems); let systemMessage = baseSystemMessage ?? ""; for (const rule of applicableRules) { 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 c92bb93ee..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, + ); }); }); @@ -155,6 +191,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { expect(supportsFn("pixtral-12b-2409")).toBe(true); expect(supportsFn("pixtral-large-latest")).toBe(true); expect(supportsFn("open-mistral-nemo")).toBe(true); + expect(supportsFn("devstral-latest")).toBe(true); }); it("should return false for other unsupported models", () => { @@ -170,6 +207,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { expect(supportsFn("CODESTRAL-LATEST")).toBe(true); expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true); expect(supportsFn("PIXTRAL-12B-2409")).toBe(true); + expect(supportsFn("DEVSTRAL-LATEST")).toBe(true); }); }); @@ -192,6 +230,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { expect(supportsFn("aya-expanse")).toBe(true); expect(supportsFn("firefunction-v2")).toBe(true); expect(supportsFn("mistral-7b")).toBe(true); + expect(supportsFn("devstral-24b")).toBe(true); }); it("should return false for explicitly unsupported models", () => { @@ -203,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", () => { @@ -218,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 8a96a4d60..e6d4387ce 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -1,235 +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", - "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"].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"].some((part) => - model.toLowerCase().includes(part), - ) - ) { - return true; - } - }, - mistral: (model) => { - // https://docs.mistral.ai/capabilities/function_calling/ - return ( - !model.toLowerCase().includes("mamba") && - [ - "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", - ].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/llm/utils/extractPathsFromCodeBlocks.test.ts b/core/llm/utils/extractPathsFromCodeBlocks.test.ts new file mode 100644 index 000000000..93959a392 --- /dev/null +++ b/core/llm/utils/extractPathsFromCodeBlocks.test.ts @@ -0,0 +1,35 @@ +import { extractPathsFromCodeBlocks } from "./extractPathsFromCodeBlocks"; + +describe("extractPathsFromCodeBlocks", () => { + it("should extract paths from code blocks with language and filepath", () => { + const content = "```typescript src/main.ts\nconst x = 1;\n```"; + expect(extractPathsFromCodeBlocks(content)).toEqual(["src/main.ts"]); + }); + + it("should extract paths from code blocks with filepath only (no language)", () => { + const content = "```test.js\nclass Calculator { }\n```"; + expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]); + }); + + it("should extract paths from code blocks with line ranges", () => { + const content = "```js test.js (19-25)\nfunction test() {}\n```"; + expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]); + }); + + it("should handle multiple code blocks with different formats", () => { + const content = + "```typescript src/main.ts\nconst x = 1;\n```\n" + + "```test.js\nclass Calculator { }\n```\n" + + "```js utils.js (19-25)\nfunction test() {}\n```"; + const result = extractPathsFromCodeBlocks(content); + expect(result).toContain("src/main.ts"); + expect(result).toContain("test.js"); + expect(result).toContain("utils.js"); + expect(result.length).toBe(3); + }); + + it("should not extract paths from code blocks without file paths", () => { + const content = "```typescript\nconst x = 1;\n```"; + expect(extractPathsFromCodeBlocks(content)).toEqual([]); + }); +}); \ No newline at end of file diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts index 7573a1f6f..00f723c7a 100644 --- a/core/llm/utils/extractPathsFromCodeBlocks.ts +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -2,21 +2,37 @@ * Extracts file paths from markdown code blocks */ export function extractPathsFromCodeBlocks(content: string): string[] { - // Match: - // 1. Starting ``` - // 2. Optional language identifier - // 3. Required whitespace - // 4. File path (captured) that must contain a dot and extension - const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g; - const paths: string[] = []; - let match; + console.log("CONTENT", content); - while ((match = codeBlockRegex.exec(content)) !== null) { - const path = match[1]; - if (path && !path.startsWith("```")) { - paths.push(path); + const paths: string[] = []; + + // Match code block opening patterns: + // 1. ```language filepath + // 2. ```filepath + // 3. ```language filepath (range) + + // First match all code block starts + const codeBlockStarts = content.match(/```[^\n]+/g) || []; + + for (const blockStart of codeBlockStarts) { + // Try to extract a valid filename with extension + const filenameMatches = blockStart.match(/([^\s()```]+\.[a-zA-Z0-9]+)/); + + if (filenameMatches && filenameMatches[1]) { + const filename = filenameMatches[1]; + + // Verify this is a legitimate filename (not part of something else) + if ( + // Check if valid extension + /\.[a-zA-Z0-9]+$/.test(filename) && + // Make sure it's not a URL + !filename.includes("://") && + // Avoid duplicates + !paths.includes(filename) + ) { + paths.push(filename); + } } } - return paths; } diff --git a/core/package-lock.json b/core/package-lock.json index ea049ae74..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.5.0", + "@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", @@ -55,6 +55,7 @@ "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", + "plist": "^3.1.0", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", "puppeteer-chromium-resolver": "^23.0.0", @@ -91,6 +92,7 @@ "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", + "@types/plist": "^3.0.5", "@types/request": "^2.48.12", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", @@ -110,7 +112,10 @@ "node": ">=20.19.0" } }, - "../../../../../documents/code/continuedev/continue/packages/config-yaml": { + "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { + "extraneous": true + }, + "../../../../documents/code/continuedev/continue/packages/config-yaml": { "version": "1.0.78", "extraneous": true, "license": "Apache-2.0", @@ -131,12 +136,9 @@ "ts-node": "^10.9.2" } }, - "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { - "extraneous": true - }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.87", + "version": "1.0.88", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -2925,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", @@ -2942,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", @@ -3737,12 +3741,18 @@ ] }, "node_modules/@modelcontextprotocol/sdk": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz", - "integrity": "sha512-IJ+5iVVs8FCumIHxWqpwgkwOzyhtHVKy45s6Ug7Dv0MfRpaYisH8QQ87rIWeWdOzlk8sfhitZ7HCyQZk7d6b8w==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.12.0.tgz", + "integrity": "sha512-m//7RlINx1F3sz3KqwY1WWzVgTcYX52HYk4bJ1hkBXV3zccAEth+jRvG8DBRrdaQuRsPAJOx2MH3zaHNCKL7Zg==", "dependencies": { + "ajv": "^6.12.6", "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" @@ -4938,6 +4948,16 @@ "pg-types": "^4.0.1" } }, + "node_modules/@types/plist": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz", + "integrity": "sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==", + "dev": true, + "dependencies": { + "@types/node": "*", + "xmlbuilder": ">=11.0.1" + } + }, "node_modules/@types/readable-stream": { "version": "4.0.18", "resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.18.tgz", @@ -5258,6 +5278,14 @@ "onnxruntime-node": "1.14.0" } }, + "node_modules/@xmldom/xmldom": { + "version": "0.8.10", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.10.tgz", + "integrity": "sha512-2WALfTl4xo2SkGCYRt6rDTFfk9R1czmBvUQy12gK2KuRKIpWEhcbbzy8EZXtz/jkRqHX8bFEc6FC1HjX4TUWYw==", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/@yomguithereal/helpers": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@yomguithereal/helpers/-/helpers-1.1.1.tgz", @@ -5287,6 +5315,45 @@ "node": ">=6.5" } }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/acorn": { "version": "8.14.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", @@ -6018,6 +6085,39 @@ "readable-stream": "^4.2.0" } }, + "node_modules/body-parser": { + "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==", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/body-parser/node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -6247,9 +6347,9 @@ } }, "node_modules/call-bind-apply-helpers": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz", - "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==", + "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==", "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" @@ -6258,6 +6358,21 @@ "node": ">= 0.4" } }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -6640,6 +6755,17 @@ "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" }, + "node_modules/content-disposition": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", + "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/content-type": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", @@ -6654,6 +6780,22 @@ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "engines": { + "node": ">=6.6.0" + } + }, "node_modules/core-js-compat": { "version": "3.39.0", "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.39.0.tgz", @@ -6672,6 +6814,18 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/cosmiconfig": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", @@ -7181,11 +7335,11 @@ } }, "node_modules/dunder-proto": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.0.tgz", - "integrity": "sha512-9+Sj30DIu+4KvHqMfLUGLFYL2PkURSYMVXJyXe92nFRvlYq5hBjLEhblKB+vkd/WVlUYMWigiY07T91Fkk0+4A==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", "dependencies": { - "call-bind-apply-helpers": "^1.0.0", + "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" }, @@ -7220,6 +7374,11 @@ "safe-buffer": "^5.0.1" } }, + "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==" + }, "node_modules/eight-colors": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/eight-colors/-/eight-colors-1.3.1.tgz", @@ -7268,6 +7427,14 @@ "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/encoding": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", @@ -7463,9 +7630,9 @@ } }, "node_modules/es-object-atoms": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", - "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "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==", "dependencies": { "es-errors": "^1.3.0" }, @@ -7558,6 +7725,11 @@ "node": ">=6" } }, + "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==" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -7933,6 +8105,14 @@ "node": ">=0.10.0" } }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -8024,6 +8204,94 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/express": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", + "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "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==", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": "^4.11 || 5 || ^5.0.0-beta.1" + } + }, + "node_modules/express/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -8250,6 +8518,22 @@ "resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz", "integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A==" }, + "node_modules/finalhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/find-replace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", @@ -8417,6 +8701,22 @@ "node": ">=12.20.0" } }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", @@ -8619,18 +8919,20 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.5.tgz", - "integrity": "sha512-Y4+pKa7XeRUPWFNvOOYHkRYrfzW07oraURSvjDmRVOJ748OrVmeXtpE4+GCEHncjCjkTxPNRt8kEbxDhsn6VTg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "dependencies": { - "call-bind-apply-helpers": "^1.0.0", - "dunder-proto": "^1.0.0", + "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", + "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", - "hasown": "^2.0.2" + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -8648,6 +8950,18 @@ "node": ">=8.0.0" } }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-stream": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", @@ -9320,6 +9634,14 @@ "node": ">= 12" } }, + "node_modules/ipaddr.js": { + "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==", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-array-buffer": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", @@ -9604,6 +9926,11 @@ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==" }, + "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==" + }, "node_modules/is-property": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", @@ -11442,6 +11769,33 @@ "tmpl": "1.0.5" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -12112,11 +12466,18 @@ "node": "*" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { "version": "1.13.3", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", - "peer": true, "engines": { "node": ">= 0.4" }, @@ -12230,6 +12591,17 @@ "whatwg-fetch": "^3.6.20" } }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -12599,6 +12971,14 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/partial-json": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", @@ -12661,6 +13041,14 @@ "node": ">=16 || 14 >=14.17" } }, + "node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "engines": { + "node": ">=16" + } + }, "node_modules/path-type": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", @@ -12855,6 +13243,14 @@ "node": ">= 6" } }, + "node_modules/pkce-challenge": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.0.tgz", + "integrity": "sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -12924,6 +13320,19 @@ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==" }, + "node_modules/plist": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz", + "integrity": "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==", + "dependencies": { + "@xmldom/xmldom": "^0.8.8", + "base64-js": "^1.5.1", + "xmlbuilder": "^15.1.1" + }, + "engines": { + "node": ">=10.4.0" + } + }, "node_modules/possible-typed-array-names": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", @@ -13205,6 +13614,18 @@ "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" }, + "node_modules/proxy-addr": { + "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==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/proxy-agent": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", @@ -13447,6 +13868,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/raw-body": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", @@ -13804,6 +14233,21 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/rrweb-cssom": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", @@ -13922,11 +14366,65 @@ "semver": "bin/semver.js" } }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/send/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/send/node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/seq-queue": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", @@ -14022,15 +14520,65 @@ } }, "node_modules/side-channel": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", - "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", - "peer": true, + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", "dependencies": { - "call-bind": "^1.0.7", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.4", - "object-inspect": "^1.13.1" + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "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==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -15106,6 +15654,38 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/mime-types": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", + "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/typed-array-buffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", @@ -15441,6 +16021,14 @@ "node": ">=10.12.0" } }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/vectordb": { "version": "0.4.20", "resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.20.tgz", @@ -15922,6 +16510,14 @@ "node": ">=18" } }, + "node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "engines": { + "node": ">=8.0" + } + }, "node_modules/xmlchars": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", diff --git a/core/package.json b/core/package.json index 9332baa21..5622cc903 100644 --- a/core/package.json +++ b/core/package.json @@ -27,6 +27,7 @@ "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", + "@types/plist": "^3.0.5", "@types/request": "^2.48.12", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", @@ -48,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.5.0", + "@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", @@ -89,6 +90,7 @@ "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", + "plist": "^3.1.0", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", "puppeteer-chromium-resolver": "^23.0.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index ef4cde60b..142764d19 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -33,7 +33,7 @@ import { ToolCall, } from "../"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; -import { ControlPlaneSessionInfo } from "../control-plane/client"; +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -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/protocol/ide.ts b/core/protocol/ide.ts index 88e7f779c..324772ace 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,5 +1,3 @@ -import { ControlPlaneSessionInfo } from "../control-plane/client"; - import type { ContinueRcJson, DiffLine, @@ -16,6 +14,7 @@ import type { TerminalOptions, Thread, } from "../"; +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; export interface GetGhTokenArgs { force?: boolean; @@ -99,7 +98,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { ControlPlaneSessionInfo | undefined, ]; logoutOfControlPlane: [undefined, void]; - reportError:[any, void]; + reportError: [any, void]; closeSidebar: [undefined, void]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 3c836126a..540f8a7e3 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -2,12 +2,13 @@ import { ToIdeFromWebviewOrCoreProtocol } from "./ide"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { + AcceptOrRejectDiffPayload, ApplyState, - SetCodeToEditPayload, HighlightedCodePayload, MessageContent, RangeInFileWithContents, - AcceptOrRejectDiffPayload, + SetCodeToEditPayload, + ShowFilePayload, } from "../"; export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { @@ -23,7 +24,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { ]; overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; - showFile: [{ filepath: string }, void]; + showFile: [ShowFilePayload, void]; toggleDevTools: [undefined, void]; reloadWindow: [undefined, void]; focusEditor: [undefined, void]; @@ -41,7 +42,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { vscMediaUrl: string; }, ]; - "jetbrains/getColors": [undefined, Record]; + "jetbrains/getColors": [undefined, Record]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; acceptDiff: [AcceptOrRejectDiffPayload, void]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 2e6ec3cff..5ba47e3d4 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,6 +1,6 @@ import { ConfigResult } from "@continuedev/config-yaml"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; -import { ControlPlaneSessionInfo } from "../control-plane/client.js"; +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, @@ -40,7 +40,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { setTTSActive: [boolean, void]; getWebviewHistoryLength: [undefined, number]; getCurrentSessionId: [undefined, string]; - "jetbrains/setColors": [Record, void]; + "jetbrains/setColors": [Record, void]; sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; }; diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 730e1ab32..937afb964 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -28,6 +28,10 @@ export const createRuleBlock: Tool = { description: "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", }, + description: { + type: "string", + description: "Short description of the rule", + }, globs: { type: "string", description: diff --git a/core/tools/implementations/createRuleBlock.test.ts b/core/tools/implementations/createRuleBlock.test.ts index 0491b8e26..04bd3d45c 100644 --- a/core/tools/implementations/createRuleBlock.test.ts +++ b/core/tools/implementations/createRuleBlock.test.ts @@ -1,4 +1,4 @@ -import * as YAML from "yaml"; +import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule"; import { createRuleBlockImpl } from "./createRuleBlock"; // Mock the extras parameter with necessary functions @@ -17,33 +17,6 @@ describe("createRuleBlockImpl", () => { jest.clearAllMocks(); }); - it("should create a basic rule with name and rule content", async () => { - const args = { - name: "Test Rule", - rule: "Always write tests", - }; - - const result = await createRuleBlockImpl(args, mockExtras as any); - - // Verify that writeFile was called with the correct YAML - expect(mockIde.writeFile).toHaveBeenCalled(); - const yamlContent = mockIde.writeFile.mock.calls[0][1]; - const parsedYaml = YAML.parse(yamlContent); - - // Verify the structure of the YAML - expect(parsedYaml).toEqual({ - name: "Test Rule", - version: "0.0.1", - schema: "v1", - rules: [ - { - name: "Test Rule", - rule: "Always write tests", - }, - ], - }); - }); - it("should create a rule with glob pattern", async () => { const args = { name: "TypeScript Rule", @@ -53,14 +26,16 @@ describe("createRuleBlockImpl", () => { await createRuleBlockImpl(args, mockExtras as any); - // Verify the YAML structure with globs - const yamlContent = mockIde.writeFile.mock.calls[0][1]; - const parsedYaml = YAML.parse(yamlContent); - expect(parsedYaml.rules[0]).toEqual({ - name: "TypeScript Rule", - rule: "Use interfaces for object shapes", + const fileContent = mockIde.writeFile.mock.calls[0][1]; + + const { frontmatter, markdown } = parseMarkdownRule(fileContent); + + expect(frontmatter).toEqual({ globs: "**/*.{ts,tsx}", }); + + expect(markdown).toContain("# TypeScript Rule"); + expect(markdown).toContain("Use interfaces for object shapes"); }); it("should create a filename based on sanitized rule name", async () => { @@ -71,8 +46,51 @@ describe("createRuleBlockImpl", () => { await createRuleBlockImpl(args, mockExtras as any); - // Check that the filename is sanitized const fileUri = mockIde.writeFile.mock.calls[0][0]; - expect(fileUri).toContain("special-chracters-spaces.yaml"); + expect(fileUri).toContain("special-chracters-spaces.md"); + }); + + it("should create a rule with description pattern", async () => { + const args = { + name: "Description Test", + rule: "This is the rule content", + description: "This is a detailed explanation of the rule", + }; + + await createRuleBlockImpl(args, mockExtras as any); + + const fileContent = mockIde.writeFile.mock.calls[0][1]; + + const { frontmatter, markdown } = parseMarkdownRule(fileContent); + + expect(frontmatter).toEqual({ + description: "This is a detailed explanation of the rule", + }); + + expect(markdown).toContain("# Description Test"); + expect(markdown).toContain("This is the rule content"); + }); + + it("should include both globs and description in frontmatter", async () => { + const args = { + name: "Complete Rule", + rule: "Follow this standard", + description: "This rule enforces our team standards", + globs: "**/*.js", + }; + + await createRuleBlockImpl(args, mockExtras as any); + + const fileContent = mockIde.writeFile.mock.calls[0][1]; + + const { frontmatter, markdown } = parseMarkdownRule(fileContent); + + expect(frontmatter).toEqual({ + description: "This rule enforces our team standards", + globs: "**/*.js", + }); + + expect(markdown).toContain("# Complete Rule"); + expect(markdown).toContain("Follow this standard"); }); }); diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index 87702e866..c1b7d4888 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -1,4 +1,3 @@ -import { ConfigYaml } from "@continuedev/config-yaml"; import * as YAML from "yaml"; import { ToolImpl } from "."; import { joinPathsToUri } from "../../util/uri"; @@ -6,6 +5,7 @@ import { joinPathsToUri } from "../../util/uri"; export interface CreateRuleBlockArgs { name: string; rule: string; + description: string; globs?: string; } @@ -19,41 +19,46 @@ export const createRuleBlockImpl: ToolImpl = async ( .replace(/[^a-z0-9\s-]/g, "") .replace(/\s+/g, "-"); - const ruleObject = { - name: args.name, - rule: args.rule, - ...(args.globs ? { globs: args.globs.trim() } : {}), - }; + const fileExtension = "md"; - const ruleBlock: ConfigYaml = { - name: args.name, - version: "0.0.1", - schema: "v1", - rules: [ruleObject], - }; + const frontmatter: Record = {}; - const ruleYaml = YAML.stringify(ruleBlock); + if (args.globs) { + frontmatter.globs = args.globs.trim(); + } + if (args.description) { + frontmatter.description = args.description.trim(); + } + const frontmatterYaml = YAML.stringify(frontmatter).trim(); + let fileContent = `--- +${frontmatterYaml} +--- + +# ${args.name} + +${args.rule} +`; const [localContinueDir] = await extras.ide.getWorkspaceDirs(); const rulesDirUri = joinPathsToUri( localContinueDir, ".continue", "rules", - `${safeRuleName}.yaml`, + `${safeRuleName}.${fileExtension}`, ); - await extras.ide.writeFile(rulesDirUri, ruleYaml); + await extras.ide.writeFile(rulesDirUri, fileContent); await extras.ide.openFile(rulesDirUri); return [ { name: "New Rule Block", - description: "", // No description throws an error in the GUI + description: args.description || "", uri: { type: "file", value: rulesDirUri, }, - content: "Rule created successfully", + content: `Rule created successfully`, }, ]; }; 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 e8b915813..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 [ @@ -406,7 +407,7 @@ Destinations to which [development data](./customize/deep-dives/development-data - `destination` (**required**): The destination/endpoint that will receive the data. Can be: - an HTTP endpoint that will receive a POST request with a JSON blob - a file URL to a directory in which events will be dumpted to `.jsonl` files -- `schema` (**required**): the schema version of the JSON blobs to be sent +- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0` - `events`: an array of event names to include. Defaults to all events if not specified. - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index 9692191eb..405417a27 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -120,6 +120,8 @@ If you're seeing a `fetch failed` error and your network requires custom certifi You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates. +***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue. + #### VS Code Proxy Settings If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl + , to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 030e9980c..f973d446b 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -66,7 +66,9 @@ const config = { ], scripts: [ - '!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();', + { + src: "/scripts/custom-reo.js", // it references from static folder + }, ], themeConfig: diff --git a/docs/static/scripts/custom-reo.js b/docs/static/scripts/custom-reo.js new file mode 100644 index 000000000..cc8c7bebc --- /dev/null +++ b/docs/static/scripts/custom-reo.js @@ -0,0 +1 @@ +!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}(); \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt index ae26033e5..8c046c342 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -11,15 +11,19 @@ import org.jetbrains.annotations.NotNull class ContinueActionPromote : ActionPromoter { override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? { - - if (actions.none { it is AcceptAutocompleteAction }) { - return null - } else { + // For autocomplete actions + if (actions.any { it is AcceptAutocompleteAction }) { val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) - if (!settings.continueState.showIDECompletionSideBySide) { - return null; + if (settings.continueState.showIDECompletionSideBySide) { + return actions.filterIsInstance() } - return actions.filterIsInstance() } + + val rejectDiffActions = actions.filterIsInstance() + if (rejectDiffActions.isNotEmpty()) { + return rejectDiffActions + } + + return null } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index 27e4aebe2..863bbec56 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -1,25 +1,12 @@ package com.github.continuedev.continueintellijextension.actions import com.github.continuedev.continueintellijextension.editor.DiffStreamService -import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.project.Project -import com.intellij.openapi.wm.ToolWindowManager -fun getPluginService(project: Project?): ContinuePluginService? { - if (project == null) { - return null - } - return ServiceManager.getService( - project, - ContinuePluginService::class.java - ) -} class AcceptDiffAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { @@ -29,7 +16,7 @@ class AcceptDiffAction : AnAction() { private fun acceptHorizontalDiff(e: AnActionEvent) { val continuePluginService = getPluginService(e.project) ?: return - continuePluginService?.diffManager?.acceptDiff(null) + continuePluginService.diffManager?.acceptDiff(null) } private fun acceptVerticalDiff(e: AnActionEvent) { @@ -61,28 +48,6 @@ class RejectDiffAction : AnAction() { } } -fun getContinuePluginService(project: Project?): ContinuePluginService? { - if (project != null) { - val toolWindowManager = ToolWindowManager.getInstance(project) - val toolWindow = toolWindowManager.getToolWindow("Continue") - - if (toolWindow != null) { - if (!toolWindow.isVisible) { - toolWindow.activate(null) - } - } - } - - return getPluginService(project) -} - -fun focusContinueInput(project: Project?) { - val continuePluginService = getContinuePluginService(project) ?: return - continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) - - continuePluginService.ideProtocolClient?.sendHighlightedCode() -} class FocusContinueInputWithoutClearAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { @@ -134,8 +99,11 @@ class OpenLogsAction : AnAction() { if (logFile.exists()) { val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile) if (virtualFile != null) { - com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true) + FileEditorManager.getInstance(project).openFile(virtualFile, true) } } } } + + + diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt new file mode 100644 index 000000000..1bd31c463 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt @@ -0,0 +1,39 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.project.Project +import com.intellij.openapi.wm.ToolWindowManager + +fun getContinuePluginService(project: Project?): ContinuePluginService? { + if (project != null) { + val toolWindowManager = ToolWindowManager.getInstance(project) + val toolWindow = toolWindowManager.getToolWindow("Continue") + + if (toolWindow != null) { + if (!toolWindow.isVisible) { + toolWindow.activate(null) + } + } + } + + return getPluginService(project) +} + +fun focusContinueInput(project: Project?) { + val continuePluginService = getContinuePluginService(project) ?: return + continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() + continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) + + continuePluginService.ideProtocolClient?.sendHighlightedCode() +} + +fun getPluginService(project: Project?): ContinuePluginService? { + if (project == null) { + return null + } + return ServiceManager.getService( + project, + ContinuePluginService::class.java + ) +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt deleted file mode 100644 index 75f0d3aff..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.actionSystem.ActionUpdateThread -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.DefaultActionGroup -import com.intellij.openapi.components.service - -class AutocompleteActionGroup : DefaultActionGroup() { - override fun getActionUpdateThread(): ActionUpdateThread { - return ActionUpdateThread.EDT - } - - override fun update(e: AnActionEvent) { - super.update(e) - removeAll() - - val continueSettingsService = service() - if (continueSettingsService.continueState.enableTabAutocomplete) { - addAll( - DisableTabAutocompleteAction(), - ) - } else { - addAll( - EnableTabAutocompleteAction(), - ) - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index a8edd5527..755b16d85 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -121,10 +121,10 @@ class ApplyToFileHandler( val prompt = buildApplyPrompt() // Extract the code ranges (highlighted or full document) - val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges() + val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet() // Get the line range for the diff stream - val rif = editorUtils.getHighlightedCode() + val rif = editorUtils.getHighlightedRIF() val startLine = rif?.range?.start?.line ?: 0 val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1) 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/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt index 6aecca81b..357757fe0 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -2,11 +2,13 @@ package com.github.continuedev.continueintellijextension.`continue` import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.colors.CodeInsightColors import java.awt.Color import kotlin.math.max import kotlin.math.min import com.intellij.ui.JBColor import com.intellij.ui.ColorUtil +import kotlin.math.roundToInt class GetTheme { fun getSecondaryDark(): Color { @@ -38,64 +40,173 @@ class GetTheme { return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground } - fun getTheme(): Map { - fun toHex(color: Color): String { - return String.format("#%02x%02x%02x", color.red, color.green, color.blue) + fun toHex(color: Color?): String? { + if(color == null) { + return null } + return String.format("#%02x%02x%02x", color.red, color.green, color.blue) + } + + fun namedColor(name: String): Color? { + // JB Color named color will fall back to a default unless we give it a fallback + // We want defaults to be handled on the GUI side, so we give it this filler color + // Which has a very low chance of conflicting with a real one + // And return undefined if it gets the skip color + val SKIP_COLOR = Color (18, 52, 86) // Hex #123456 + val color = JBColor.namedColor(name, SKIP_COLOR) + if(toHex(color) == "#123456") { + return null + } + return color + } + + fun lighten(color: Color, percentage: Int = 5): Color { + // Increase each RGB component slightly + val factor = 1 + percentage / 100f; + fun lightenInt(value: Int): Int { + return (value * factor).roundToInt().coerceAtMost(255) + } + return Color( + lightenInt(color.red), + lightenInt (color.green), + lightenInt(color.blue), + color.alpha + ) + } + + fun darken(color: Color, percentage: Int = 5): Color { + // Decrease each RGB component slightly + val factor = 1 - percentage / 100f; + fun darkenInt(value: Int): Int { + return (value * factor).roundToInt().coerceAtLeast(0) + } + return Color( + darkenInt(color.red), + darkenInt(color.green), + darkenInt(color.blue), + color.alpha + ) + } + + fun slightChange(color: Color?, percentage: Int = 5): Color? { + if(color == null){ + return null + } + // If dark, make slightly lighter. If light, make slightly darker + val averageRgb = (color.red + color.green + color.blue) / 3 + return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage) + } + + fun getTheme(): Map { try { + val editorScheme = EditorColorsManager.getInstance().globalScheme + val background = JBColor.background() val foreground = JBColor.foreground() - val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230)) - val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0)) - - val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150)) - val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0)) - - val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255)) - val border = JBColor.border() - val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255)) - val editorScheme = EditorColorsManager.getInstance().globalScheme + val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor") + + val buttonBackground = namedColor("Button.default.startBackground") + ?: namedColor("Button.default.background") + + val buttonForeground = namedColor("Button.default.startForeground") + ?: namedColor("Button.default.foreground") + + val buttonHoverBackground = namedColor("Button.default.hoverStartBackground") + ?: namedColor("Button.default.hoverBackground") + ?: namedColor("Button.default.startHoverBackground") + ?: slightChange(buttonBackground) + + val secondaryBackground = namedColor("Button.background") ?: background + val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground) + + val badgeBackground = namedColor("Badge.background") + val badgeForeground = namedColor("Badge.foreground") + + val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background") + val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground") + + val inputBackground = namedColor("TextField.background") + val inputForeground = namedColor("TextField.foreground") + val inputPlaceholder = namedColor("TextField.inactiveForeground") + + val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background) + val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground") + + val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor") + val listSelectionForeground = namedColor("List.selectionForeground") + + val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground") + + val mutedDescription = namedColor("Component.infoForeground") + ?: namedColor("ContextHelp.foreground") + ?: namedColor("TextField.placeholderForeground") + ?: namedColor("Label.disabledForeground") + ?: namedColor("ToolTip.foreground") + + val link = namedColor("Link.activeForeground") + + val successColor = namedColor("ValidationSuccess.successColor") + ?: namedColor("Component.successForeground") + ?: namedColor("Label.successForeground") + val warningColor = namedColor("ValidationWarning.warningColor") + ?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor + ?: namedColor("Component.warningForeground") + ?: namedColor("Label.warningForeground") + val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground") + + val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor") val editorBackground = editorScheme.defaultBackground val editorForeground = editorScheme.defaultForeground - val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220)) - - val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0) + val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor + val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?: + editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor + + // These should match the keys in GUI's theme.ts val theme = mapOf( - "--vscode-editor-foreground" to toHex(editorForeground), - "--vscode-editor-background" to toHex(editorBackground), - - "--vscode-button-background" to toHex(buttonBackground), - "--vscode-button-foreground" to toHex(buttonForeground), - - "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50", - - "--vscode-quickInputList-focusForeground" to toHex(foreground), - "--vscode-quickInput-background" to toHex(inputBackground), - - "--vscode-badge-background" to toHex(badgeBackground), - "--vscode-badge-foreground" to toHex(badgeForeground), - - "--vscode-input-background" to toHex(inputBackground), - "--vscode-input-border" to toHex(border), - "--vscode-sideBar-background" to toHex(background), - "--vscode-sideBar-border" to toHex(border), - "--vscode-focusBorder" to toHex(focusBorder), - - "--vscode-commandCenter-activeBorder" to toHex(focusBorder), - "--vscode-commandCenter-inactiveBorder" to toHex(border), - - "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40" - ) - + "background" to background, + "foreground" to foreground, + "editor-background" to editorBackground, + "editor-foreground" to editorForeground, + "primary-background" to buttonBackground, + "primary-foreground" to buttonForeground, + "primary-hover" to buttonHoverBackground, + "secondary-background" to secondaryBackground, + "secondary-foreground" to foreground, + "secondary-hover" to secondaryHoverBackground, + "border" to border, + "border-focus" to focusBorder, + "command-background" to commandBackground, + "command-foreground" to commandForeground, + "command-border" to border, + "command-border-focus" to focusBorder, + "description" to description, + "description-muted" to mutedDescription, + "input-background" to inputBackground, + "input-foreground" to inputForeground, + "input-border" to border, + "input-placeholder" to inputPlaceholder, + "table-oddRow" to tableOddRow, + "badge-background" to badgeBackground, + "badge-foreground" to badgeForeground, + "success" to successColor, + "warning" to warningColor, + "error" to errorColor, + "link" to link, + "accent" to accentColor, + "find-match" to findMatchBackground, + "find-match-selected" to findMatchSelectedBackground, + "list-hover" to listHoverBackground, + "list-active" to actionHoverBackground, + "list-active-foreground" to listSelectionForeground + ).mapValues { toHex(it.value) } return theme } catch (error: Error) { return mapOf() } - } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index cc9f018fa..d0527313a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -91,6 +91,15 @@ class IdeProtocolClient( respond(jsonData) } + "showFile" -> { + val params = Gson().fromJson( + dataElement.toString(), + ShowFilePayload::class.java + ) + ide.openFile(params.filepath) + respond(null) + } + "getIdeSettings" -> { val settings = ide.getIdeSettings() respond(settings) @@ -438,7 +447,7 @@ class IdeProtocolClient( "acceptDiff" -> { val params = Gson().fromJson( dataElement.toString(), - AcceptDiffParams::class.java + AcceptOrRejectDiffPayload::class.java ) val filepath = params.filepath; @@ -454,7 +463,7 @@ class IdeProtocolClient( "rejectDiff" -> { val params = Gson().fromJson( dataElement.toString(), - RejectDiffParams::class.java + AcceptOrRejectDiffPayload::class.java ) val filepath = params.filepath; @@ -493,7 +502,7 @@ class IdeProtocolClient( fun sendHighlightedCode(edit: Boolean = false) { val editor = EditorUtils.getEditor(project) - val rif = editor?.getHighlightedCode() ?: return + val rif = editor?.getHighlightedRIF() ?: return continuePluginService.sendToWebview( "highlightedCode", 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 b4c9d14ca..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 @@ -337,6 +337,5 @@ class DiffStreamHandler( private fun setClosed() { sendUpdate(ApplyStateStatus.CLOSED) resetState() - onClose() } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt index 23b1b1bcd..857c0104f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt @@ -1,7 +1,5 @@ package com.github.continuedev.continueintellijextension.editor -import com.github.continuedev.continueintellijextension.Position -import com.github.continuedev.continueintellijextension.Range import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction @@ -72,28 +70,33 @@ class EditorUtils(val editor: Editor) { editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP) } + /** + * Remove the selected range in a thread-safe manner + */ + fun removeSelection() { + ApplicationManager.getApplication().invokeLater { + editor.selectionModel.removeSelection() + } + } /** * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix) */ - fun extractCodeRanges(): Triple { - val rif = getHighlightedCode() + fun getHighlightedRangeTriplet(): Triple { + val rif = getHighlightedRIF() return if (rif == null) { // If no highlight, use the whole document as highlighted Triple("", editor.document.text, "") } else { // Use the RangeInFileWithContents to get absolute offsets - val startOffset = rif.getStartOffset(editor.document) - val endOffset = rif.getEndOffset(editor.document) + val (startOffset, endOffset) = rif.offsets + val prefix = editor.document.getText(TextRange(0, startOffset)) val highlighted = rif.contents val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) - // Remove the selection after processing - ApplicationManager.getApplication().invokeLater { - editor.selectionModel.removeSelection() - } + removeSelection() Triple(prefix, highlighted, suffix) } @@ -103,7 +106,7 @@ class EditorUtils(val editor: Editor) { * Gets the selected code from the current editor. * Returns null if there is no selection. */ - fun getHighlightedCode(): RangeInFileWithContents? { + fun getHighlightedRIF(): RangeInFileWithContents? { return ApplicationManager.getApplication().runReadAction { val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index 9e597b621..4caac4ffd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -1,337 +1,11 @@ package com.github.continuedev.continueintellijextension.editor -import com.github.continuedev.continueintellijextension.`continue`.GetTheme -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull -import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel -import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel -import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.colors.EditorColorsManager -import com.intellij.openapi.editor.colors.EditorFontType -import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.DumbAware -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.IconLoader -import com.intellij.openapi.util.Ref -import com.intellij.openapi.util.TextRange -import com.intellij.ui.JBColor -import com.intellij.util.ui.JBUI -import com.intellij.util.ui.UIUtil -import java.awt.* -import java.awt.event.* -import java.awt.geom.AffineTransform -import java.awt.geom.Path2D -import java.awt.geom.RoundRectangle2D -import javax.swing.* -import javax.swing.event.DocumentEvent -import javax.swing.event.DocumentListener -import javax.swing.event.ListDataListener -import javax.swing.plaf.basic.BasicComboBoxUI -import kotlin.math.max -import net.miginfocom.swing.MigLayout -import org.jdesktop.swingx.JXPanel -import org.jdesktop.swingx.JXTextArea -const val MAIN_FONT_SIZE = 13 - -const val DOWN_ARROW = " โ–พ" - -fun makeTextArea(): JTextArea { - val textArea = - CustomTextArea(1, 40).apply { - lineWrap = true - wrapStyleWord = true - isOpaque = false - background = GetTheme().getSecondaryDark() - maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) - margin = JBUI.insets(6, 8, 2, 4) - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) - preferredSize = Dimension(400, 75) - } - textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - return textArea -} - -fun makePanel( - project: Project, - customPanelRef: Ref, - textArea: JTextArea, - inlayRef: Ref, - comboBoxRef: Ref>, - leftInset: Int, - modelTitles: List, - onEnter: () -> Unit, - onCancel: () -> Unit, - onAccept: () -> Unit, - onReject: () -> Unit -): JPanel { - val topPanel = - ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply { - background = JBColor(0x20888888, 0x20888888) - isOpaque = false - } - - val panel = - CustomPanel( - MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), - project, - modelTitles, - comboBoxRef, - onEnter, - onCancel, - onAccept, - onReject, - textArea - ) - .apply { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - background = defaultBackground - add(textArea, "grow, gap 0!, height 100%") - - putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - preferredSize = textArea.preferredSize - setup() - } - - customPanelRef.set(panel) - - textArea.addComponentListener( - object : ComponentAdapter() { - override fun componentResized(e: ComponentEvent?) { - panel.revalidate() - panel.repaint() - } - }) - - topPanel.add(panel, "grow, gap 0!") - - return topPanel -} - -fun openInlineEdit(project: Project?, editor: Editor) { - if (project == null) return - - // Don't open in terminal - if (EditorUtils(editor).isTerminal()) { - return - } - - val manager = EditorComponentInlaysManager.from(editor, true) - - // Get list of model titles - val continuePluginService = project.service() - val modelTitles = mutableListOf() - - continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val modelsByRole = - response.castNestedOrNull>("content", "result", "config", "modelsByRole") ?: return@request - val role = if (modelsByRole.containsKey("edit")) "edit" else "chat" - modelsByRole.castNestedOrNull>(role) - ?.mapNotNull { it.castNestedOrNull("title") } - ?.let(modelTitles::addAll) - } - - // This is a hacky way to not complicate getting model titles with coroutines - // 1500 feels like way upper limit of "would be weird if panel showed up after that long" - // And should always allow enough time to load config - val maxWaitTime = 1500 - val startTime = System.currentTimeMillis() - while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { - Thread.sleep(20) - } - - // Get highlighted range - val selectionModel = editor.selectionModel - val startOffset = selectionModel.selectionStart - val endOffset = selectionModel.selectionEnd - val startLineNumber = editor.document.getLineNumber(startOffset) - var endLineNumber = editor.document.getLineNumber(endOffset) - - // Doesn't seem to be any built-in methods to check for a line selection that contains trailing - // newlines. - // The only case this matters is when a user double-clicks to highlight a full line. Without this - // check. - // the highlighted range will continue to the following line. - val isSingleLineSelection = - endLineNumber > startLineNumber && - endLineNumber < editor.document.lineCount && - editor.document.getLineStartOffset(endLineNumber) == endOffset - - if (isSingleLineSelection) { - endLineNumber-- - } - - val prefix = editor.document.getText(TextRange(0, startOffset)) - val highlighted = editor.document.getText(TextRange(startOffset, endOffset)) - val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) - val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1) - - // Un-highlight the selected text - selectionModel.removeSelection() - - // Get indentation width in pixels - val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1 - val lineStart = editor.document.getLineStartOffset(indentationLineNum) - val lineEnd = editor.document.getLineEndOffset(indentationLineNum) - val text = editor.document.getText(TextRange(lineStart, lineEnd)) - val indentation = text.takeWhile { it == ' ' }.length - val charWidth = - editor.contentComponent - .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)) - .charWidth(' ') - val leftInset = indentation * charWidth * 2 / 3 - - val inlayRef = Ref() - val customPanelRef = Ref() - - // Create text area, attach key listener - val textArea = makeTextArea() - - // Create diff stream handler - val diffStreamHandler = - DiffStreamHandler( - project, - editor, - startLineNumber, - endLineNumber, - { - inlayRef.get()?.dispose() - }, - { - textArea.document.insertString(textArea.caretPosition, ", ", null) - textArea.requestFocus() - customPanelRef.get().finish() - }, - null, - null - ) - - val diffStreamService = project.service() - diffStreamService.register(diffStreamHandler, editor) - - val comboBoxRef = Ref>() - - fun onEnter() { - val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) - customPanelRef.get().enter() - diffStreamHandler.streamDiffLinesToEditor( - textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true - ) - } - - val panel = - makePanel( - project, - customPanelRef, - textArea, - inlayRef, - comboBoxRef, - leftInset, - modelTitles, - { onEnter() }, - { - diffStreamService.reject(editor) - selectionModel.setSelection(startOffset, endOffset) - }, - { - diffStreamService.accept(editor) - inlayRef.get().dispose() - }, - { - diffStreamService.reject(editor) - inlayRef.get().dispose() - }) - - val inlay = manager.insert(startLineNumber, panel, true) - - panel.revalidate() - inlayRef.set(inlay) - val viewport = (editor as? EditorImpl)?.scrollPane?.viewport - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) - - // Add key listener to text area - textArea.addKeyListener( - object : KeyAdapter() { - override fun keyTyped(e: KeyEvent) { - if (customPanelRef.get().isFinished) { - customPanelRef.get().setup() - } - } - - override fun keyPressed(e: KeyEvent) { - when (e.keyCode) { - KeyEvent.VK_ESCAPE -> { - diffStreamService.reject(editor) - selectionModel.setSelection(startOffset, endOffset) - } - - KeyEvent.VK_ENTER -> { - when (e.modifiersEx) { - KeyEvent.SHIFT_DOWN_MASK -> { - textArea.document.insertString(textArea.caretPosition, "\n", null) - } - - 0 -> { - onEnter() - e.consume() - } - } - } - } - } - - // We need this because backspace/delete is not registering properly on keyPressed for an - // unknown reason - override fun keyReleased(e: KeyEvent) { - if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { - if (customPanelRef.get().isFinished) { - customPanelRef.get().setup() - } - } - } - }) - - // Listen for changes to textarea line count - textArea.document.addDocumentListener( - object : DocumentListener { - private var lastNumLines: Int = 0 - - private fun updateSize() { - val numLines = textArea.text.lines().size - if (numLines != lastNumLines) { - lastNumLines = numLines - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) - } - } - - override fun insertUpdate(e: DocumentEvent?) { - updateSize() - } - - override fun removeUpdate(e: DocumentEvent?) { - updateSize() - } - - override fun changedUpdate(e: DocumentEvent?) { - updateSize() - } - }) - - textArea.requestFocus() -} - -/** - * Adapted from - * https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt - */ class InlineEditAction : AnAction(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabled = true @@ -347,417 +21,4 @@ class InlineEditAction : AnAction(), DumbAware { val project = e.getData(PlatformDataKeys.PROJECT) ?: return openInlineEdit(project, editor) } -} - -class CustomPanel( - layout: MigLayout, - project: Project, - modelTitles: List, - comboBoxRef: Ref>, - private val onEnter: () -> Unit, - private val onCancel: () -> Unit, - private val onAccept: () -> Unit, - private val onReject: () -> Unit, - private val textArea: JTextArea -) : JPanel(layout) { - private val shadowSize = 5 - private val cornerRadius = 8 - private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow - private val borderColor = Color(128, 128, 128, 128) - private val borderThickness = 1 - private val triangleSize = 6 - private val rightMargin = 3.0 - private val closeButton: JComponent = createCloseButton() - private val originalTextColor: Color = textArea.foreground - private val greyTextColor: Color = Color(128, 128, 128, 200) - var isFinished = false - - init { - isOpaque = false - add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!") - } - - private fun createCloseButton(): JComponent { - val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) - return JLabel(closeIcon).apply { - background = Color(0, 0, 0, 0) - border = JBUI.Borders.empty(2, 6, 2, 0) - toolTipText = "`esc` to cancel" - isOpaque = false - addMouseListener( - object : MouseAdapter() { - override fun mouseEntered(e: MouseEvent) { - cursor = Cursor(Cursor.HAND_CURSOR) - } - - override fun mouseExited(e: MouseEvent) { - cursor = Cursor.getDefaultCursor() - } - - override fun mouseClicked(e: MouseEvent) { - onCancel() - } - }) - } - } - - private val subPanelA: JPanel = - JPanel(MigLayout("insets 0, fillx")).apply { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - val continueSettingsService = service() - val dropdown = - JComboBox(modelTitles.toTypedArray()).apply { - setUI(TransparentArrowButtonUI()) - isEditable = true - background = defaultBackground - foreground = Color(128, 128, 128, 200) - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12) - border = JBUI.Borders.empty(8) - isOpaque = false - isEditable = false - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - preferredSize = Dimension(200, 30) - - renderer = object : DefaultListCellRenderer() { - override fun getListCellRendererComponent( - list: JList<*>?, - value: Any?, - index: Int, - isSelected: Boolean, - cellHasFocus: Boolean - ): Component { - val component = - super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) - if (component is JLabel) { - component.border = JBUI.Borders.empty(4, 6) - } - return component - } - }.apply { - horizontalAlignment = SwingConstants.LEFT - } - - selectedIndex = - if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let { - if (modelTitles.isEmpty()) -1 - else { - val index = modelTitles.indexOf(it) - if (index != -1) index else 0 - } - } ?: 0 - - addActionListener { - continueSettingsService.continueState.lastSelectedInlineEditModel = - (selectedItem as String).removeSuffix(DOWN_ARROW) - } - } - - comboBoxRef.set(dropdown) - - val rightButton = - CustomButton("โŽ Enter") { onEnter() } - .apply { - background = globalScheme.defaultForeground - foreground = globalScheme.defaultBackground - border = JBUI.Borders.empty(2, 6) - } - - val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { - isOpaque = false - add(rightButton, "align right") - } - - border = JBUI.Borders.empty(0, 0, 16, 12) - isOpaque = false - - add(dropdown, "align left") - add(rightPanel, "align right") - - cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) - } - - private val subPanelB: JPanel = - JPanel(BorderLayout()).apply { - isOpaque = false - - val progressBar = JProgressBar().apply { isIndeterminate = true } - - add(progressBar, BorderLayout.CENTER) - border = JBUI.Borders.empty(0, 0, 16, 12) - } - - private val subPanelC: JPanel = - JPanel(MigLayout("insets 0, fillx")).apply { - val leftLabel = - JLabel("Type to re-prompt").apply { - foreground = Color(156, 163, 175) // text-gray-400 - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = JBUI.Borders.emptyLeft(4) - } - - val leftButton = - CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}โŒซ)") { onReject() } - .apply { - background = JBColor(0x30FF0000, 0x30FF0000) - } - - val rightButton = - CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}โŽ)") { onAccept() } - .apply { - background = JBColor(0x3000FF00, 0x3000FF00) - } - - val rightPanel = - JPanel(MigLayout("insets 0, fillx")).apply { - isOpaque = false - add(leftButton, "align right") - add(rightButton, "align right") - border = JBUI.Borders.empty() - } - - add(leftLabel, "align left") - add(rightPanel, "align right") - border = JBUI.Borders.empty(0, 0, 16, 12) - isOpaque = false - } - - fun setup() { - remove(subPanelB) - remove(subPanelC) - add(subPanelA, "grow, gap 0!") - isFinished = false - revalidate() - repaint() - textArea.foreground = originalTextColor - } - - fun enter() { - remove(subPanelA) - remove(subPanelC) - add(subPanelB, "grow, gap 0!") - revalidate() - repaint() - } - - fun finish() { - remove(subPanelB) - add(subPanelC, "grow, gap 0!") - revalidate() - repaint() - isFinished = true - textArea.foreground = greyTextColor - } - - override fun paintComponent(g: Graphics) { - super.paintComponent(g) - - val g2 = g as Graphics2D - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - - val w = width - shadowSize - val h = height - shadowSize - - // Create the shape for the tooltip/triangle - val shape = Path2D.Double() - shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) - shape.quadTo( - borderThickness / 2.0, - borderThickness / 2.0, - cornerRadius.toDouble(), - borderThickness / 2.0 - ) - shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) - shape.quadTo( - w - borderThickness / 2.0 - rightMargin, - borderThickness / 2.0, - w - borderThickness / 2.0 - rightMargin, - cornerRadius.toDouble() - ) - shape.lineTo( - w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble() - ) - shape.quadTo( - w - borderThickness / 2.0 - rightMargin, - h - triangleSize.toDouble(), - w - cornerRadius.toDouble() - rightMargin, - h - triangleSize.toDouble() - ) - shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) - shape.lineTo(borderThickness / 2.0, h.toDouble()) - shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) - - // Draw shadow - g2.color = shadowColor - g2.fill( - shape.createTransformedShape( - AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble()) - ) - ) - - // Draw main shape - g2.color = background - g2.fill(shape) - - // Draw border - g2.color = borderColor - g2.stroke = BasicStroke(borderThickness.toFloat()) - g2.draw(shape) - } -} - -class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { - private var isHovered = false - - init { - isOpaque = false - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - addMouseListener( - object : MouseAdapter() { - override fun mouseEntered(e: MouseEvent?) { - isHovered = true - repaint() - } - - override fun mouseExited(e: MouseEvent?) { - isHovered = false - repaint() - } - - override fun mouseClicked(e: MouseEvent?) { - onClick() - } - }) - - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = JBUI.Borders.empty(2, 6) - } - - override fun paintComponent(g: Graphics) { - val g2 = g as Graphics2D - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - - val cornerRadius = 8 - val rect = Rectangle(0, 0, width, height) - val roundRect = - RoundRectangle2D.Float( - rect.x.toFloat(), - rect.y.toFloat(), - rect.width.toFloat(), - rect.height.toFloat(), - cornerRadius.toFloat(), - cornerRadius.toFloat() - ) - g2.color = background - g2.fill(roundRect) - g2.color = foreground - g2.drawString( - text, - (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), - (height / 2 + g.fontMetrics.ascent / 2).toFloat() - ) - } -} - -class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { - init { - setRows(rows) - setColumns(columns) - } - - override fun paintComponent(g: Graphics) { - // Draw placeholder - if (text.isEmpty()) { - g.color = Color(128, 128, 128, 255) - g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) - g.drawString("Enter instructions...", 8, 20) - } - - super.paintComponent(g) - } -} - -class ShadowPanel(layout: LayoutManager) : JXPanel(layout) { - override fun getPreferredSize(): Dimension { - val prefSize = super.getPreferredSize() - val insets = getInsets() - prefSize.width += insets.left + insets.right - prefSize.height += insets.top + insets.bottom - return prefSize - } - - override fun paintComponent(g: Graphics) { - super.paintComponent(g) - } -} - -class TransparentArrowButtonUI : BasicComboBoxUI() { - override fun createArrowButton() = - JButton().apply { - isVisible = false - preferredSize = Dimension(0, 0) - } - - override fun getInsets(): Insets { - return JBUI.insetsLeft(6) - } - - override fun installUI(c: JComponent?) { - super.installUI(c) - comboBox.isOpaque = false - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - comboBox.background = defaultBackground - - // Modify the ComboBoxModel to include the down symbol - val originalModel = comboBox.model - comboBox.model = - object : ComboBoxModel { - override fun getSize(): Int = originalModel.size - - override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) - - override fun setSelectedItem(anItem: Any?) { - originalModel.selectedItem = anItem - } - - override fun getSelectedItem(): Any? { - val item = originalModel.selectedItem - return "$item$DOWN_ARROW" - } - - override fun addListDataListener(l: ListDataListener?) { - originalModel.addListDataListener(l) - } - - override fun removeListDataListener(l: ListDataListener?) { - originalModel.removeListDataListener(l) - } - } - } - - override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { - // Do nothing to prevent painting the background - } - - override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { - val renderer = comboBox.renderer - val item = comboBox.selectedItem - - if (item != null) { - val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) - c.font = comboBox.font - c.foreground = Color(156, 163, 175) // text-gray-400 - c.background = comboBox.background - - if (c is JComponent) { - c.isOpaque = false - } - - val currentValuePane = currentValuePane - currentValuePane.paintComponent( - g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true - ) - } - } -} +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt new file mode 100644 index 000000000..ee0499067 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt @@ -0,0 +1,746 @@ +package com.github.continuedev.continueintellijextension.editor + +import com.github.continuedev.continueintellijextension.`continue`.GetTheme +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel +import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel +import com.intellij.openapi.Disposable +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.colors.EditorFontType +import com.intellij.openapi.editor.impl.EditorImpl +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.IconLoader +import com.intellij.openapi.util.Ref +import com.intellij.openapi.util.TextRange +import com.intellij.ui.JBColor +import com.intellij.util.ui.JBUI +import com.intellij.util.ui.UIUtil +import java.awt.* +import java.awt.event.* +import java.awt.geom.AffineTransform +import java.awt.geom.Path2D +import java.awt.geom.RoundRectangle2D +import javax.swing.* +import javax.swing.event.DocumentEvent +import javax.swing.event.DocumentListener +import javax.swing.event.ListDataListener +import javax.swing.plaf.basic.BasicComboBoxUI +import kotlin.math.max +import net.miginfocom.swing.MigLayout +import org.jdesktop.swingx.JXPanel +import org.jdesktop.swingx.JXTextArea + +const val MAIN_FONT_SIZE = 13 +const val DOWN_ARROW = " โ–พ" +const val MAX_MODEL_WAIT_TIME = 1500 + +/** + * Fetches and combines available model titles from both "edit" and "chat" roles. + * Edit models are prioritized and appear first in the returned list. + * Handles duplicate models by only including them once (prioritizing edit role). + * + * @param continuePluginService The service used to fetch config information + * @return List of model titles with edit models first, duplicates removed + * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds + */ +fun getModelTitles(continuePluginService: ContinuePluginService): List { + val modelTitles = mutableListOf() + + continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> + val modelsByRole = + response.castNestedOrNull>("content", "result", "config", "modelsByRole") ?: return@request + + // Get edit models first + val editModels = modelsByRole.castNestedOrNull>("edit") + ?.mapNotNull { it.castNestedOrNull("title") } ?: emptyList() + + // Then get chat models + val chatModels = modelsByRole.castNestedOrNull>("chat") + ?.mapNotNull { it.castNestedOrNull("title") } ?: emptyList() + + // Add edit models first, then chat models (avoiding duplicates) + modelTitles.addAll(editModels) + modelTitles.addAll(chatModels.filter { it !in editModels }) + } + + val startTime = System.currentTimeMillis() + while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) { + Thread.sleep(20) + } + + return modelTitles +} + +fun makeTextArea(): JTextArea { + val textArea = + CustomTextArea(1, 40).apply { + lineWrap = true + wrapStyleWord = true + isOpaque = false + background = GetTheme().getSecondaryDark() + maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) + margin = JBUI.insets(6, 8, 2, 4) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) + preferredSize = Dimension(400, 75) + } + textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) + return textArea +} + +fun makePanel( + project: Project, + customPanelRef: Ref, + textArea: JTextArea, + inlayRef: Ref, + comboBoxRef: Ref>, + leftInset: Int, + modelTitles: List, + onEnter: () -> Unit, + onCancel: () -> Unit, + onAccept: () -> Unit, + onReject: () -> Unit +): JPanel { + val topPanel = + ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply { + background = JBColor(0x20888888, 0x20888888) + isOpaque = false + } + + val panel = + CustomPanel( + MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), + project, + modelTitles, + comboBoxRef, + onEnter, + onCancel, + onAccept, + onReject, + textArea + ) + .apply { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + background = defaultBackground + add(textArea, "grow, gap 0!, height 100%") + + putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) + preferredSize = textArea.preferredSize + setup() + } + + customPanelRef.set(panel) + + textArea.addComponentListener( + object : ComponentAdapter() { + override fun componentResized(e: ComponentEvent?) { + panel.revalidate() + panel.repaint() + } + }) + + topPanel.add(panel, "grow, gap 0!") + + return topPanel +} + +fun openInlineEdit(project: Project?, editor: Editor) { + if (project == null) return + + val editorUtils = EditorUtils(editor) + + // Don't open in terminal + if (editorUtils.isTerminal()) { + return + } + + val manager = EditorComponentInlaysManager.from(editor, true) + + val continuePluginService = project.service() + val modelTitles = getModelTitles(continuePluginService) + + val highlightedRIF = editorUtils.getHighlightedRIF() ?: return + val (startLineNumber, endLineNumber) = highlightedRIF.lines + val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets + + + val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet() + val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1) + + editorUtils.removeSelection() + + // Get indentation width in pixels + val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1 + val lineStart = editor.document.getLineStartOffset(indentationLineNum) + val lineEnd = editor.document.getLineEndOffset(indentationLineNum) + val text = editor.document.getText(TextRange(lineStart, lineEnd)) + val indentation = text.takeWhile { it == ' ' }.length + val charWidth = + editor.contentComponent + .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)) + .charWidth(' ') + val leftInset = indentation * charWidth * 2 / 3 + + val inlayRef = Ref() + val customPanelRef = Ref() + + // Create text area, attach key listener + val textArea = makeTextArea() + + // Create diff stream handler + val diffStreamHandler = + DiffStreamHandler( + project, + editor, + startLineNumber, + endLineNumber, + { + inlayRef.get()?.dispose() + }, + { + textArea.document.insertString(textArea.caretPosition, ", ", null) + textArea.requestFocus() + customPanelRef.get().finish() + }, + null, + null + ) + + val diffStreamService = project.service() + diffStreamService.register(diffStreamHandler, editor) + + val comboBoxRef = Ref>() + + fun onEnter() { + val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) + customPanelRef.get().enter() + diffStreamHandler.streamDiffLinesToEditor( + textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true + ) + } + + val panel = + makePanel( + project, + customPanelRef, + textArea, + inlayRef, + comboBoxRef, + leftInset, + modelTitles, + { onEnter() }, + { + diffStreamService.reject(editor) + editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset) + }, + { + diffStreamService.accept(editor) + inlayRef.get().dispose() + }, + { + diffStreamService.reject(editor) + inlayRef.get().dispose() + }) + + val inlay = manager.insert(startLineNumber, panel, true) + + panel.revalidate() + inlayRef.set(inlay) + val viewport = (editor as? EditorImpl)?.scrollPane?.viewport + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) + + // Add key listener to text area + textArea.addKeyListener( + object : KeyAdapter() { + override fun keyTyped(e: KeyEvent) { + if (customPanelRef.get().isFinished) { + customPanelRef.get().setup() + } + } + + override fun keyPressed(e: KeyEvent) { + when (e.keyCode) { + KeyEvent.VK_ESCAPE -> { + diffStreamService.reject(editor) + editorUtils.editor.selectionModel.setSelection( + highlightedStartOffset, + highlightedEndOffset + ) + } + + KeyEvent.VK_ENTER -> { + when (e.modifiersEx) { + KeyEvent.SHIFT_DOWN_MASK -> { + textArea.document.insertString(textArea.caretPosition, "\n", null) + } + + 0 -> { + onEnter() + e.consume() + } + } + } + } + } + + // We need this because backspace/delete is not registering properly on keyPressed for an + // unknown reason + override fun keyReleased(e: KeyEvent) { + if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { + if (customPanelRef.get().isFinished) { + customPanelRef.get().setup() + } + } + } + }) + + // Listen for changes to textarea line count + textArea.document.addDocumentListener( + object : DocumentListener { + private var lastNumLines: Int = 0 + + private fun updateSize() { + val numLines = textArea.text.lines().size + if (numLines != lastNumLines) { + lastNumLines = numLines + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) + } + } + + override fun insertUpdate(e: DocumentEvent?) { + updateSize() + } + + override fun removeUpdate(e: DocumentEvent?) { + updateSize() + } + + override fun changedUpdate(e: DocumentEvent?) { + updateSize() + } + }) + + textArea.requestFocus() +} + + +class CustomPanel( + layout: MigLayout, + project: Project, + modelTitles: List, + comboBoxRef: Ref>, + private val onEnter: () -> Unit, + private val onCancel: () -> Unit, + private val onAccept: () -> Unit, + private val onReject: () -> Unit, + private val textArea: JTextArea +) : JPanel(layout) { + private val shadowSize = 5 + private val cornerRadius = 8 + private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow + private val borderColor = Color(128, 128, 128, 128) + private val borderThickness = 1 + private val triangleSize = 6 + private val rightMargin = 3.0 + private val closeButton: JComponent = createCloseButton() + private val originalTextColor: Color = textArea.foreground + private val greyTextColor: Color = Color(128, 128, 128, 200) + var isFinished = false + + init { + isOpaque = false + add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!") + } + + private fun createCloseButton(): JComponent { + val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) + return JLabel(closeIcon).apply { + background = Color(0, 0, 0, 0) + border = JBUI.Borders.empty(2, 6, 2, 0) + toolTipText = "`esc` to cancel" + isOpaque = false + addMouseListener( + object : MouseAdapter() { + override fun mouseEntered(e: MouseEvent) { + cursor = Cursor(Cursor.HAND_CURSOR) + } + + override fun mouseExited(e: MouseEvent) { + cursor = Cursor.getDefaultCursor() + } + + override fun mouseClicked(e: MouseEvent) { + onCancel() + } + }) + } + } + + private val subPanelA: JPanel = + JPanel(MigLayout("insets 0, fillx")).apply { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + val continueSettingsService = service() + val dropdown = + JComboBox(modelTitles.toTypedArray()).apply { + setUI(TransparentArrowButtonUI()) + isEditable = true + background = defaultBackground + foreground = Color(128, 128, 128, 200) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12) + border = JBUI.Borders.empty(8) + isOpaque = false + isEditable = false + cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) + preferredSize = Dimension(200, 30) + + renderer = object : DefaultListCellRenderer() { + override fun getListCellRendererComponent( + list: JList<*>?, + value: Any?, + index: Int, + isSelected: Boolean, + cellHasFocus: Boolean + ): Component { + val component = + super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) + if (component is JLabel) { + component.border = JBUI.Borders.empty(4, 6) + } + return component + } + }.apply { + horizontalAlignment = SwingConstants.LEFT + } + + selectedIndex = + if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let { + if (modelTitles.isEmpty()) -1 + else { + val index = modelTitles.indexOf(it) + if (index != -1) index else 0 + } + } ?: 0 + + addActionListener { + continueSettingsService.continueState.lastSelectedInlineEditModel = + (selectedItem as String).removeSuffix(DOWN_ARROW) + } + } + + comboBoxRef.set(dropdown) + + val rightButton = + CustomButton("โŽ Enter") { onEnter() } + .apply { + background = JBColor.namedColor("Button.startBackground") + foreground = JBColor.namedColor("Button.foreground") + border = JBUI.Borders.empty(2, 6) + } + + val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { + isOpaque = false + add(rightButton, "align right") + } + + border = JBUI.Borders.empty(0, 0, 16, 12) + isOpaque = false + + add(dropdown, "align left") + add(rightPanel, "align right") + + cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) + } + + private val subPanelB: JPanel = + JPanel(BorderLayout()).apply { + isOpaque = false + + val progressBar = JProgressBar().apply { isIndeterminate = true } + + add(progressBar, BorderLayout.CENTER) + border = JBUI.Borders.empty(0, 0, 16, 12) + } + + private val subPanelC: JPanel = + JPanel(MigLayout("insets 0, fillx")).apply { + val leftLabel = + JLabel("Type to re-prompt").apply { + foreground = Color(156, 163, 175) // text-gray-400 + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) + border = JBUI.Borders.emptyLeft(4) + } + + val leftButton = + CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}โŒซ)") { onReject() } + .apply { + background = Color(0, 0, 0, 0) + foreground = JBColor.foreground() + border = JBUI.Borders.empty(2, 6) + } + + val rightButton = + CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}โŽ)") { onAccept() } + .apply { + background = JBColor.namedColor("Button.startBackground") + foreground = JBColor.namedColor("Button.foreground") + border = JBUI.Borders.empty(2, 6) + } + + val rightPanel = + JPanel(MigLayout("insets 0, fillx")).apply { + isOpaque = false + add(leftButton, "align right") + add(rightButton, "align right") + border = JBUI.Borders.empty() + } + + add(leftLabel, "align left") + add(rightPanel, "align right") + border = JBUI.Borders.empty(0, 0, 16, 12) + isOpaque = false + } + + fun setup() { + remove(subPanelB) + remove(subPanelC) + add(subPanelA, "grow, gap 0!") + isFinished = false + revalidate() + repaint() + textArea.foreground = originalTextColor + } + + fun enter() { + remove(subPanelA) + remove(subPanelC) + add(subPanelB, "grow, gap 0!") + revalidate() + repaint() + } + + fun finish() { + remove(subPanelB) + add(subPanelC, "grow, gap 0!") + revalidate() + repaint() + isFinished = true + textArea.foreground = greyTextColor + } + + override fun paintComponent(g: Graphics) { + super.paintComponent(g) + + val g2 = g as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + val w = width - shadowSize + val h = height - shadowSize + + // Create the shape for the tooltip/triangle + val shape = Path2D.Double() + shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) + shape.quadTo( + borderThickness / 2.0, + borderThickness / 2.0, + cornerRadius.toDouble(), + borderThickness / 2.0 + ) + shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) + shape.quadTo( + w - borderThickness / 2.0 - rightMargin, + borderThickness / 2.0, + w - borderThickness / 2.0 - rightMargin, + cornerRadius.toDouble() + ) + shape.lineTo( + w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble() + ) + shape.quadTo( + w - borderThickness / 2.0 - rightMargin, + h - triangleSize.toDouble(), + w - cornerRadius.toDouble() - rightMargin, + h - triangleSize.toDouble() + ) + shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) + shape.lineTo(borderThickness / 2.0, h.toDouble()) + shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) + + // Draw shadow + g2.color = shadowColor + g2.fill( + shape.createTransformedShape( + AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble()) + ) + ) + + // Draw main shape + g2.color = background + g2.fill(shape) + + // Draw border + g2.color = borderColor + g2.stroke = BasicStroke(borderThickness.toFloat()) + g2.draw(shape) + } +} + +class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { + private var isHovered = false + + init { + isOpaque = false + cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) + addMouseListener( + object : MouseAdapter() { + override fun mouseEntered(e: MouseEvent?) { + isHovered = true + repaint() + } + + override fun mouseExited(e: MouseEvent?) { + isHovered = false + repaint() + } + + override fun mouseClicked(e: MouseEvent?) { + onClick() + } + }) + + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) + border = JBUI.Borders.empty(2, 6) + } + + override fun paintComponent(g: Graphics) { + val g2 = g as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + val cornerRadius = 8 + val rect = Rectangle(0, 0, width, height) + val roundRect = + RoundRectangle2D.Float( + rect.x.toFloat(), + rect.y.toFloat(), + rect.width.toFloat(), + rect.height.toFloat(), + cornerRadius.toFloat(), + cornerRadius.toFloat() + ) + g2.color = background + g2.fill(roundRect) + g2.color = foreground + g2.drawString( + text, + (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), + (height / 2 + g.fontMetrics.ascent / 2).toFloat() + ) + } +} + +class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { + init { + setRows(rows) + setColumns(columns) + } + + override fun paintComponent(g: Graphics) { + // Draw placeholder + if (text.isEmpty()) { + g.color = Color(128, 128, 128, 255) + g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) + g.drawString("Enter instructions...", 8, 20) + } + + super.paintComponent(g) + } +} + +class ShadowPanel(layout: LayoutManager) : JXPanel(layout) { + override fun getPreferredSize(): Dimension { + val prefSize = super.getPreferredSize() + val insets = getInsets() + prefSize.width += insets.left + insets.right + prefSize.height += insets.top + insets.bottom + return prefSize + } + + override fun paintComponent(g: Graphics) { + super.paintComponent(g) + } +} + +class TransparentArrowButtonUI : BasicComboBoxUI() { + override fun createArrowButton() = + JButton().apply { + isVisible = false + preferredSize = Dimension(0, 0) + } + + override fun getInsets(): Insets { + return JBUI.insetsLeft(6) + } + + override fun installUI(c: JComponent?) { + super.installUI(c) + comboBox.isOpaque = false + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + comboBox.background = defaultBackground + + // Modify the ComboBoxModel to include the down symbol + val originalModel = comboBox.model + comboBox.model = + object : ComboBoxModel { + override fun getSize(): Int = originalModel.size + + override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) + + override fun setSelectedItem(anItem: Any?) { + originalModel.selectedItem = anItem + } + + override fun getSelectedItem(): Any? { + val item = originalModel.selectedItem + return "$item$DOWN_ARROW" + } + + override fun addListDataListener(l: ListDataListener?) { + originalModel.addListDataListener(l) + } + + override fun removeListDataListener(l: ListDataListener?) { + originalModel.removeListDataListener(l) + } + } + } + + override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { + // Do nothing to prevent painting the background + } + + override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { + val renderer = comboBox.renderer + val item = comboBox.selectedItem + + if (item != null) { + val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) + c.font = comboBox.font + c.foreground = Color(156, 163, 175) // text-gray-400 + c.background = comboBox.background + + if (c is JComponent) { + c.isOpaque = false + } + + val currentValuePane = currentValuePane + currentValuePane.paintComponent( + g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true + ) + } + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt index 98d2041d0..61eacc6fc 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt @@ -12,22 +12,43 @@ import com.intellij.openapi.util.TextRange class RangeInFileWithContents( val filepath: String, val range: Range, - val contents: String + val contents: String, + val document: Document + ) { /** - * Returns the absolute document offset for the start position + * The absolute document offset for the start position */ - fun getStartOffset(document: Document): Int { - return document.getLineStartOffset(range.start.line) + range.start.character - } + val startOffset: Int + get() = document.getLineStartOffset(range.start.line) + range.start.character /** - * Returns the absolute document offset for the end position + * The absolute document offset for the end position */ - fun getEndOffset(document: Document): Int { - return document.getLineStartOffset(range.end.line) + range.end.character - } + val endOffset: Int + get() = document.getLineStartOffset(range.end.line) + range.end.character + /** + * The line number where the highlighted range starts (zero-based) + */ + val startLine: Int + get() = range.start.line + + /** + * The line number where the highlighted range ends (zero-based) + * This already accounts for proper line ending calculations. + */ + val endLine: Int + get() = range.end.line + + /** + * Both the start and end line numbers of the highlighted range as a pair + */ + val lines: Pair + get() = Pair(startLine, endLine) + + val offsets: Pair + get() = Pair(startOffset, endOffset) companion object { /** @@ -45,6 +66,13 @@ class RangeInFileWithContents( val startChar = selectionStart - document.getLineStartOffset(startLine) val endChar = selectionEnd - document.getLineStartOffset(endLine) + // Adjust end line if it's a single line selection with trailing newlines + val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) { + endLine - 1 + } else { + endLine + } + val selectedText = document.getText( TextRange(selectionStart, selectionEnd) ) @@ -53,10 +81,30 @@ class RangeInFileWithContents( filepath, Range( Position(startLine, startChar), - Position(endLine, endChar) + Position(adjustedEndLine, endChar) ), - selectedText + selectedText, + document ) } + + /** + * Checks if the selection spans to the next line only because of trailing newlines. + * This matters when a user double-clicks to highlight a full line. + * + * @return true if the selection is actually a single line selection with trailing newline + */ + fun isSelectionWithTrailingNewline( + document: Document, + selectionStart: Int, + selectionEnd: Int + ): Boolean { + val startLine = document.getLineNumber(selectionStart) + val endLine = document.getLineNumber(selectionEnd) + + return endLine > startLine && + endLine < document.lineCount && + document.getLineStartOffset(endLine) == selectionEnd + } } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index ad902a8b9..616702466 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -166,7 +166,7 @@ class VerticalDiffBlock( val rejectBtn = createButton( "${getAltKeyLabel()}${getShiftKeyLabel()}N", - JBColor(0x77FF0000, 0x77FF0000) + JBColor(0xFF0000, 0xFF0000) ).apply { addActionListener { handleReject() @@ -178,13 +178,14 @@ class VerticalDiffBlock( createButton( "${getAltKeyLabel()}${ getShiftKeyLabel() - }Y", JBColor(0x7700BB00, 0x7700BB00) + }Y", JBColor(0x00BB00, 0x00BB00) ).apply { addActionListener { handleAccept() } } + return Pair(acceptBtn, rejectBtn) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index b875f744c..718755a99 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -15,16 +15,6 @@ data class ApplyToFileParams( val toolCallId: String? ) -data class AcceptDiffParams( - val filepath: String, - val streamId: String -) - -data class RejectDiffParams( - val filepath: String, - val streamId: String -) - data class InsertAtCursorParams( val text: String ) 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 aaa4a8e8e..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,10 +244,15 @@ data class StreamDiffLinesPayload( val input: String, val language: String?, val modelTitle: String?, - val includeRulesInSystemMessage: Boolean + val includeRulesInSystemMessage: Boolean, + val fileUri: String? ) data class AcceptOrRejectDiffPayload( val filepath: String, val streamId: String? = null +) + +data class ShowFilePayload( + val filepath: String ) \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 0e856be4c..92005ffdc 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -78,9 +78,9 @@ class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction" text="Reject Diff" description="Reject Diff"> + first-keystroke="shift ctrl BACK_SPACE"/> + first-keystroke="shift meta BACK_SPACE"/> diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index fde20fbb2..993198fe0 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -3494,6 +3494,20 @@ } }, "required": ["type", "url"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["streamable-http"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] } ] } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 09ee927d9..5634027da 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,16 +1,16 @@ { "name": "continue", - "version": "1.1.35", + "version": "1.1.39", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.35", + "version": "1.1.39", "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", @@ -64,7 +64,7 @@ "devDependencies": { "@biomejs/biome": "1.6.4", "@nestjs/common": "^11.0.16", - "@openapitools/openapi-generator-cli": "^2.5.2", + "@openapitools/openapi-generator-cli": "^2.20.0", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", @@ -107,9 +107,9 @@ "@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", + "@continuedev/openai-adapters": "^1.0.25", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -148,6 +148,7 @@ "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", + "plist": "^3.1.0", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", "puppeteer-chromium-resolver": "^23.0.0", @@ -184,6 +185,7 @@ "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", + "@types/plist": "^3.0.5", "@types/request": "^2.48.12", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", @@ -706,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", @@ -1442,14 +1445,28 @@ "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" }, + "node_modules/@nestjs/axios": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz", + "integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^10.0.0 || ^11.0.0", + "axios": "^1.3.1", + "rxjs": "^7.0.0" + } + }, "node_modules/@nestjs/common": { - "version": "11.0.16", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.16.tgz", - "integrity": "sha512-agvuQ8su4aZ+PVxAmY89odG1eR97HEQvxPmTMdDqyvDWzNerl7WQhUEd+j4/UyNWcF1or1UVcrtPj52x+eUSsA==", + "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.5.0", "iterare": "1.2.1", + "load-esm": "1.0.2", "tslib": "2.8.1", "uid": "2.0.2" }, @@ -1458,9 +1475,8 @@ "url": "https://opencollective.com/nest" }, "peerDependencies": { - "class-transformer": "*", - "class-validator": "*", - "file-type": "^20.4.1", + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, @@ -1473,6 +1489,58 @@ } } }, + "node_modules/@nestjs/core": { + "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", + "dependencies": { + "@nuxt/opencollective": "0.4.1", + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "8.2.0", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "engines": { + "node": ">= 20" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^11.0.0", + "@nestjs/microservices": "^11.0.0", + "@nestjs/platform-express": "^11.0.0", + "@nestjs/websockets": "^11.0.0", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + }, + "@nestjs/websockets": { + "optional": true + } + } + }, + "node_modules/@nestjs/core/node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1565,11 +1633,29 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/@nuxt/opencollective": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz", + "integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "consola": "^3.2.3" + }, + "bin": { + "opencollective": "bin/opencollective.js" + }, + "engines": { + "node": "^14.18.0 || >=16.10.0", + "npm": ">=5.10.0" + } + }, "node_modules/@nuxtjs/opencollective": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz", "integrity": "sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==", "dev": true, + "license": "MIT", "dependencies": { "chalk": "^4.1.0", "consola": "^2.15.0", @@ -1583,11 +1669,19 @@ "npm": ">=5.0.0" } }, + "node_modules/@nuxtjs/opencollective/node_modules/consola": { + "version": "2.15.3", + "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", + "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", + "dev": true, + "license": "MIT" + }, "node_modules/@nuxtjs/opencollective/node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", "dev": true, + "license": "MIT", "dependencies": { "whatwg-url": "^5.0.0" }, @@ -1607,48 +1701,52 @@ "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@nuxtjs/opencollective/node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true + "dev": true, + "license": "BSD-2-Clause" }, "node_modules/@nuxtjs/opencollective/node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", "dev": true, + "license": "MIT", "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "node_modules/@openapitools/openapi-generator-cli": { - "version": "2.15.3", - "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.15.3.tgz", - "integrity": "sha512-2UBnsDlMt36thhdXxisbA1qReVtbCaw+NCvXoslRXlaJBL4qkAmZUhNeDLNu3LCbwA2PASMWhJSqeLwgwMCitw==", + "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": "3.1.1", - "@nestjs/common": "10.4.6", - "@nestjs/core": "10.4.6", + "@nestjs/axios": "4.0.0", + "@nestjs/common": "11.1.1", + "@nestjs/core": "11.1.1", "@nuxtjs/opencollective": "0.3.2", - "axios": "1.7.7", + "axios": "1.9.0", "chalk": "4.1.2", "commander": "8.3.0", "compare-versions": "4.1.4", "concurrently": "6.5.1", "console.table": "0.10.0", - "fs-extra": "10.1.0", + "fs-extra": "11.3.0", "glob": "9.3.5", "inquirer": "8.2.6", "lodash": "4.17.21", - "proxy-agent": "6.4.0", - "reflect-metadata": "0.1.13", - "rxjs": "7.8.1", + "proxy-agent": "6.5.0", + "reflect-metadata": "0.2.2", + "rxjs": "7.8.2", "tslib": "2.8.1" }, "bin": { @@ -1662,97 +1760,6 @@ "url": "https://opencollective.com/openapi_generator" } }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/axios": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz", - "integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", - "axios": "^1.3.1", - "rxjs": "^6.0.0 || ^7.0.0" - } - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common": { - "version": "10.4.6", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.6.tgz", - "integrity": "sha512-KkezkZvU9poWaNq4L+lNvx+386hpOxPJkfXBBeSMrcqBOx8kVr36TGN2uYkF4Ta4zNu1KbCjmZbc0rhHSg296g==", - "dev": true, - "dependencies": { - "iterare": "1.2.1", - "tslib": "2.7.0", - "uid": "2.0.2" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/nest" - }, - "peerDependencies": { - "class-transformer": "*", - "class-validator": "*", - "reflect-metadata": "^0.1.12 || ^0.2.0", - "rxjs": "^7.1.0" - }, - "peerDependenciesMeta": { - "class-transformer": { - "optional": true - }, - "class-validator": { - "optional": true - } - } - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common/node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", - "dev": true - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/core": { - "version": "10.4.6", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-10.4.6.tgz", - "integrity": "sha512-zXVPxCNRfO6gAy0yvEDjUxE/8gfZICJFpsl2lZAUH31bPb6m+tXuhUq2mVCTEltyMYQ+DYtRe+fEYM2v152N1g==", - "dev": true, - "hasInstallScript": true, - "dependencies": { - "@nuxtjs/opencollective": "0.3.2", - "fast-safe-stringify": "2.1.1", - "iterare": "1.2.1", - "path-to-regexp": "3.3.0", - "tslib": "2.7.0", - "uid": "2.0.2" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/nest" - }, - "peerDependencies": { - "@nestjs/common": "^10.0.0", - "@nestjs/microservices": "^10.0.0", - "@nestjs/platform-express": "^10.0.0", - "@nestjs/websockets": "^10.0.0", - "reflect-metadata": "^0.1.12 || ^0.2.0", - "rxjs": "^7.1.0" - }, - "peerDependenciesMeta": { - "@nestjs/microservices": { - "optional": true - }, - "@nestjs/platform-express": { - "optional": true - }, - "@nestjs/websockets": { - "optional": true - } - } - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/core/node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", - "dev": true - }, "node_modules/@openapitools/openapi-generator-cli/node_modules/brace-expansion": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", @@ -1762,6 +1769,21 @@ "balanced-match": "^1.0.0" } }, + "node_modules/@openapitools/openapi-generator-cli/node_modules/fs-extra": { + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz", + "integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/@openapitools/openapi-generator-cli/node_modules/glob": { "version": "9.3.5", "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", @@ -1804,18 +1826,6 @@ "node": ">=8" } }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/path-to-regexp": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz", - "integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==", - "dev": true - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/reflect-metadata": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", - "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", - "dev": true - }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -1957,7 +1967,6 @@ "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "debug": "^4.4.0", "fflate": "^0.8.2", @@ -1972,12 +1981,11 @@ } }, "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", - "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -1995,8 +2003,7 @@ "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@tootallnate/once": { "version": "2.0.0", @@ -2010,7 +2017,8 @@ "version": "0.23.0", "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@types/body-parser": { "version": "1.19.5", @@ -3076,12 +3084,10 @@ } }, "node_modules/agent-base": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", - "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", - "dependencies": { - "debug": "^4.3.4" - }, + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "license": "MIT", "engines": { "node": ">= 14" } @@ -3341,6 +3347,7 @@ "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", "dev": true, + "license": "MIT", "dependencies": { "tslib": "^2.0.1" }, @@ -3375,9 +3382,10 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.7.7", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz", - "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==", + "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", "form-data": "^4.0.0", @@ -3432,6 +3440,7 @@ "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", "dev": true, + "license": "MIT", "engines": { "node": ">=10.0.0" } @@ -4604,10 +4613,14 @@ } }, "node_modules/consola": { - "version": "2.15.3", - "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", - "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", - "dev": true + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } }, "node_modules/console-control-strings": { "version": "1.1.0", @@ -4970,6 +4983,7 @@ "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", "dev": true, + "license": "MIT", "dependencies": { "ast-types": "^0.13.4", "escodegen": "^2.1.0", @@ -5458,6 +5472,7 @@ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", @@ -5479,6 +5494,7 @@ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -5647,6 +5663,7 @@ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true, + "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", "esvalidate": "bin/esvalidate.js" @@ -5954,7 +5971,8 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/fastq": { "version": "1.17.1", @@ -5999,8 +6017,7 @@ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/figures": { "version": "3.2.0", @@ -6039,12 +6056,11 @@ } }, "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", - "peer": true, "dependencies": { "@tokenizer/inflate": "^0.2.6", "strtok3": "^10.2.0", @@ -6489,15 +6505,15 @@ } }, "node_modules/get-uri": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz", - "integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==", + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.4.tgz", + "integrity": "sha512-E1b1lFFLvLgak2whF2xDBcOy6NLVGZBqqjJjsIhvopKfWWEi64pLVTWWehV8KlLerZkfNTA95sTe2OdJKm1OzQ==", "dev": true, + "license": "MIT", "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", - "debug": "^4.3.4", - "fs-extra": "^11.2.0" + "debug": "^4.3.4" }, "engines": { "node": ">= 14" @@ -6508,24 +6524,11 @@ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", "dev": true, + "license": "MIT", "engines": { "node": ">= 14" } }, - "node_modules/get-uri/node_modules/fs-extra": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", - "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", - "dev": true, - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=14.14" - } - }, "node_modules/getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", @@ -6984,11 +6987,12 @@ } }, "node_modules/https-proxy-agent": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", - "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", "dependencies": { - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "4" }, "engines": { @@ -7919,6 +7923,26 @@ "uc.micro": "^1.0.1" } }, + "node_modules/load-esm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.2.tgz", + "integrity": "sha512-nVAvWk/jeyrWyXEAs84mpQCYccxRqgKY4OznLuJhJCa0XsPSfdOIr2zvBZEj3IHEHbX97jjscKRRV539bW0Gpw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "engines": { + "node": ">=13.2.0" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -9265,6 +9289,7 @@ "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.4.0" } @@ -9963,31 +9988,33 @@ } }, "node_modules/pac-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.0.2.tgz", - "integrity": "sha512-BFi3vZnO9X5Qt6NRz7ZOaPja3ic0PhlsmCRYLOpN11+mWBCR6XJDqW5RF3j8jm4WGGQZtBA+bTfxYzeKW73eHg==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", "dev": true, + "license": "MIT", "dependencies": { "@tootallnate/quickjs-emscripten": "^0.23.0", - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "^4.3.4", "get-uri": "^6.0.1", "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.5", + "https-proxy-agent": "^7.0.6", "pac-resolver": "^7.0.1", - "socks-proxy-agent": "^8.0.4" + "socks-proxy-agent": "^8.0.5" }, "engines": { "node": ">= 14" } }, "node_modules/pac-proxy-agent/node_modules/socks-proxy-agent": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", - "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "^7.1.1", + "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" }, @@ -10000,6 +10027,7 @@ "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", "dev": true, + "license": "MIT", "dependencies": { "degenerator": "^5.0.0", "netmask": "^2.0.2" @@ -10192,7 +10220,6 @@ "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -10678,19 +10705,20 @@ } }, "node_modules/proxy-agent": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.4.0.tgz", - "integrity": "sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==", + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", + "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "^4.3.4", "http-proxy-agent": "^7.0.1", - "https-proxy-agent": "^7.0.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^7.14.1", - "pac-proxy-agent": "^7.0.1", + "pac-proxy-agent": "^7.1.0", "proxy-from-env": "^1.1.0", - "socks-proxy-agent": "^8.0.2" + "socks-proxy-agent": "^8.0.5" }, "engines": { "node": ">= 14" @@ -10701,17 +10729,19 @@ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", "dev": true, + "license": "ISC", "engines": { "node": ">=12" } }, "node_modules/proxy-agent/node_modules/socks-proxy-agent": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", - "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "^7.1.1", + "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" }, @@ -11075,11 +11105,11 @@ } }, "node_modules/reflect-metadata": { - "version": "0.1.14", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.14.tgz", - "integrity": "sha512-ZhYeb6nRaXCfhnndflDK8qI6ZQ/YcWZCISRAWICW9XYqMUwjZM9Z0DveWX/ABN01oxSHwVxKQmxeYZSsm0jh5A==", + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", "dev": true, - "peer": true + "license": "Apache-2.0" }, "node_modules/regenerator-runtime": { "version": "0.14.1", @@ -11416,10 +11446,11 @@ "integrity": "sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA==" }, "node_modules/rxjs": { - "version": "7.8.1", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", - "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "dev": true, + "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" } @@ -12166,7 +12197,6 @@ "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@tokenizer/token": "^0.3.0", "peek-readable": "^7.0.0" @@ -12822,7 +12852,6 @@ "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" @@ -13080,7 +13109,6 @@ "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 3ac9d33c5..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.35", + "version": "1.1.40", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -105,7 +105,7 @@ "continue.enableQuickActions": { "type": "boolean", "default": false, - "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev โ€บ Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/features/quick-actions)" + "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev โ€บ Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/customize/deep-dives/vscode-actions#quick-actions)" }, "continue.enableTabAutocomplete": { "type": "boolean", @@ -631,7 +631,7 @@ "devDependencies": { "@biomejs/biome": "1.6.4", "@nestjs/common": "^11.0.16", - "@openapitools/openapi-generator-cli": "^2.5.2", + "@openapitools/openapi-generator-cli": "^2.20.0", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", @@ -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/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 2e6acfb86..73f36afdb 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -1,6 +1,5 @@ import crypto from "crypto"; -import { ControlPlaneSessionInfo } from "core/control-plane/client"; import { getControlPlaneEnvSync } from "core/control-plane/env"; import fetch from "node-fetch"; import { v4 as uuidv4 } from "uuid"; @@ -18,6 +17,12 @@ import { window, } from "vscode"; +import { + AuthType, + ControlPlaneSessionInfo, + HubEnv, + isHubEnv, +} from "core/control-plane/AuthTypes"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; import { SecretStorage } from "./SecretStorage"; import { UriEventHandler } from "./uriHandler"; @@ -280,12 +285,21 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { try { const codeVerifier = generateRandomString(64); const codeChallenge = await generateCodeChallenge(codeVerifier); - const token = await this.login(codeChallenge, scopes); + + if (!isHubEnv(controlPlaneEnv)) { + throw new Error("Login is disabled"); + } + + const token = await this.login(codeChallenge, controlPlaneEnv, scopes); if (!token) { throw new Error(`Continue login failure`); } - const userInfo = (await this.getUserInfo(token, codeVerifier)) as any; + const userInfo = (await this.getUserInfo( + token, + codeVerifier, + controlPlaneEnv, + )) as any; const { user, access_token, refresh_token } = userInfo; const session: ContinueAuthenticationSession = { @@ -352,7 +366,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { /** * Log in to Continue */ - private async login(codeChallenge: string, scopes: string[] = []) { + private async login( + codeChallenge: string, + hubEnv: HubEnv, + scopes: string[] = [], + ) { return await window.withProgress( { location: ProgressLocation.Notification, @@ -369,7 +387,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { const url = new URL("https://api.workos.com/user_management/authorize"); const params = { response_type: "code", - client_id: controlPlaneEnv.WORKOS_CLIENT_ID, + client_id: hubEnv.WORKOS_CLIENT_ID, redirect_uri: this.redirectUri, state: stateId, code_challenge: codeChallenge, @@ -458,7 +476,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { * @param token * @returns */ - private async getUserInfo(token: string, codeVerifier: string) { + private async getUserInfo( + token: string, + codeVerifier: string, + hubEnv: HubEnv, + ) { const resp = await fetch( "https://api.workos.com/user_management/authenticate", { @@ -467,7 +489,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { "Content-Type": "application/json", }, body: JSON.stringify({ - client_id: controlPlaneEnv.WORKOS_CLIENT_ID, + client_id: hubEnv.WORKOS_CLIENT_ID, code_verifier: codeVerifier, grant_type: "authorization_code", code: token, @@ -484,6 +506,12 @@ export async function getControlPlaneSessionInfo( silent: boolean, useOnboarding: boolean, ): Promise { + if (!isHubEnv(controlPlaneEnv)) { + return { + AUTH_TYPE: AuthType.OnPrem, + }; + } + try { if (useOnboarding) { WorkOsAuthProvider.useOnboardingUri = true; @@ -498,6 +526,7 @@ export async function getControlPlaneSessionInfo( return undefined; } return { + AUTH_TYPE: controlPlaneEnv.AUTH_TYPE, accessToken: session.accessToken, account: { id: session.account.id, diff --git a/gui/package-lock.json b/gui/package-lock.json index 579d35a6a..17f6b1514 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.5.0", + "@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", @@ -152,6 +152,7 @@ "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", + "plist": "^3.1.0", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", "puppeteer-chromium-resolver": "^23.0.0", @@ -188,6 +189,7 @@ "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", + "@types/plist": "^3.0.5", "@types/request": "^2.48.12", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", @@ -209,7 +211,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.87", + "version": "1.0.88", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 03b6fb05a..6fc120707 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -9,6 +9,7 @@ import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; import Stats from "./pages/stats"; +import ThemePage from "./styles/ThemePage"; import { ROUTES } from "./util/navigation"; const router = createMemoryRouter([ @@ -37,6 +38,10 @@ const router = createMemoryRouter([ path: ROUTES.CONFIG, element: , }, + { + path: ROUTES.THEME, + element: , + }, ], }, ]); 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/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index 6154b3452..da0e439c0 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -3,6 +3,7 @@ import { useContext } from "react"; import { lightGray, vscForeground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { isJetBrains } from "../../../util"; +import { extractCommand } from "../utils/commandExtractor"; interface RunInTerminalButtonProps { command: string; @@ -16,18 +17,6 @@ export function RunInTerminalButton({ command }: RunInTerminalButtonProps) { return null; } - // Extract just the command line (the line after $ or the first line) - function extractCommand(cmd: string): string { - // If the command contains a $ prompt, extract the line after it - if (cmd.includes("$")) { - const match = cmd.match(/\$\s*([^\n]+)/); - return match ? match[1].trim() : ""; - } - - // Otherwise, just take the first line - return cmd.split("\n")[0].trim(); - } - function runInTerminal() { // Extract just the command line const extractedCommand = extractCommand(command); diff --git a/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx b/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx index 40ca69708..8224af794 100644 --- a/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +++ b/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx @@ -44,14 +44,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { data-tooltip-id={id} data-tooltip-delay-show={500} > - - {content} - + {content}
{processedContent ?? symbol.filepath}
diff --git a/gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts b/gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts new file mode 100644 index 000000000..1d1d6099c --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts @@ -0,0 +1,80 @@ +import { extractCommand } from './commandExtractor'; + +describe('extractCommand', () => { + // Test basic command extraction + it('should extract command from $ prompt', () => { + expect(extractCommand('$ echo hello')).toBe('echo hello'); + expect(extractCommand('$ echo hello')).toBe('echo hello'); + expect(extractCommand('$echo hello')).toBe('echo hello'); + }); + + // Test comment removal + it('should remove comments at beginning of lines', () => { + expect(extractCommand('# shell comment\necho hello')).toBe('echo hello'); + expect(extractCommand('// js comment\necho hello')).toBe('echo hello'); + expect(extractCommand('/* multi-line\ncomment */\necho hello')).toBe('echo hello'); + }); + + // Test multiline comment removal + it('should remove multiline comments anywhere in the text', () => { + expect(extractCommand('echo /* comment */ hello')).toBe('echo hello'); + expect(extractCommand('echo hello /* comment */')).toBe('echo hello'); + expect(extractCommand('echo /* multiple\nline\ncomment */ hello')).toBe('echo hello'); + }); + + // Test line continuation handling + it('should handle line continuations correctly', () => { + expect(extractCommand('echo hello && \\\necho world')).toBe('echo hello && echo world'); + expect(extractCommand('echo hello | \\\ngrep h')).toBe('echo hello | grep h'); + expect(extractCommand('echo hello \\\nworld')).toBe('echo hello world'); + }); + + // Test complex command combinations + it('should handle complex command combinations', () => { + expect(extractCommand(` + # shell comment + echo hello /* inline comment */ && \\ + // js comment + echo world + `)).toBe('echo hello && echo world'); + }); + + // Test empty and whitespace handling + it('should handle empty and whitespace inputs', () => { + expect(extractCommand('')).toBe(''); + expect(extractCommand(' \n \t ')).toBe(''); + }); + + // Test comment-only inputs + it('should handle comment-only inputs', () => { + expect(extractCommand('/* comment */')).toBe(''); + expect(extractCommand('# comment')).toBe(''); + expect(extractCommand('// comment')).toBe(''); + expect(extractCommand('/* multi\nline\ncomment */')).toBe(''); + }); + + // Test inline comments + it('should handle inline comments correctly according to implementation', () => { + // But removes multiline comments even when inline + expect(extractCommand('/* inline */ echo hello world')).toBe('echo hello world'); + }); + + // Test multiple line continuations + it('should handle multiple line continuations', () => { + expect(extractCommand(` + echo hello && \\ + echo world && \\ + echo test + `)).toBe('echo hello && echo world && echo test'); + }); + + // Test nested line continuations + it('should handle nested line continuations', () => { + expect(extractCommand(` + echo hello && \\ + (echo nested && \\ + echo more) && \\ + echo final + `)).toBe('echo hello && (echo nested && echo more) && echo final'); + }); +}); \ No newline at end of file diff --git a/gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts b/gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts new file mode 100644 index 000000000..35075b6bd --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts @@ -0,0 +1,50 @@ +/** + * Extracts and processes command strings, handling comments and line continuations. + * @param cmd The command string to process + * @returns The processed command string + */ +export function extractCommand(cmd: string): string { + if (!cmd || cmd.trim() === '') { + return ''; + } + + // Remove multi-line comments (/* ... */) and replace with a single space + cmd = cmd.replace(/\/\*[\s\S]*?\*\//g, " "); + + // Handle the $ prompt case first + if (cmd.includes("$")) { + const match = cmd.match(/\$\s*([^\n]+)/); + if (match) { + // Return just the command after $ without further processing + return match[1].trim(); + } + } + + // Process lines - remove single-line comments only at beginning of lines + const lines = cmd.split('\n') + .map(line => line.replace(/^\s*#.*$/, '').replace(/^\s*\/\/.*$/, '')) + .map(line => line.trim()) + .filter(line => line); + + // Join lines with proper handling of continuations + let result = ''; + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + + // Remove trailing continuation characters and join with next line + while ( + (line.endsWith('&&') || line.endsWith('|') || line.endsWith('\\')) && + i < lines.length - 1 + ) { + // Remove the continuation character(s) and any trailing spaces + line = line.replace(/(&&|\||\\)\s*$/, '').trim(); + // Join with the next line + i++; + line += ' ' + lines[i]; + } + + result += line + ' '; + } + + return result.trim().replace(/\s+/g, ' '); +} \ No newline at end of file diff --git a/gui/src/components/TabBar/TabBar.tsx b/gui/src/components/TabBar/TabBar.tsx index 3b87a23c6..7f881edd5 100644 --- a/gui/src/components/TabBar/TabBar.tsx +++ b/gui/src/components/TabBar/TabBar.tsx @@ -1,5 +1,5 @@ import { XMarkIcon } from "@heroicons/react/24/outline"; -import { useCallback, useEffect } from "react"; +import React, { useCallback, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius } from ".."; @@ -13,16 +13,30 @@ import { } from "../../redux/slices/tabsSlice"; import { AppDispatch, RootState } from "../../redux/store"; import { loadSession, saveCurrentSession } from "../../redux/thunks/session"; +import { varWithFallback } from "../../styles/theme"; + +// Haven't set up theme colors for tabs yet +// Will keep it simple and choose from existing ones. Comments show vars we could use +const tabBorderVar = varWithFallback("border"); // --vscode-tab-border +const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground +const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground +const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground +const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground +const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground +const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground +const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop const TabBarContainer = styled.div` display: flex; flex-wrap: wrap; flex-shrink: 0; flex-grow: 0; - background-color: var(--vscode-tab-inactiveBackground); + background-color: ${tabBackgroundVar}; border-bottom: none; position: relative; margin-top: 2px; + max-height: 100px; + overflow: auto; /* Hide scrollbar but keep functionality */ scrollbar-width: none; @@ -41,24 +55,18 @@ const Tab = styled.div<{ isActive: boolean }>` max-width: 150px; height: 25px; background-color: ${(props) => - props.isActive - ? "var(--vscode-tab-activeBackground)" - : "var(--vscode-tab-inactiveBackground)"}; + props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar}; color: ${(props) => - props.isActive - ? "var(--vscode-tab-activeForeground)" - : "var(--vscode-tab-inactiveForeground)"}; + props.isActive ? tabSelectedForegroundVar : tabForegroundVar}; cursor: pointer; - border: 1px solid var(--vscode-tab-border); + border: 1px solid ${tabBorderVar}; border-bottom: ${(props) => - props.isActive ? "none" : `1px solid var(--vscode-tab-border)`}; + props.isActive ? "none" : `1px solid ${tabBorderVar}`}; user-select: none; position: relative; transition: background-color 0.2s; border-top: ${(props) => - props.isActive - ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)` - : `1px solid var(--vscode-tab-border)`}; + props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`}; &:first-child { border-left: none; } @@ -68,13 +76,9 @@ const Tab = styled.div<{ isActive: boolean }>` &:hover { background-color: ${(props) => - props.isActive - ? "var(--vscode-tab-activeBackground)" - : "var(--vscode-tab-hoverBackground)"}; + props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar}; color: ${(props) => - props.isActive - ? "var(--vscode-tab-activeForeground)" - : "var(--vscode-tab-hoverForeground)"}; + props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar}; } `; @@ -104,7 +108,7 @@ const CloseButton = styled.button` &:hover { opacity: 1; - background-color: var(--vscode-tab-hoverBackground); + background-color: ${tabHoverBackgroundVar}; } ${Tab}:hover & { @@ -119,33 +123,12 @@ const CloseButton = styled.button` const TabBarSpace = styled.div` flex: 1; display: flex; - border-bottom: 1px solid var(--vscode-tab-border); - background-color: var(--vscode-tab-inactiveBackground); + border-bottom: 1px solid ${tabBorderVar}; + background-color: ${tabBackgroundVar}; `; -const NewTabButton = styled.button` - display: flex; - align-items: center; - justify-content: center; - width: 35px; - height: 100%; - border: none; - background: transparent; - color: var(--vscode-tab-inactiveForeground); - cursor: pointer; - opacity: 0.7; - transition: opacity 0.2s; - - &:hover { - opacity: 1; - background-color: var(--vscode-tab-hoverBackground); - color: var(--vscode-tab-hoverForeground); - } -`; - -export function TabBar() { +export const TabBar = React.forwardRef((_, ref) => { const dispatch = useDispatch(); - const currentSession = useSelector((state: RootState) => state.session); const currentSessionId = useSelector((state: RootState) => state.session.id); const currentSessionTitle = useSelector( (state: RootState) => state.session.title, @@ -160,7 +143,6 @@ export function TabBar() { return Date.now().toString(36) + Math.random().toString(36).substring(2); }, []); - // Handle session changes useEffect(() => { if (!currentSessionId) return; @@ -243,10 +225,13 @@ export function TabBar() { } }; - return tabs.length === 1 ? ( - <> - ) : ( - + return ( + {tabs.map((tab) => ( ); -} +}); diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 5acf040b6..d205d59f8 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -4,12 +4,11 @@ import ReactMarkdown from "react-markdown"; import styled from "styled-components"; import { CloseButton, - VSC_BACKGROUND_VAR, defaultBorderRadius, - parseColorForHex, vscBackground, vscForeground, } from ".."; +import { varWithFallback } from "../../styles/theme"; interface TextDialogProps { showDialog: boolean; @@ -22,7 +21,7 @@ const ScreenCover = styled.div` position: fixed; width: 100%; height: 100%; - background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa; + background-color: ${varWithFallback("background")}aa; z-index: 100000; flex-direction: column; `; diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index fd174f59c..f5badfe41 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -13,35 +13,24 @@ import { } from "react"; import { HeaderButton, Input } from ".."; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { useAppSelector } from "../../redux/hooks"; +import { + Rectangle, + SearchMatch, + searchWithinContainer, +} from "./findWidgetSearch"; +import useDebounceValue from "./useDebounce"; +import { useElementSize } from "./useElementSize"; -interface SearchMatch { - index: number; - textNode: Text; - overlayRectangle: Rectangle; -} - -type ScrollToMatchOption = "closest" | "first" | "none"; - -const SEARCH_DEBOUNCE = 300; -const RESIZE_DEBOUNCE = 200; - -interface Rectangle { - top: number; - left: number; - width: number; - height: number; -} - -interface HighlightOverlayProps extends Rectangle { +interface HighlightOverlayProps { + rectangle: Rectangle; isCurrent: boolean; } const HighlightOverlay = (props: HighlightOverlayProps) => { - const { isCurrent, top, left, width, height } = props; + const { top, left, width, height } = props.rectangle; return (
{ ); }; +type ScrollToMatchOption = "closest" | "first" | "none"; + /* useFindWidget takes a container ref and returns 1. A widget that can be placed anywhere to search the contents of that container @@ -64,18 +55,22 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { Container must have relative positioning */ -export const useFindWidget = (searchRef: RefObject) => { +export const useFindWidget = ( + searchRef: RefObject, + headerRef: RefObject, + disabled: boolean, +) => { // Search input, debounced - const [input, setInput] = useState(""); - const debouncedInput = useRef(""); const inputRef = useRef(null); + const [currentValue, setCurrentValue] = useState(""); + const searchTerm = useDebounceValue(currentValue, 300); // Widget open/closed state const [open, setOpen] = useState(false); const openWidget = useCallback(() => { setOpen(true); inputRef?.current?.select(); - }, [setOpen, inputRef]); + }, [inputRef]); // Search settings and results const [caseSensitive, setCaseSensitive] = useState(false); @@ -97,7 +92,7 @@ export const useFindWidget = (searchRef: RefObject) => { behavior: "smooth", }); }, - [searchRef.current], + [searchRef], ); const nextMatch = useCallback(() => { @@ -143,327 +138,166 @@ export const useFindWidget = (searchRef: RefObject) => { }, [inputRef, matches, nextMatch]); // Handle container resize changes - highlight positions must adjust - const [isResizing, setIsResizing] = useState(false); - useEffect(() => { - let timeoutId: NodeJS.Timeout | null = null; - if (!searchRef?.current) return; - - const resizeObserver = new ResizeObserver((entries) => { - if (timeoutId) { - clearTimeout(timeoutId); - } - setIsResizing(true); - timeoutId = setTimeout(() => { - setIsResizing(false); - }, RESIZE_DEBOUNCE); - }); - - resizeObserver.observe(searchRef.current); - return () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - if (searchRef.current) resizeObserver.unobserve(searchRef.current); - }; - }, [searchRef.current]); + const { clientHeight: headerHeight, isResizing: headerResizing } = + useElementSize(headerRef); + const { isResizing: containerResizing } = useElementSize(searchRef); + const isResizing = useMemo(() => { + return containerResizing || headerResizing; + }, [containerResizing, headerResizing]); // Main function for finding matches and generating highlight overlays const refreshSearch = useCallback( - (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { - if (clearFirst) setMatches([]); - - const searchContainer = searchRef.current; - - const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable - if (!searchContainer || !_query) { - setMatches([]); - return; - } - const query = caseSensitive ? _query : _query.toLowerCase(); - - // First grab all text nodes - // Skips any elements with the "find-widget-skip" class - const textNodes: Text[] = []; - const walker = document.createTreeWalker( - searchRef.current, - NodeFilter.SHOW_ALL, + (scrollTo: ScrollToMatchOption = "none") => { + const { results, closestToMiddle } = searchWithinContainer( + searchRef, + searchTerm, { - acceptNode: (node) => { - if (node.nodeType === Node.ELEMENT_NODE) { - if ((node as Element).classList.contains("find-widget-skip")) - return NodeFilter.FILTER_REJECT; - return NodeFilter.FILTER_ACCEPT; - } else if (node.nodeType === Node.TEXT_NODE) { - if (!node.nodeValue) return NodeFilter.FILTER_REJECT; - const nodeValue = caseSensitive - ? node.nodeValue - : node.nodeValue.toLowerCase(); - if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; - } - return NodeFilter.FILTER_REJECT; - }, + caseSensitive, + useRegex, + offsetHeight: headerHeight, }, ); - - while (walker.nextNode()) { - if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; - textNodes.push(walker.currentNode as Text); - } - - // Now walk through each node match and extract search results - // One node can have several matches - const newMatches: SearchMatch[] = []; - textNodes.forEach((textNode, idx) => { - // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail - const highlightFullLine = - textNode.parentElement?.className.includes("hljs"); - - let nodeTextValue = caseSensitive - ? textNode.nodeValue - : textNode.nodeValue.toLowerCase(); - let startIndex = 0; - while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { - // Create a range to measure the size and position of the match - const range = document.createRange(); - range.setStart(textNode, startIndex); - const endIndex = startIndex + query.length; - range.setEnd(textNode, endIndex); - const rect = range.getBoundingClientRect(); - range.detach(); - startIndex = endIndex; - - const top = - rect.top + searchContainer.clientTop + searchContainer.scrollTop; - const left = - rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; - - // Build a match result and push to matches - const newMatch: SearchMatch = { - index: 0, // will set later - textNode, - overlayRectangle: { - top, - left: highlightFullLine ? 2 : left, - width: highlightFullLine - ? searchContainer.clientWidth - 4 - : rect.width, // equivalent of adding 2 px x padding - height: rect.height, - }, - }; - newMatches.push(newMatch); - - if (highlightFullLine) { - break; // Since highlighting full line no need for multiple overlays, will cause darker highlight - } - } - }); - - // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) - // Filter them out by using the overlay rectangle as a hash key - const matchHash = Object.fromEntries( - newMatches.map((match) => [ - JSON.stringify(match.overlayRectangle), - match, - ]), - ); - const filteredMatches = Object.values(matchHash).map((match, index) => ({ - ...match, - index, - })); - + setMatches(results); // Find match closest to the middle of the view - const verticalMiddle = - searchRef.current.scrollTop + searchRef.current.clientHeight / 2; - let closestDist = Infinity; - let closestMatchToMiddle: SearchMatch | null = null; - filteredMatches.forEach((match) => { - const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); - if (dist < closestDist) { - closestDist = dist; - closestMatchToMiddle = match; - } - }); - - // Update matches and scroll to the closest or first match - setMatches(filteredMatches); - if (query.length > 1 && filteredMatches.length) { + if (searchTerm.length > 1 && results.length) { if (scrollTo === "first") { - scrollToMatch(filteredMatches[0]); + scrollToMatch(results[0]); } if (scrollTo === "closest") { - if (closestMatchToMiddle) { - scrollToMatch(closestMatchToMiddle); + if (closestToMiddle) { + scrollToMatch(closestToMiddle); } } if (scrollTo === "none") { - if (closestMatchToMiddle) { - setCurrentMatch(closestMatchToMiddle); + if (closestToMiddle) { + setCurrentMatch(closestToMiddle); } else { - setCurrentMatch(filteredMatches[0]); + setCurrentMatch(results[0]); } } } }, - [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex], + [ + searchTerm, + caseSensitive, + useRegex, + searchRef, + headerHeight, + scrollToMatch, + ], ); // Triggers that should cause immediate refresh of results to closest search value: - // Input change (debounced) and window click - const lastUpdateRef = useRef(0); useEffect(() => { - const debounce = () => { - debouncedInput.current = input; - lastUpdateRef.current = Date.now(); - refreshSearch("closest"); - }; - const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; - if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { - debounce(); + if (disabled || isResizing || !open) { + setMatches([]); } else { - const handler = setTimeout(() => { - debounce(); - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); - return () => { - clearTimeout(handler); - }; + refreshSearch("closest"); } - }, [refreshSearch, input]); + }, [refreshSearch, open, disabled, isResizing]); - // Could consider doing any window click but I only handled search div here - // Since usually only clicks in search div will cause content changes in search div + // Clicks in search div can cause content changes that for some reason don't trigger resize + // Refresh clicking within container useEffect(() => { const searchContainer = searchRef.current; if (!open || !searchContainer) return; const handleSearchRefClick = () => { - refreshSearch("none"); + setTimeout(() => { + refreshSearch("none"); + }, 150); }; searchContainer.addEventListener("click", handleSearchRefClick); return () => { searchContainer.removeEventListener("click", handleSearchRefClick); }; - }, [searchRef.current, refreshSearch, open]); - - // Triggers that should cause results to temporarily disappear and then reload - // Active = LLM is generating, etc. - const active = useAppSelector((state) => state.session.isStreaming); - - useEffect(() => { - if (active || isResizing) setMatches([]); - else refreshSearch("none"); - }, [refreshSearch, active]); - - useEffect(() => { - if (!open) setMatches([]); - else refreshSearch("closest"); - }, [refreshSearch, open]); - - useEffect(() => { - refreshSearch("closest"); - }, [refreshSearch, caseSensitive, useRegex]); + }, [searchRef, refreshSearch, open]); // Find widget component - const widget = useMemo(() => { - return ( -
- { - setInput(e.target.value); - }} - placeholder="Search..." - /> -

- {matches.length === 0 - ? "No results" - : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} -

-
- { - e.stopPropagation(); - previousMatch(); - }} - className="h-4 w-4 focus:ring" - disabled={matches.length < 2 || active} - > - - - { - e.stopPropagation(); - nextMatch(); - }} - className="h-4 w-4 focus:ring" - disabled={matches.length < 2 || active} - > - - -
+ const widget = ( +
+ { + setCurrentValue(e.target.value); + }} + placeholder="Search..." + /> +

+ {matches.length === 0 + ? "No results" + : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} +

+
{ e.stopPropagation(); - setCaseSensitive((curr) => !curr); + previousMatch(); }} - className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" + className="h-4 w-4 focus:ring" + disabled={matches.length < 2 || disabled} > - Aa + - {/* TODO - add useRegex functionality */} - setOpen(false)} - className="focus:ring" + { + e.stopPropagation(); + nextMatch(); + }} + className="h-4 w-4 focus:ring" + disabled={matches.length < 2 || disabled} > - - + +
- ); - }, [ - open, - input, - inputRef, - caseSensitive, - matches, - currentMatch, - previousMatch, - nextMatch, - ]); + { + e.stopPropagation(); + setCaseSensitive((curr) => !curr); + }} + className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" + > + Aa + + {/* TODO - add useRegex functionality */} + setOpen(false)} + className="focus:ring" + > + + +
+ ); // Generate the highlight overlay elements const highlights = useMemo(() => { return matches.map((match) => ( )); }, [matches, currentMatch]); return { - matches, highlights, - inputRef, - input: debouncedInput, - setInput, - open, - setOpen, widget, }; }; diff --git a/gui/src/components/find/findWidgetSearch.ts b/gui/src/components/find/findWidgetSearch.ts new file mode 100644 index 000000000..8b03d77af --- /dev/null +++ b/gui/src/components/find/findWidgetSearch.ts @@ -0,0 +1,146 @@ +export interface Rectangle { + top: number; + left: number; + width: number; + height: number; +} + +export interface SearchMatch { + index: number; + textNode: Text; + overlayRectangle: Rectangle; +} + +interface SearchOptions { + caseSensitive: boolean; + useRegex: boolean; + offsetHeight: number; +} + +export const searchWithinContainer = ( + containerRef: React.RefObject, + searchQuery: string, + options: SearchOptions, +): { + results: SearchMatch[]; + closestToMiddle: SearchMatch | null; +} => { + const searchContainer = containerRef.current; + + if (!searchContainer || !searchQuery) { + return { + results: [], + closestToMiddle: null, + }; + } + const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase(); + + // First grab all text nodes + // Skips any elements with the "find-widget-skip" class + const textNodes: Text[] = []; + const walker = document.createTreeWalker( + searchContainer, + NodeFilter.SHOW_ALL, + { + acceptNode: (node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + if ((node as Element).classList.contains("find-widget-skip")) + return NodeFilter.FILTER_REJECT; + return NodeFilter.FILTER_ACCEPT; + } else if (node.nodeType === Node.TEXT_NODE) { + if (!node.nodeValue) return NodeFilter.FILTER_REJECT; + const nodeValue = options.caseSensitive + ? node.nodeValue + : node.nodeValue.toLowerCase(); + if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; + } + return NodeFilter.FILTER_REJECT; + }, + }, + ); + + while (walker.nextNode()) { + if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; + textNodes.push(walker.currentNode as Text); + } + + // Now walk through each node match and extract search results + // One node can have several matches + const newMatches: SearchMatch[] = []; + textNodes.forEach((textNode, idx) => { + // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail + const highlightFullLine = + textNode.parentElement?.className.includes("hljs"); + + let nodeTextValue = options.caseSensitive + ? textNode.nodeValue + : textNode.nodeValue.toLowerCase(); + let startIndex = 0; + while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { + // Create a range to measure the size and position of the match + const range = document.createRange(); + range.setStart(textNode, startIndex); + const endIndex = startIndex + query.length; + range.setEnd(textNode, endIndex); + const rect = range.getBoundingClientRect(); + range.detach(); + startIndex = endIndex; + + const top = + rect.top + + searchContainer.clientTop + + searchContainer.scrollTop - + options.offsetHeight; + + const left = + rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; + + // Build a match result and push to matches + const newMatch: SearchMatch = { + index: 0, // will set later + textNode, + overlayRectangle: { + top, + left: highlightFullLine ? 2 : left, + width: highlightFullLine + ? searchContainer.clientWidth - 4 + : rect.width, // equivalent of adding 2 px x padding + height: rect.height, + }, + }; + newMatches.push(newMatch); + + if (highlightFullLine) { + break; // Since highlighting full line no need for multiple overlays, will cause darker highlight + } + } + }); + + // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) + // Filter them out by using the overlay rectangle as a hash key + const matchHash = Object.fromEntries( + newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]), + ); + const filteredMatches = Object.values(matchHash).map((match, index) => ({ + ...match, + index, + })); + + // Find the match closest to the vertical middle of the container + const verticalMiddle = + searchContainer.scrollTop + searchContainer.clientHeight / 2; + let closestDist = Infinity; + let closestMatchToMiddle: SearchMatch | null = null; + filteredMatches.forEach((match) => { + const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); + if (dist < closestDist) { + closestDist = dist; + closestMatchToMiddle = match; + } + }); + + return { + results: filteredMatches, + closestToMiddle: closestMatchToMiddle, + }; +}; diff --git a/gui/src/components/find/useDebounce.ts b/gui/src/components/find/useDebounce.ts new file mode 100644 index 000000000..8a9898429 --- /dev/null +++ b/gui/src/components/find/useDebounce.ts @@ -0,0 +1,19 @@ +import { useEffect, useState } from "react"; + +function useDebounceValue(value: T, delay: number = 500): T { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timer = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(timer); + }; + }, [value, delay]); + + return debouncedValue; +} + +export default useDebounceValue; diff --git a/gui/src/components/find/useElementSize.ts b/gui/src/components/find/useElementSize.ts new file mode 100644 index 000000000..fc4b307a2 --- /dev/null +++ b/gui/src/components/find/useElementSize.ts @@ -0,0 +1,81 @@ +import { RefObject, useCallback, useEffect, useState } from "react"; + +interface ElementSize { + clientWidth: number; + clientHeight: number; + scrollWidth: number; + scrollHeight: number; + isResizing: boolean; +} + +interface UseElementSizeOptions { + debounceMs?: number; +} + +export const useElementSize = ( + ref: RefObject, + debounceMs = 250, +): ElementSize => { + const [size, setSize] = useState({ + clientWidth: 0, + clientHeight: 0, + scrollWidth: 0, + scrollHeight: 0, + isResizing: false, + }); + + // Debounced update function + const debouncedSetSize = useCallback( + (measurements: Omit) => { + let timeoutId: NodeJS.Timeout; + + setSize((prev) => ({ ...prev, isResizing: true })); + + timeoutId = setTimeout(() => { + setSize({ + ...measurements, + isResizing: false, + }); + }, debounceMs); + + return () => clearTimeout(timeoutId); + }, + [debounceMs], + ); + + useEffect(() => { + if (!ref.current) return; + + const updateSize = () => { + const element = ref.current; + if (!element) return; + + const measurements = { + clientWidth: element.clientWidth, + clientHeight: element.clientHeight, + scrollWidth: element.scrollWidth, + scrollHeight: element.scrollHeight, + }; + + debouncedSetSize(measurements); + }; + + // Create ResizeObserver instance + const resizeObserver = new ResizeObserver(() => { + updateSize(); + }); + + // Start observing the element + resizeObserver.observe(ref.current); + + // Initial size calculation + updateSize(); + + // Cleanup + return () => { + resizeObserver.disconnect(); + }; + }, [ref, debouncedSetSize]); + + return size; +}; diff --git a/gui/src/components/gui/Alert.tsx b/gui/src/components/gui/Alert.tsx index cc1e5c9d1..be4d72160 100644 --- a/gui/src/components/gui/Alert.tsx +++ b/gui/src/components/gui/Alert.tsx @@ -39,7 +39,7 @@ function Alert({ children, type = "info" }: AlertProps) { const { Icon } = ALERT_CONFIGS[type]; return ( -
+
6) { - hexColor = hexColor.slice(0, 6); - } - - const r = parseInt(hexColor.substring(0, 2), 16); - const g = parseInt(hexColor.substring(2, 4), 16); - const b = parseInt(hexColor.substring(4, 6), 16); - - return { r, g, b }; -} - -export function parseColorForHex(colorVar: string): string { - const value = getComputedStyle(document.documentElement).getPropertyValue( - colorVar, - ); - if (value.startsWith("#")) { - return value.slice(0, 7); - } - - // Parse rgb/rgba - const rgbValues = value - .slice(value.startsWith("rgba") ? 5 : 4, -1) - .split(",") - .map((x) => x.trim()) - .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) - .map((x) => parseInt(x, 10)); - - let hex = - "#" + - rgbValues - .map((x) => x.toString(16)) - .map((x) => (x.length === 1 ? "0" + x : x)) - .join(""); - - return hex; -} +export const vscInputBackground = varWithFallback("input-background"); +export const vscQuickInputBackground = varWithFallback("input-background"); +export const vscBackground = varWithFallback("background"); +export const vscForeground = varWithFallback("foreground"); +export const vscButtonBackground = varWithFallback("primary-background"); +export const vscButtonForeground = varWithFallback("primary-foreground"); +export const vscEditorBackground = varWithFallback("editor-background"); +export const vscListActiveBackground = varWithFallback("list-active"); +export const vscFocusBorder = varWithFallback("border-focus"); +export const vscListActiveForeground = varWithFallback( + "list-active-foreground", +); +export const vscInputBorder = varWithFallback("input-border"); +export const vscInputBorderFocus = varWithFallback("border-focus"); +export const vscBadgeBackground = varWithFallback("badge-background"); +export const vscBadgeForeground = varWithFallback("badge-foreground"); +export const vscCommandCenterActiveBorder = varWithFallback( + "command-border-focus", +); +export const vscCommandCenterInactiveBorder = varWithFallback("command-border"); export const Button = styled.button` padding: 6px 12px; @@ -158,7 +75,7 @@ export const GhostButton = styled.button` border: none; color: ${vscForeground}; - background-color: rgba(255, 255, 255, 0.08); + background-color: rgba(128, 128, 128, 0.4); &:disabled { color: gray; pointer-events: none; @@ -226,10 +143,6 @@ export const Input = styled.input` } `; -export const Label = styled.label<{ fontSize?: number }>` - font-size: ${(props) => props.fontSize || getFontSize()}px; -`; - export const HeaderButton = styled.button<{ inverted: boolean | undefined; backgroundColor?: string; 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/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index a5b89d0f4..3b8359e96 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -159,7 +159,7 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { contentEditable={false} >
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 4281221a5..194346045 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(); @@ -246,12 +246,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 }} > @@ -270,7 +270,7 @@ export default function AssistantSelect() {
@@ -305,7 +305,7 @@ export default function AssistantSelect() { > @@ -343,7 +343,7 @@ export default function AssistantSelect() { onClick={session ? onNewAssistant : () => login(false)} >
( ]); case "getControlPlaneSessionInfo": return returnFor("getControlPlaneSessionInfo", { + AUTH_TYPE: AuthType.WorkOsStaging, accessToken: "", account: { label: "", diff --git a/gui/src/context/VscTheme.tsx b/gui/src/context/VscTheme.tsx index 2ca1dac59..8a0195141 100644 --- a/gui/src/context/VscTheme.tsx +++ b/gui/src/context/VscTheme.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useState } from "react"; -import { parseHexColor } from "../components"; import { useWebviewListener } from "../hooks/useWebviewListener"; +import { parseHexColor } from "../styles/utils"; const hljsToTextMate: Record = { ".hljs-comment": ["comment"], diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 1b609ce39..155b91e2c 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -1,9 +1,9 @@ import { useCallback, useContext, useEffect, useRef } from "react"; -import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { FromCoreProtocol } from "core/protocol"; +import { useMainEditor } from "../components/mainInput/TipTapEditor"; import { initializeProfilePreferences, setOrganizations, @@ -16,7 +16,7 @@ import { setConfigResult } from "../redux/slices/configSlice"; import { setLastNonEditSessionEmpty, updateEditStateApplyState, -} from "../redux/slices/editModeState"; +} from "../redux/slices/editState"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { acceptToolCall, @@ -24,11 +24,15 @@ import { updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; -import { streamResponseAfterToolCall } from "../redux/thunks"; +import { exitEdit, streamResponseAfterToolCall } from "../redux/thunks"; import { cancelStream } from "../redux/thunks/cancelStream"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; +import { + setDocumentStylesFromLocalStorage, + setDocumentStylesFromTheme, +} from "../styles/theme"; import { isJetBrains } from "../util"; import { setLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; @@ -37,12 +41,18 @@ function ParallelListeners() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => 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]) => { @@ -96,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); @@ -129,76 +139,50 @@ 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(); - for (const colorVar of VSC_THEME_COLOR_VARS) { - if (jetbrains) { - const cached = localStorage.getItem(colorVar); - if (cached) { - document.body.style.setProperty(colorVar, cached); - } - } - - // Remove alpha channel from colors - const value = getComputedStyle(document.documentElement).getPropertyValue( - colorVar, - ); - if (colorVar.startsWith("#") && value.length > 7) { - document.body.style.setProperty(colorVar, value.slice(0, 7)); - } - } + 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") { - Object.entries(result.content).forEach(([key, value]) => { - document.body.style.setProperty(key, value); - document.documentElement.style.setProperty(key, value); - }); - } - }); + 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; - }); - - for (const colorVar of VSC_THEME_COLOR_VARS) { - if (document.body.style.getPropertyValue(colorVar)) { - localStorage.setItem( - colorVar, - document.body.style.getPropertyValue(colorVar), - ); - } - } + 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; + }); } }, []); useWebviewListener( "jetbrains/setColors", async (data) => { - Object.entries(data).forEach(([key, value]) => { - document.body.style.setProperty(key, value); - document.documentElement.style.setProperty(key, value); - }); + setDocumentStylesFromTheme(data); }, [], ); @@ -221,7 +205,7 @@ function ParallelListeners() { ); useWebviewListener("setInactive", async () => { - dispatch(cancelStream()); + void dispatch(cancelStream()); }); useWebviewListener("setTTSActive", async (status) => { @@ -230,7 +214,7 @@ function ParallelListeners() { // TODO - remove? useWebviewListener("submitMessage", async (data) => { - dispatch( + void dispatch( streamResponseThunk({ editorState: data.message, modifiers: { useCodebase: false, noContext: true }, @@ -251,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)); @@ -280,7 +265,7 @@ function ParallelListeners() { }), ); // dispatch(setToolCallOutput([])); - dispatch( + void dispatch( streamResponseAfterToolCall({ toolCallId: currentToolCallApplyState.toolCallId!, }), @@ -291,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/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index b293de719..2d6d06b4f 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,5 +1,6 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; +import { isHubSession } from "core/control-plane/AuthTypes"; import { SecondaryButton } from "../../components"; import { Popover, @@ -27,6 +28,11 @@ export function AccountButton() { ); } + // No login button for on-prem deployments + if (!isHubSession(session)) { + return null; + } + return ( {({ close }) => ( diff --git a/gui/src/pages/config/HelpCenterSection.tsx b/gui/src/pages/config/HelpCenterSection.tsx index a82b775a8..e49a17780 100644 --- a/gui/src/pages/config/HelpCenterSection.tsx +++ b/gui/src/pages/config/HelpCenterSection.tsx @@ -1,6 +1,7 @@ import { ArrowTopRightOnSquareIcon, DocumentArrowUpIcon, + PaintBrushIcon, TableCellsIcon, } from "@heroicons/react/24/outline"; import { useContext } from "react"; @@ -9,6 +10,7 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch } from "../../redux/hooks"; import { setOnboardingCard } from "../../redux/slices/uiSlice"; import { saveCurrentSession } from "../../redux/thunks/session"; +import { ROUTES } from "../../util/navigation"; import MoreHelpRow from "./MoreHelpRow"; export function HelpCenterSection() { @@ -83,6 +85,16 @@ export function HelpCenterSection() { ideMessenger.post("showTutorial", undefined); }} /> + {process.env.NODE_ENV === "development" && ( + { + navigate(ROUTES.THEME); + }} + /> + )}
); diff --git a/gui/src/pages/config/KeyboardShortcuts.tsx b/gui/src/pages/config/KeyboardShortcuts.tsx index d7c3828d7..77d8c2733 100644 --- a/gui/src/pages/config/KeyboardShortcuts.tsx +++ b/gui/src/pages/config/KeyboardShortcuts.tsx @@ -11,7 +11,7 @@ interface KeyboardShortcutProps { function KeyboardShortcut(props: KeyboardShortcutProps) { return (
{props.description}: 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 71b87c93a..75fb48c4b 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -44,24 +44,21 @@ import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiSlice"; -import { cancelStream } from "../../redux/thunks/cancelStream"; -import { streamEditThunk } from "../../redux/thunks/editMode"; -import { loadLastSession } from "../../redux/thunks/session"; import { streamResponseThunk } from "../../redux/thunks"; +import { cancelStream } from "../../redux/thunks/cancelStream"; +import { streamEditThunk } from "../../redux/thunks/edit"; +import { loadLastSession } from "../../redux/thunks/session"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS, incrementFreeTrialCount, } from "../../util/freeTrial"; -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"; import { ToolCallDiv } from "./ToolCallDiv"; import { useAutoScroll } from "./useAutoScroll"; -import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; const StepsDiv = styled.div` position: relative; @@ -113,6 +110,7 @@ export function Chat() { const [stepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); const stepsDivRef = useRef(null); + const tabsRef = useRef(null); const history = useAppSelector((state) => state.session.history); const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, @@ -120,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( @@ -143,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); @@ -152,7 +149,11 @@ export function Chat() { }; }, [isStreaming, jetbrains]); - const { widget, highlights } = useFindWidget(stepsDivRef); + const { widget, highlights } = useFindWidget( + stepsDivRef, + tabsRef, + isStreaming, + ); const currentToolCallApplyState = useAppSelector( selectCurrentToolCallApplyState, @@ -179,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; } @@ -218,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(); @@ -246,7 +246,15 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [history, selectedModels, streamResponse, mode, codeToEdit, toolCallState], + [ + history, + selectedModels, + streamResponse, + mode, + isInEdit, + codeToEdit, + toolCallState, + ], ); useWebviewListener( @@ -286,13 +294,12 @@ export function Chat() { return ( <> + {!!showSessionTabs && !isInEdit && } {widget} - {!!showSessionTabs && mode !== "edit" && } - 0 ? "flex-1" : ""}`} + className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} > {highlights} {history.map((item, index: number) => ( @@ -376,24 +383,14 @@ export function Chat() { ))}
- <> - {!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/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 50caf7dfe..7d5f652bf 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -1,12 +1,15 @@ import { ArrowTopRightOnSquareIcon, - Cog8ToothIcon, + ClipboardIcon, + Cog6ToothIcon, + KeyIcon, } from "@heroicons/react/24/outline"; import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; import { useContext, useMemo } from "react"; -import { Button, SecondaryButton } from "../../components"; +import { GhostButton, SecondaryButton } from "../../components"; import { DiscordIcon } from "../../components/svg/DiscordIcon"; import { GithubIcon } from "../../components/svg/GithubIcon"; +import ToggleDiv from "../../components/ToggleDiv"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { selectSelectedProfile } from "../../redux/"; @@ -48,11 +51,15 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); const handleRefreshProfiles = () => { - refreshProfiles(); + void refreshProfiles(); dispatch(setShowDialog(false)); dispatch(setDialogMessage(undefined)); }; + const copyErrorToClipboard = () => { + void navigator.clipboard.writeText(parsedError); + }; + // Collect model information to display useful error info let modelTitle = "Chat model"; let providerName = "the model provider"; @@ -99,30 +106,29 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { } const checkKeysButton = apiKeyUrl ? ( - + + View key + ) : null; const configButton = ( - { ideMessenger.post("config/openProfile", { profileId: undefined, }); }} > -
- -
- Open Assistant configuration -
+ + View config + ); if ( @@ -131,7 +137,20 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { return ; } - let errorContent: React.ReactNode = <>; + let errorContent = ( +
+
+

+ There was an error handling the response from{" "} + {selectedModel?.title || "the model"}. +

+

+ Please try to submit your message again, and if the error persists, + let us know by reporting the issue using the buttons below. +

+
+
+ ); // Display components for specific errors if (statusCode === 429) { @@ -141,7 +160,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { {`This might mean your ${modelTitle} usage has been rate limited by ${providerName}.`} -
+
{checkKeysButton} {configButton}
@@ -230,51 +249,71 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); } + console.log({ message }); + return ( -
-

- {statusCode ? `Error (status code ${statusCode})` : "Error"} -

+
+ {/* Concise error title */} +

+ Error handling model response +

- {message ? ( -
- - {parsedError} - -
{ - ideMessenger.post("toggleDevTools", undefined); - }} - > - View Logs - -
+ {errorContent} + + {/* Expandable technical details using ToggleDiv */} + {message && ( +
+ +
+ + {parsedError} + + +
+ + + Copy output + + + { + ideMessenger.post("toggleDevTools", undefined); + }} + className="flex items-center" + > + + View Logs + +
+
+
- ) : null} -
{errorContent}
+ )} -
- Report this error: -
- + Report this error +
+ { ideMessenger.post("openUrl", GITHUB_LINK); }} > Github - - + { ideMessenger.post("openUrl", DISCORD_LINK); }} > Discord - +
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/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index c9a21a30c..8f11fc7f5 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -100,6 +100,7 @@ export const streamResponseThunk = createAsyncThunk< ? (userMsg as UserChatMessage | ToolResultChatMessage) : undefined, rules, + selectedContextItems, ); // Store in history for UI display diff --git a/gui/src/styles/ThemePage.tsx b/gui/src/styles/ThemePage.tsx new file mode 100644 index 000000000..b365ec535 --- /dev/null +++ b/gui/src/styles/ThemePage.tsx @@ -0,0 +1,232 @@ +import { + CheckCircleIcon, + ExclamationCircleIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { useContext, useEffect, useMemo, useState } from "react"; +import { useNavigate } from "react-router-dom"; +import { Button } from "../components"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { isJetBrains } from "../util"; +import { ROUTES } from "../util/navigation"; +import { + clearThemeLocalCache, + setDocumentStylesFromTheme, + THEME_COLORS, + varWithFallback, +} from "./theme"; + +const ThemeTailwindClassExample = ({ + colorName, + varNames, + defaultColor, + isMissing, +}: { + colorName: string; + varNames: string[]; + defaultColor: string; + isMissing?: boolean; +}) => { + return ( + <> +
+ {colorName} +
+
+ {varNames.join(", ")} +
+
+ {defaultColor} +
+ + ); +}; + +function ThemePage() { + const navigate = useNavigate(); + const [listToggled, setListToggled] = useState(false); + const ideMessenger = useContext(IdeMessengerContext); + const jetbrains = useMemo(() => { + return isJetBrains(); + }, []); + + const [missingVars, setMissingVars] = useState([]); + const refreshColors = () => { + if (jetbrains) { + // Jetbrains: get colors and check which ones are missing from theme + void ideMessenger + .request("jetbrains/getColors", undefined) + .then((result) => { + console.log(result); + if (result.status === "success") { + const missingColors = setDocumentStylesFromTheme(result.content); + setMissingVars(missingColors); + } + }); + } else { + // VS Code: find actual missing CSS variables + const notFound: string[] = []; + Object.entries(THEME_COLORS).forEach(([colorName, themeVals], idx) => { + let found = false; + themeVals.vars.forEach((cssVar) => { + const value = getComputedStyle( + document.documentElement, + ).getPropertyValue(cssVar); + if (!value) { + notFound.push(`cssVar (choice #${idx + 1} for color ${colorName}`); + } + }); + }); + setMissingVars(notFound); + } + }; + + useEffect(() => { + refreshColors(); + }, []); + + return ( +
+ navigate(ROUTES.HOME)} + > + โ† + Back to Chat + +

+ Theme Tester +

+
+
+

Normal text

+

Description text

+

Muted text

+
+ + + + +
+ Normal border +
+ +
+ Focus border +
+ + + +
+ Badge +
+ +
+ + Success +
+
+ + Warning +
+
+ + Error +
+ +
setListToggled(!listToggled)} + className={`cursor-pointer p-2 ${listToggled ? "bg-list-active text-list-active-foreground" : "bg-background text-foreground hover:bg-list-hover"}`} + > + List item (clickable) +
+
+ Editor +
+ + + + + + + + + +
+ even table row +
+ odd table row +
+
+ Link +
+
+ find match + current match +
+
+ Accent +
+
+
+

Manage Theme

+

Missing Theme Colors

+ {missingVars.length > 0 ? ( +
+ {missingVars.map((varName) => ( +
+ {varName} +
+ ))} +
+ ) : ( +
No missing variables
+ )} + + {jetbrains ? ( + + ) : null} +

All Theme Colors

+
+
+ Theme Color +
+
+ CSS Var +
+
+ Default +
+ {Object.entries(THEME_COLORS).map(([colorName, val]) => ( + + ))} +
+
+ ); +} +export default ThemePage; diff --git a/gui/src/styles/theme.test.ts b/gui/src/styles/theme.test.ts new file mode 100644 index 000000000..f65dd7583 --- /dev/null +++ b/gui/src/styles/theme.test.ts @@ -0,0 +1,24 @@ +import { getRecursiveVar } from "./theme"; + +test("getRecursiveVar returns single var with default for one variable", () => { + const vars = ["--test-var"]; + const defaultColor = "#ffffff"; + const result = getRecursiveVar(vars, defaultColor); + expect(result).toBe("var(--test-var, #ffffff)"); +}); + +test("getRecursiveVar returns nested vars in correct order for multiple variables", () => { + const vars = ["--first-var", "--second-var", "--third-var"]; + const defaultColor = "#000000"; + const result = getRecursiveVar(vars, defaultColor); + expect(result).toBe( + "var(--first-var, var(--second-var, var(--third-var, #000000)))", + ); +}); + +test("getRecursiveVar handles empty vars array", () => { + const vars: string[] = []; + const defaultColor = "#123456"; + const result = getRecursiveVar(vars, defaultColor); + expect(result).toBe("#123456"); +}); diff --git a/gui/src/styles/theme.ts b/gui/src/styles/theme.ts new file mode 100644 index 000000000..ad0ee0bd7 --- /dev/null +++ b/gui/src/styles/theme.ts @@ -0,0 +1,271 @@ +// All vscode variables https://gist.github.com/estruyf/ba49203e1a7d6868e9320a4ea480c27a +// Examples for vscode https://github.com/githubocto/tailwind-vscode/blob/main/index.js + +// The current default theme is dark with blue accents +export const THEME_COLORS = { + background: { + vars: [ + "--vscode-sideBar-background", + "--vscode-editor-background", + "--vscode-panel-background", + ], + default: "#1e1e1e", // dark gray + }, + foreground: { + vars: [ + "--vscode-sideBar-foreground", + "--vscode-editor-foreground", + "--vscode-panel-foreground", + ], + default: "#e6e6e6", // light gray + }, + "editor-background": { + vars: ["--vscode-editor-background"], + default: "#1e1e1e", // dark gray + }, + "editor-foreground": { + vars: ["--vscode-editor-foreground"], + default: "#e6e6e6", // light gray + }, + "primary-background": { + vars: ["--vscode-button-background"], + default: "#2c5aa0", // medium blue + }, + "primary-foreground": { + vars: ["--vscode-button-foreground"], + default: "#ffffff", // white + }, + "primary-hover": { + vars: ["--vscode-button-hoverBackground"], + default: "#3a6db3", // lighter blue + }, + "secondary-background": { + vars: ["--vscode-button-secondaryBackground"], + default: "#303030", // medium dark gray + }, + "secondary-foreground": { + vars: ["--vscode-button-secondaryForeground"], + default: "#e6e6e6", // light gray + }, + "secondary-hover": { + vars: ["--vscode-button-secondaryHoverBackground"], + default: "#3a3a3a", // medium gray + }, + border: { + vars: ["--vscode-sideBar-border", "--vscode-panel-border"], + default: "#2a2a2a", // dark gray border + }, + "border-focus": { + vars: ["--vscode-focusBorder"], + default: "#3a6db3", // lighter blue + }, + // Command styles are used for tip-tap editor + "command-background": { + vars: ["--vscode-commandCenter-background"], + default: "#252525", // dark gray + }, + "command-foreground": { + vars: ["--vscode-commandCenter-foreground"], + default: "#e6e6e6", // light gray + }, + "command-border": { + vars: ["--vscode-commandCenter-inactiveBorder"], + default: "#555555", // medium gray + }, + "command-border-focus": { + vars: ["--vscode-commandCenter-activeBorder"], + default: "#4d8bf0", // bright blue + }, + description: { + vars: ["--vscode-descriptionForeground"], + default: "#b3b3b3", // medium light gray + }, + "description-muted": { + vars: ["--vscode-list-deemphasizedForeground"], + default: "#8c8c8c", // medium gray + }, + "input-background": { + vars: ["--vscode-input-background"], + default: "#2d2d2d", // dark gray + }, + "input-foreground": { + vars: ["--vscode-input-foreground"], + default: "#e6e6e6", // light gray + }, + "input-border": { + vars: [ + "--vscode-input-border", + "--vscode-commandCenter-inactiveBorder", + "vscode-border", + ], + default: "#555555", // medium gray + }, + "input-placeholder": { + vars: ["--vscode-input-placeholderForeground"], + default: "#9e9e9e", // medium light gray + }, + "table-oddRow": { + vars: ["--vscode-tree-tableOddRowsBackground"], + default: "#2d2d2d", // dark gray + }, + "badge-background": { + vars: ["--vscode-badge-background"], + default: "#4d4d4d", // medium dark gray + }, + "badge-foreground": { + vars: ["--vscode-badge-foreground"], + default: "#ffffff", // white + }, + success: { + vars: [ + "--vscode-notebookStatusSuccessIcon-foreground", + "--vscode-testing-iconPassed", + "--vscode-gitDecoration-addedResourceForeground", + "--vscode-charts-green", + ], + default: "#4caf50", // green + }, + warning: { + vars: [ + "--vscode-editorWarning-foreground", + "--vscode-list-warningForeground", + ], + default: "#ffb74d", // amber/yellow + }, + error: { + vars: ["--vscode-editorError-foreground", "--vscode-list-errorForeground"], + default: "#f44336", // red + }, + link: { + vars: ["--vscode-textLink-foreground"], + default: "#5c9ce6", // medium blue + }, + accent: { + vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"], + default: "#4d8bf0", // bright blue + }, + "find-match": { + vars: ["--vscode-editor-findMatchBackground"], // Can't get "var(--vscode-editor-findMatchBackground, rgba(237, 18, 146, 0.5))" to work + default: "#264f7840", // translucent blue + }, + "find-match-selected": { + vars: ["--vscode-editor-findMatchHighlightBackground"], + default: "#ffb74d40", // translucent amber + }, + "list-hover": { + // --vscode-tab-hoverBackground + vars: ["--vscode-list-hoverBackground"], + default: "#383838", // medium dark gray + }, + "list-active": { + vars: ["--vscode-list-activeSelectionBackground"], + default: "#2c5aa050", // translucent medium blue + }, + "list-active-foreground": { + vars: ["--vscode-list-activeSelectionForeground"], + default: "#ffffff", // white + }, +}; + +// TODO: add fonts - GUI fonts in jetbrains differ from IDE: +// --vscode-editor-font-family; +// --vscode-font-family; +export const THEME_CSS_VARS = Object.values(THEME_COLORS) + .map((value) => value.vars) + .flat(); + +export const THEME_CSS_VAR_DEFAULTS = Object.entries(THEME_COLORS).reduce( + (acc, [_, value]) => { + value.vars.forEach((varName) => { + acc[varName] = value.default; + }); + return acc; + }, + {} as Record, +); + +export const THEME_DEFAULTS = Object.entries(THEME_COLORS).reduce( + (acc, [key, value]) => { + acc[key] = value.default; + return acc; + }, + {} as Record, +); + +// Generates recursive CSS variable fallback for a given color name +// e.g. var(--vscode-button-background, var(--vscode-button-foreground, #ffffff)) +export const getRecursiveVar = (vars: string[], defaultColor: string) => { + return [...vars].reverse().reduce((curr, varName) => { + return `var(${varName}, ${curr})`; + }, defaultColor); +}; + +export const varWithFallback = (colorName: keyof typeof THEME_COLORS) => { + const themeVals = THEME_COLORS[colorName]; + if (!themeVals) { + throw new Error(`Invalid theme color name ${colorName}`); + } + return getRecursiveVar(themeVals.vars, themeVals.default); +}; + +export const setDocumentStylesFromTheme = ( + theme: Record, +) => { + // Check for extraneous theme items + Object.entries(theme).forEach(([colorName, value]) => { + const themeVals = THEME_COLORS[colorName as keyof typeof THEME_COLORS]; + if (!themeVals) { + console.warn( + `Receieved theme color ${colorName} which is not used by the theme`, + ); + return; + } + }); + + // Write theme values to document + const missingColors: string[] = []; + Object.entries(THEME_COLORS).forEach(([colorName, settings]) => { + let colorVal = settings.default; + const newColor = theme[colorName]; + if (newColor) { + colorVal = newColor; + // Remove alpha channel from all hex colors (seems to cause bad colors) + if (newColor.startsWith("#") && newColor.length > 7) { + colorVal = colorVal.slice(0, 7); + } + } else { + missingColors.push(colorName); + // console.warn( + // `Missing theme color: ${colorName}. Falling back to default ${colorVal}`, + // ); + } + + localStorage.setItem(colorName, colorVal); + for (const cssVar of settings.vars) { + document.body.style.setProperty(cssVar, colorVal); + document.documentElement.style.setProperty(cssVar, colorVal); + } + }); + + return missingColors; +}; + +export const setDocumentStylesFromLocalStorage = (checkCache: boolean) => { + for (const [colorName, themeVals] of Object.entries(THEME_COLORS)) { + for (const cssVar of themeVals.vars) { + // Get cached values (for non-vscode IDEs) + if (checkCache) { + const cached = localStorage.getItem(colorName); + if (cached) { + document.body.style.setProperty(cssVar, cached); + } + } + } + } +}; + +export const clearThemeLocalCache = () => { + for (const colorName of Object.keys(THEME_COLORS)) { + localStorage.removeItem(colorName); + } +}; diff --git a/gui/src/styles/utils.ts b/gui/src/styles/utils.ts new file mode 100644 index 000000000..a46860ac4 --- /dev/null +++ b/gui/src/styles/utils.ts @@ -0,0 +1,45 @@ +export function parseHexColor(hexColor: string): { + r: number; + g: number; + b: number; +} { + if (hexColor.startsWith("#")) { + hexColor = hexColor.slice(1); + } + + if (hexColor.length > 6) { + hexColor = hexColor.slice(0, 6); + } + + const r = parseInt(hexColor.substring(0, 2), 16); + const g = parseInt(hexColor.substring(2, 4), 16); + const b = parseInt(hexColor.substring(4, 6), 16); + + return { r, g, b }; +} + +export function parseColorForHex(colorVar: string): string { + const value = getComputedStyle(document.documentElement).getPropertyValue( + colorVar, + ); + if (value.startsWith("#")) { + return value.slice(0, 7); + } + + // Parse rgb/rgba + const rgbValues = value + .slice(value.startsWith("rgba") ? 5 : 4, -1) + .split(",") + .map((x) => x.trim()) + .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) + .map((x) => parseInt(x, 10)); + + let hex = + "#" + + rgbValues + .map((x) => x.toString(16)) + .map((x) => (x.length === 1 ? "0" + x : x)) + .join(""); + + return hex; +} diff --git a/gui/src/util/navigation.ts b/gui/src/util/navigation.ts index 0f145b6cd..44ef9a9ee 100644 --- a/gui/src/util/navigation.ts +++ b/gui/src/util/navigation.ts @@ -2,5 +2,6 @@ export const ROUTES = { HOME: "/", CONFIG: "/config", + THEME: "/theme", // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`, }; diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index 941429d2e..ed91cee11 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -1,5 +1,6 @@ /** @type {import('tailwindcss').Config} */ const defaultTheme = require("tailwindcss/defaultTheme"); +const { varWithFallback, THEME_COLORS } = require("./src/styles/theme"); module.exports = { content: [ @@ -29,25 +30,75 @@ module.exports = { default: "5px", }, colors: { - lightgray: "#999998", - "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))", - "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))", - "vsc-foreground": "var(--vscode-editor-foreground, #fff)", - "vsc-editor-background": - "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))", - "vsc-input-border": "var(--vscode-input-border, #999998)", - "vsc-commandCenter-inactiveBorder": - "var(--vscode-commandCenter-inactiveBorder, #999998)", + background: varWithFallback("background"), + foreground: varWithFallback("foreground"), + editor: { + DEFAULT: varWithFallback("editor-background"), + foreground: varWithFallback("editor-foreground"), + }, + primary: { + DEFAULT: varWithFallback("primary-background"), + foreground: varWithFallback("primary-foreground"), + hover: varWithFallback("primary-hover"), + }, + secondary: { + DEFAULT: varWithFallback("secondary-background"), + foreground: varWithFallback("secondary-foreground"), + hover: varWithFallback("secondary-hover"), + }, + border: { + DEFAULT: varWithFallback("border"), + focus: varWithFallback("border-focus"), + }, + command: { + DEFAULT: varWithFallback("command-background"), + foreground: varWithFallback("command-foreground"), + border: { + DEFAULT: varWithFallback("command-border"), + focus: varWithFallback("command-border-focus"), + }, + }, + description: { + DEFAULT: varWithFallback("description"), + muted: varWithFallback("description-muted"), + }, + input: { + DEFAULT: varWithFallback("input-background"), + foreground: varWithFallback("input-foreground"), + border: varWithFallback("input-border"), + placeholder: varWithFallback("input-placeholder"), + }, + table: { + oddRow: varWithFallback("table-oddRow"), + }, + badge: { + DEFAULT: varWithFallback("badge-background"), + foreground: varWithFallback("badge-foreground"), + }, + success: varWithFallback("success"), + warning: varWithFallback("warning"), + error: varWithFallback("error"), + link: varWithFallback("link"), + accent: varWithFallback("accent"), + findMatch: { + DEFAULT: THEME_COLORS["find-match"].default, + selected: varWithFallback("find-match-selected"), + }, + list: { + hover: varWithFallback("list-hover"), + active: { + DEFAULT: varWithFallback("list-active"), + foreground: varWithFallback("list-active-foreground"), + }, + }, - // Starting to make things less vsc-specific - // TODO make it all non-IDE-specific naming - "find-match-selected": - "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))", - "table-odd-rows":"var(--vscode-tree-tableOddRowsBackground, #1bbe84)", - "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)", - "list-active-foreground": - "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))", - badge: "var(--vscode-badge-background, #1bbe84)", + // DEPRECATED, slowly remove usages of these ide-named or explicit colors + lightgray: "#999998", // use border, description, or description-muted instead - AVOID + "vsc-input-background": varWithFallback("input-background"), // use "input-background" instead + "vsc-background": varWithFallback("background"), // use "background" instead + "vsc-foreground": varWithFallback("editor-foreground"), // use "foreground" instead + "vsc-editor-background": varWithFallback("editor-background"), // use "editor" instead + "vsc-input-border": varWithFallback("input-border"), // use "input-border" instead }, }, }, 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. + {" "}