diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json index f4b9c4c78..f62954280 100644 --- a/.eslintrc.shared.json +++ b/.eslintrc.shared.json @@ -6,6 +6,7 @@ }, "plugins": ["@typescript-eslint", "import"], "rules": { + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/.github/ISSUE_TEMPLATE/docs_issue_report.yml b/.github/ISSUE_TEMPLATE/docs_issue_report.yml new file mode 100644 index 000000000..d04f976f4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/docs_issue_report.yml @@ -0,0 +1,83 @@ +--- +name: 📖 Documentation Issue Report +description: Report issues related to the documentation +labels: [area:docs] + +body: + - type: markdown + attributes: + value: | + ## Thank you for helping us improve our documentation! + We appreciate your feedback. Before submitting, please check if a similar issue already exists. + + ### Quick Contribution Tips: + - Click "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev) to contribute directly. + - For local development, see [CONTRIBUTING.md](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md#-updating--improving-documentation). + + - type: dropdown + id: doc-issue-category + attributes: + label: Issue Category + description: Select the category that best describes your issue. + options: + - Undocumented feature or missing documentation + - Incorrect or outdated information + - Suggestion for existing article + - Broken or dead link + - Documentation organization issue + - Other (please describe in the details section) + validations: + required: true + + - type: input + id: page-url + attributes: + label: Affected Documentation Page URL + description: Provide the URL of the specific page where you encountered the issue. + placeholder: "https://docs.continue.dev/path/to/page" + validations: + required: false + + - type: textarea + id: details + attributes: + label: Issue Description + description: Please describe the issue in detail. Include specifics about missing information, outdated content, or improvements needed. + placeholder: | + Examples: + - Missing section on [topic] + - Incorrect information about [subject] + - Outdated example code for [feature] + - Suggestion to improve [section] by [details] + validations: + required: true + + - type: textarea + id: expected-content + attributes: + label: Expected Content + description: If applicable, provide the content you believe should be added or updated. + placeholder: "Suggested details or changes for the documentation..." + + - type: textarea + id: additional-info + attributes: + label: Additional Information + description: Add any other relevant information that may help us understand and resolve your issue. + placeholder: "Additional context, screenshots, or related links..." + + - type: input + id: related-issue + attributes: + label: Related Issue + description: If this issue is related to an existing GitHub issue, provide the issue number. + placeholder: "#123" + + - type: checkboxes + id: terms + attributes: + label: Code of Conduct + description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/continuedev/continue/blob/main/CODE_OF_CONDUCT.md) + options: + - label: I agree to follow this project's Code of Conduct + required: true \ No newline at end of file diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index e5f44c03e..c41c57f72 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -96,7 +96,7 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [install-root, install-core] + needs: [ install-root, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -157,7 +157,7 @@ jobs: npx tsc --noEmit binary-checks: - needs: [install-root, install-core] + needs: [ install-root, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -193,7 +193,7 @@ jobs: npx tsc --noEmit install-vscode: - needs: [install-root, install-core] + needs: [ install-root, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -277,7 +277,7 @@ jobs: vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [install-root, install-vscode] + needs: [ install-root, install-vscode ] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: @@ -306,7 +306,7 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [ install-vscode, install-core ] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -338,7 +338,7 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [ install-vscode, install-core ] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -445,7 +445,7 @@ jobs: path: extensions/vscode/e2e/storage/screenshots gui-tests: - needs: [install-gui, install-core] + needs: [ install-gui, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -476,7 +476,7 @@ jobs: npm test jetbrains-tests: - needs: [install-root, install-core] + needs: [ install-root, core-checks ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -573,3 +573,5 @@ jobs: name: jb-failure-report path: | ${{ github.workspace }}/extensions/intellij/build/reports + + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eddf7b45b..ca26d38fe 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -188,7 +188,7 @@ After you've written your context provider, make sure to complete the following: ### Adding an LLM Provider -Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, Novita AI, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps: +Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps: 1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example. @@ -209,7 +209,7 @@ While any model that works with a supported provider can be used with Continue, 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 [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed) - [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this. -- 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), [Novita AI](./core/llm/llms/Novita.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Novita AI](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), [Replicate](https://replicate.com/collections/streaming-language-models). +- 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), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models). - [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates. ### Adding Pre-indexed Documentation diff --git a/core/commands/slash/http.ts b/core/commands/slash/http.ts index 2f5e2a7af..7a662561c 100644 --- a/core/commands/slash/http.ts +++ b/core/commands/slash/http.ts @@ -1,5 +1,6 @@ import { SlashCommand } from "../../index.js"; import { removeQuotesAndEscapes } from "../../util/index.js"; +import { streamResponse } from "../../llm/stream.js"; const HttpSlashCommand: SlashCommand = { name: "http", @@ -23,14 +24,8 @@ const HttpSlashCommand: SlashCommand = { if (response.body === null) { throw new Error("Response body is null"); } - const reader = response.body.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - const decoded = new TextDecoder("utf-8").decode(value); - yield decoded; + for await (const chunk of streamResponse(response)) { + yield chunk; } }, }; diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index 7395e82c8..f239e3ee1 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -73,7 +73,15 @@ class MCPContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { - return (this.options as MCPContextProviderOptions).submenuItems; + return (this.options as MCPContextProviderOptions).submenuItems.map( + (item, index) => ({ + ...item, + id: JSON.stringify({ + mcpId: String(index), + uri: item.id, + }), + }), + ); } } diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 99d5c9a01..1e3a0ec4e 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -172,7 +172,7 @@ export async function deterministicApplyLazyEdit( oldText.slice(endIndex); } else { console.warn("No matching node found for lazy block"); - return []; + return undefined; } } } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 756b3db54..c4b999521 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -61,6 +61,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = ]; // Message types to pass through from core to webview +// Note: If updating these values, make a corresponding update in +// extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index 2312123a0..7d8c98944 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -5,6 +5,10 @@ keywords: [model, autocomplete] sidebar_position: 2 --- +:::info +This page recommends models and providers for Autocomplete. Read more about how to set up your `config.json` [here](../reference.md). +::: + ## Best overall experience For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context: @@ -26,7 +30,7 @@ The API keys for Codestral and the general Mistral APIs are different. If you ar ## Local, offline / self-hosted experience -For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users: +For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)). ```json title="config.json"" { @@ -45,7 +49,20 @@ Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality su For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. ::: +### Using a remote instance +When using a remote instance you need to set the `"apiBase"` value in the configuration: + +```json title="config.json"" +{ + "tabAutocompleteModel": { + "title": "Qwen2.5-Coder 1.5B", + "model": "qwen2.5-coder:1.5b-base", + "provider": "ollama" + "apiBase": "http://:11434" + } +} +``` ## Other experiences -There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). +There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.md) diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index 4ec425e81..e4c35ddc5 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing cmd/ctrl + L< ## Active file -You can include the currently open file as context by pressing cmd + opt + enter (Mac) or alt + enter (Windows) when you send your request at Chat window(Prompt can't be empty). +You can include the currently open file as context by pressing opt + enter (Mac) or alt + enter (Windows) when you send your request at Chat window(Prompt can't be empty). ## Specific file diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 832f2f837..eb7dc5430 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -33,7 +33,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz ### Llama 3.1 405B from Meta -If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Novita AI](../customize/model-providers/more/novita.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)). +If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)). @@ -48,18 +48,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your ] ``` - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "novita", - "model": "meta-llama/llama-3.1-405b-instruct", - "apiKey": "[NOVITA_API_KEY]" - } - ] - ``` - ```json title="config.json" "models": [ @@ -94,18 +82,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your ] ``` - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "nebius", - "model": "llama3.1-405b", - "apiKey": "[NEBIUS_API_KEY]" - } - ] - ``` - ### GPT-4o from OpenAI diff --git a/docs/docs/customize/model-providers/more/vllm.md b/docs/docs/customize/model-providers/more/vllm.md index 72d79c645..d54baeb88 100644 --- a/docs/docs/customize/model-providers/more/vllm.md +++ b/docs/docs/customize/model-providers/more/vllm.md @@ -1,22 +1,59 @@ # vLLM -Run the OpenAI-compatible server by vLLM using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/models/engine_args.html). +vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html). ```shell -vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024 +vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct ``` +## Chat model -The continue implementation uses [OpenAI](../top-level/openai.md) under the hood and automatically selects the available model. You only need to set the `apiBase` like this: +We recommend configuring **Llama3.1 8B** as your chat model. ```json title="config.json" { "models": [ { - "title": "My vLLM OpenAI-compatible server", - "apiBase": "http://localhost:8000/v1" + "title": "Llama3.1 8B Instruct", + "provider": "vllm", + "model": "meta-llama/Meta-Llama-3.1-8B-Instruct" + "apiBase": "http:///v1" } ] } ``` -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) +## Autocomplete model + +We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Qwen2.5-Coder 1.5B", + "provider": "vllm", + "model": "Qwen/Qwen2.5-Coder-1.5B" + "apiBase": "http:///v1" + } +} +``` + +## Embeddings model + +We recommend configuring **Nomic Embed Text** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "vllm", + "model": "nomic-ai/nomic-embed-text-v1" + "apiBase": "http:///v1" + } +} +``` + +## Reranking model + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + + +The continue implementation uses [OpenAI](../top-level/openai.md) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index e1f3e53e8..d2a4749c0 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -53,3 +53,20 @@ We recommend configuring **Nomic Embed Text** as your embeddings model. Ollama currently does not offer any reranking models. [Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Using a remote instance + +To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama3.1 8B", + "provider": "ollama", + "model": "llama3.1:8b" + "apiBase": "http://:11434" + } + ] +} +``` diff --git a/docs/docs/customize/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md index 38e90bee9..e2ac72986 100644 --- a/docs/docs/customize/tutorials/llama3.1.md +++ b/docs/docs/customize/tutorials/llama3.1.md @@ -71,28 +71,6 @@ Together AI provides fast and reliable inference of open-source models. You'll b } ``` - -## Novita AI - -[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today! - -1. Create an account [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) -2. Copy your API key that appears on the welcome screen -3. Update your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "novita", - "model": "meta-llama/llama-3.1-405b-instruct", - "apiKey": "" - } - ] -} -``` - ## Replicate Replicate makes it easy to host and run open-source AI with an API. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx index 4ef37a41e..cbbef8761 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx @@ -33,7 +33,7 @@ import TabItem from "@theme/TabItem"; ### 来自 Meta 的 Llama 3.1 405B -如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 、[Novita AI](../customize/model-providers/more/novita.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。 +如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md index dc285627a..e02ba6741 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md @@ -71,27 +71,6 @@ Together AI 提供开源模型的快速和可信任的推理。你可以以良 } ``` -## Novita AI - -[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以以良好的速度运行 405b 模型。 - -1. 创建账号 [在这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) -2. 复制[Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)中的你的 API key -3. 更新你的 Continue 配置文件,像这样: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "novita", - "model": "meta-llama/llama-3.1-405b-instruct", - "apiKey": "" - } - ] -} -``` - ## Replicate Replicate 让使用 API 托管和运行开源 AI 变得简单。 diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index ac787e936..2be56cfd9 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -3,4 +3,6 @@ src/main/resources/webview src/main/resources/bin src/main/resources/config_schema.json src/main/resources/continue_rc_schema.json -video \ No newline at end of file +video +src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/* +!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json \ No newline at end of file diff --git a/extensions/intellij/.run/Run IDE for UI Tests.run.xml b/extensions/intellij/.run/Run IDE for UI Tests.run.xml deleted file mode 100644 index 5f7eb46c8..000000000 --- a/extensions/intellij/.run/Run IDE for UI Tests.run.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/extensions/intellij/.run/Run Test IDE.run.xml b/extensions/intellij/.run/Run Test IDE.run.xml new file mode 100644 index 000000000..80a2a251f --- /dev/null +++ b/extensions/intellij/.run/Run Test IDE.run.xml @@ -0,0 +1,27 @@ + + + + + + + true + true + false + false + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Tests.run.xml b/extensions/intellij/.run/Run Tests.run.xml new file mode 100644 index 000000000..bdff34d6d --- /dev/null +++ b/extensions/intellij/.run/Run Tests.run.xml @@ -0,0 +1,24 @@ + + + + + + + true + true + false + false + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run e2e tests.run.xml b/extensions/intellij/.run/Run e2e tests.run.xml new file mode 100644 index 000000000..2280aece0 --- /dev/null +++ b/extensions/intellij/.run/Run e2e tests.run.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index d37aaa2c4..836eaa7b6 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -101,7 +101,9 @@ toolbar. _Run | Debugging Actions | Reload Changed Classes`_ - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension - `gui`: Changes will be reloaded automatically -- `core`: Run `npm run build` from the `binary` directory (requires restarting the `Start Core Dev Server` task) +- `core`: Run `npm run build -- --os [darwin | linux | win32]` from the `binary` directory (requires + restarting the + `Start Core Dev Server` task) ### Setting breakpoints diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 25d2fb361..ee7dce8be 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -130,7 +130,10 @@ tasks { // Configure UI tests plugin // Read more: https://github.com/JetBrains/intellij-ui-test-robot runIdeForUiTests { - environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue") + environment( + "CONTINUE_GLOBAL_DIR", + "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue" + ) systemProperty("robot-server.port", "8082") systemProperty("ide.mac.message.dialogs.as.sheets", "false") systemProperty("jb.privacy.policy.text", "") @@ -141,6 +144,7 @@ tasks { systemProperty("idea.trust.all.projects", "true") systemProperty("ide.show.tips.on.startup.default.value", "false") systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000") + systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true") // This is to ensure we load the GUI with OSR enabled. We have logic that // renders with OSR disabled below a particular IDE version. @@ -180,6 +184,5 @@ tasks { test { useJUnitPlatform() - environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index facc89424..72819421a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -10,7 +10,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.SettingsListener -import com.intellij.openapi.Disposable +import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo @@ -162,7 +162,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { override fun after(events: List) { // Collect all relevant URIs for deletions val deletedURIs = events.filterIsInstance() - .map { event -> event.file.url } + .mapNotNull { event -> event.file.toUriOrNull() } // Send "files/deleted" message if there are any deletions if (deletedURIs.isNotEmpty()) { @@ -172,7 +172,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { // Collect all relevant URIs for content changes val changedURIs = events.filterIsInstance() - .map { event -> event.file.url } + .mapNotNull { event -> event.file.toUriOrNull() } // Send "files/changed" message if there are any content changes if (changedURIs.isNotEmpty()) { @@ -220,7 +220,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { // Reload the WebView continuePluginService?.let { pluginService -> val allModulePaths = ModuleManager.getInstance(project).modules - .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.url } } + .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } } val topLevelModulePaths = allModulePaths .filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt index 45fb3b597..03b91e87c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt @@ -22,4 +22,4 @@ class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() { && autocompleteService.pendingCompletion?.text != null return enabled } -}) {} \ No newline at end of file +}) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index d21c04f56..b2650b8f4 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.autocomplete import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.github.continuedev.continueintellijextension.utils.uuid import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.application.* @@ -10,8 +11,10 @@ import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.InlayProperties +import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project +import com.intellij.openapi.util.TextRange import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement @@ -32,9 +35,24 @@ fun PsiElement.isInjectedText(): Boolean { return false } +fun Editor.addInlayElement( + lines: List, + offset: Int, + properties: InlayProperties +) { + if (this is EditorImpl) { + if (lines[0].isNotEmpty()) { + inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0]))) + } + if (lines.size > 1) { + inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1))) + } + } +} + @Service(Service.Level.PROJECT) class AutocompleteService(private val project: Project) { - var pendingCompletion: PendingCompletion? = null; + var pendingCompletion: PendingCompletion? = null private val autocompleteLookupListener = project.service() private var widget: AutocompleteSpinnerWidget? = null @@ -66,12 +84,16 @@ class AutocompleteService(private val project: Project) { // Request a completion from the core val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) + + val uri = virtualFile?.toUriOrNull() ?: return + + val line = editor.caretModel.primaryCaret.logicalPosition.line val column = editor.caretModel.primaryCaret.logicalPosition.column val input = mapOf( "completionId" to completionId, - "filepath" to virtualFile?.url, + "filepath" to uri, "pos" to mapOf( - "line" to editor.caretModel.primaryCaret.logicalPosition.line, + "line" to line, "character" to column ), "clipboardText" to "", @@ -79,10 +101,6 @@ class AutocompleteService(private val project: Project) { "recentlyVisitedRanges" to emptyList(), ) - val lineStart = editor.document.getLineStartOffset(editor.caretModel.primaryCaret.logicalPosition.line) - val lineEnd = editor.document.getLineEndOffset(editor.caretModel.primaryCaret.logicalPosition.line) - val lineLength = lineEnd - lineStart - project.service().coreMessenger?.request( "autocomplete/complete", input, @@ -95,7 +113,7 @@ class AutocompleteService(private val project: Project) { val completion = completions[0].toString() val finalTextToInsert = deduplicateCompletion(editor, offset, completion) - if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) { + if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) { renderCompletion(editor, offset, finalTextToInsert) pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) } @@ -104,13 +122,19 @@ class AutocompleteService(private val project: Project) { ) } - private fun shouldRenderCompletion(completion: String, column: Int, lineLength: Int, editor: Editor): Boolean { - if (completion.isEmpty()) { + private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean { + if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) { return false } + if (completion.lines().size == 1) { + return true + } + + val endOffset = editor.document.getLineEndOffset(line) + // Do not render if completion is multi-line and caret is in middle of line - return !(completion.lines().size > 1 && column < lineLength) + return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank() } private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { @@ -124,9 +148,9 @@ class AutocompleteService(private val project: Project) { val N = 10 var textAfterCursor = if (caretOffset + N <= document.textLength) { - document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N)) + document.getText(TextRange(caretOffset, caretOffset + N)) } else { - document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength)) + document.getText(TextRange(caretOffset, document.textLength)) } // Avoid truncating the completion text when the text after the cursor is blank @@ -169,19 +193,9 @@ class AutocompleteService(private val project: Project) { properties.relatesToPrecedingText(true) properties.disableSoftWrapping(true) - if (completion.lines().size > 1) { - editor.inlayModel.addBlockElement( - offset, - properties, - ContinueMultilineCustomElementRenderer(editor, completion) - ) - } else { - editor.inlayModel.addInlineElement( - offset, - properties, - ContinueCustomElementRenderer(editor, completion) - ) - } + val lines = completion.lines() + pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) + editor.addInlayElement(lines, offset, properties) // val attributes = TextAttributes().apply { // backgroundColor = JBColor.GREEN @@ -209,7 +223,7 @@ class AutocompleteService(private val project: Project) { ({}) ) invokeLater { - clearCompletions(editor) + clearCompletions(editor, completion) } } @@ -272,44 +286,40 @@ class AutocompleteService(private val project: Project) { project.service().coreMessenger?.request("autocomplete/cancel", null, null, ({})) } - fun clearCompletions(editor: Editor) { + fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) { if (isInjectedFile(editor)) return - if (pendingCompletion != null) { - cancelCompletion(pendingCompletion!!) - pendingCompletion = null - } - editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueCustomElementRenderer) { - it.dispose() - } - } - editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueMultilineCustomElementRenderer) { - it.dispose() - } + if (completion != null) { + cancelCompletion(completion) + if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null } + disposeInlayRenderer(editor) } private fun isInjectedFile(editor: Editor): Boolean { - val psiFile = runReadAction { PsiDocumentManager.getInstance(project).getPsiFile(editor.document) } - if (psiFile == null) { - return false - } - val response = runReadAction { psiFile.isInjectedText() } - return response + return ApplicationManager.getApplication().executeOnPooledThread { + ApplicationManager.getApplication().runReadAction { + val psiFile = + PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return@runReadAction false + return@runReadAction psiFile.isInjectedText() + } + }.get() } fun hideCompletions(editor: Editor) { if (isInjectedFile(editor)) return + disposeInlayRenderer(editor) + } + + private fun disposeInlayRenderer(editor: Editor) { editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueCustomElementRenderer) { + if (it.renderer is ContinueInlayRenderer) { it.dispose() } } editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueMultilineCustomElementRenderer) { + if (it.renderer is ContinueInlayRenderer) { it.dispose() } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt deleted file mode 100644 index bfaeedb2d..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorCustomElementRenderer -import com.intellij.openapi.editor.Inlay -import com.intellij.openapi.editor.colors.EditorFontType -import com.intellij.openapi.editor.impl.EditorImpl -import com.intellij.openapi.editor.impl.FontInfo -import com.intellij.openapi.editor.markup.TextAttributes -import com.intellij.ui.JBColor -import com.intellij.util.ui.UIUtil -import java.awt.Font -import java.awt.Graphics -import java.awt.Rectangle -import kotlin.math.ceil - -class ContinueCustomElementRenderer( - val editor: Editor, - val text: String, -) : EditorCustomElementRenderer { - override fun calcWidthInPixels(inlay: Inlay<*>): Int { - val width = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(this.text) - return width - } - - private fun font(editor: Editor): Font { - val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN) - return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize) - } - - private fun offsetY(editor: Editor): Int { - val metrics = - FontInfo.getFontMetrics(font(editor), FontInfo.getFontRenderContext(editor.contentComponent)) - val fontHeight = - font(editor).createGlyphVector(metrics.fontRenderContext, text).visualBounds.height - val height = (editor.lineHeight + fontHeight) / 2 - return ceil(height).toInt() - } - - override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) { - g.color = JBColor.GRAY - g.font = font(inlay.editor) - g.drawString(this.text, targetRegion.x, targetRegion.y + inlay.editor.ascent) - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt new file mode 100644 index 000000000..bcf37fa20 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt @@ -0,0 +1,58 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.EditorCustomElementRenderer +import com.intellij.openapi.editor.Inlay +import com.intellij.openapi.editor.colors.EditorFontType +import com.intellij.openapi.editor.impl.EditorImpl +import com.intellij.openapi.editor.markup.TextAttributes +import com.intellij.ui.JBColor +import com.intellij.util.ui.UIUtil +import java.awt.Font +import java.awt.Graphics +import java.awt.Rectangle + +/** + * The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor. + * It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays. + * + * This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the + * necessary width and height based on the content and rendering each line with appropriate font and color. + * + * @author lk + */ +class ContinueInlayRenderer(val lines: List) : EditorCustomElementRenderer { + override fun calcWidthInPixels(inlay: Inlay<*>): Int { + var maxLen = 0; + for (line in lines) { + val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line) + if (len > maxLen) { + maxLen = len + } + } + return maxLen + } + + override fun calcHeightInPixels(inlay: Inlay<*>): Int { + return (inlay.editor as EditorImpl).lineHeight * lines.size + } + + private fun font(editor: Editor): Font { + val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN) + return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n")) + .deriveFont(editor.colorsScheme.editorFontSize) + } + + override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) { + val editor = inlay.editor + g.color = JBColor.GRAY + g.font = font(editor) + var additionalYOffset = 0 + val ascent = editor.ascent + val lineHeight = editor.lineHeight + for (line in lines) { + g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset) + additionalYOffset += lineHeight + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt deleted file mode 100644 index a24b2453a..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorCustomElementRenderer -import com.intellij.openapi.editor.Inlay -import com.intellij.openapi.editor.colors.EditorFontType -import com.intellij.openapi.editor.impl.EditorImpl -import com.intellij.openapi.editor.impl.FontInfo -import com.intellij.openapi.editor.markup.TextAttributes -import com.intellij.ui.JBColor -import com.intellij.util.ui.UIUtil -import java.awt.Font -import java.awt.Graphics -import java.awt.Rectangle -import kotlin.math.ceil -import kotlin.math.max - -class ContinueMultilineCustomElementRenderer( - val editor: Editor, - val text: String, -) : EditorCustomElementRenderer { - override fun calcWidthInPixels(inlay: Inlay<*>): Int { - val lines = text.lines() - var maxLen = 0; - for (line in lines) { - val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line) - if (len > maxLen) { - maxLen = len - } - } - return maxLen - } - - override fun calcHeightInPixels(inlay: Inlay<*>): Int { - return (inlay.editor as EditorImpl).lineHeight * text.lines().size - } - - protected val font: Font - get() { - val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN) - return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize) - } - - private fun offsetY(): Int { - val metrics = - FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent)) - val fontHeight = - font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.height - val height = (editor.lineHeight + fontHeight) / 2 - return ceil(height).toInt() - } - - private fun offsetX(): Int { - val currentLine = editor.caretModel.primaryCaret.logicalPosition.line - val currentColumn = editor.caretModel.primaryCaret.logicalPosition.column - val metrics = - FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent)) - val fontWidth = - font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.width - val widthBeforeCaret = (editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth( - text.substring(0, minOf(currentColumn, text.length)) - ) - return max(0, widthBeforeCaret - (editor as EditorImpl).scrollingModel.horizontalScrollOffset) - } - - override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) { - g.color = JBColor.GRAY - g.font = font - var additionalYOffset = -editor.lineHeight; - var isFirstLine = true - for (line in text.lines()) { - g.drawString( - line, - if (isFirstLine) targetRegion.x + offsetX() else targetRegion.x, - targetRegion.y + inlay.editor.ascent + additionalYOffset - ) - additionalYOffset += editor.lineHeight - isFirstLine = false - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index b309cbbc6..585dd716f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -50,13 +50,78 @@ class MessageTypes { "showToast", ) + // Note: If updating these values, make a corresponding update in + // core/protocol/passThrough.ts val PASS_THROUGH_TO_WEBVIEW = listOf( "configUpdate", "getDefaultModelTitle", - "indexProgress", + "indexProgress", // Codebase + "indexing/statusUpdate", // Docs, etc. + "addContextItem", "refreshSubmenuItems", + "isContinueInputFocused", "didChangeAvailableProfiles", - "addContextItem" + "setTTSActive", + "getWebviewHistoryLength", + "getCurrentSessionId", + "signInToControlPlane", + "openDialogMessage", + "docs/suggestions", + ) + + // Note: If updating these values, make a corresponding update in + // core/protocol/passThrough.ts + val PASS_THROUGH_TO_CORE = listOf( + "abort", + "history/list", + "history/delete", + "history/load", + "history/save", + "devdata/log", + "config/addModel", + "config/addContextProvider", + "config/newPromptFile", + "config/ideSettingsUpdate", + "config/getSerializedProfileInfo", + "config/deleteModel", + "config/listProfiles", + "config/openProfile", + "context/getContextItems", + "context/getSymbolsForFiles", + "context/loadSubmenuItems", + "context/addDocs", + "context/removeDocs", + "context/indexDocs", + "autocomplete/complete", + "autocomplete/cancel", + "autocomplete/accept", + "command/run", + "tts/kill", + "llm/complete", + "llm/streamComplete", + "llm/streamChat", + "llm/listModels", + "streamDiffLines", + "chatDescriber/describe", + "stats/getTokensPerDay", + "stats/getTokensPerModel", + // Codebase + "index/setPaused", + "index/forceReIndex", + "index/forceReIndexFiles", + "index/indexingProgressBarInitialized", + // Docs, etc. + "indexing/reindex", + "indexing/abort", + "indexing/setPaused", + "docs/getSuggestedDocs", + "docs/initStatuses", + // + "completeOnboarding", + "addAutocompleteModel", + "profiles/switch", + "didChangeSelectedProfile", + "tools/call", ) } } \ 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 5921300cf..afc714267 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 @@ -549,12 +549,14 @@ class IdeProtocolClient( val startChar = startOffset - document.getLineStartOffset(startLine) val endChar = endOffset - document.getLineStartOffset(endLine) - return@runReadAction RangeInFileWithContents( - virtualFile.url, Range( - Position(startLine, startChar), - Position(endLine, endChar) - ), selectedText - ) + return@runReadAction virtualFile.toUriOrNull()?.let { + RangeInFileWithContents( + it, Range( + Position(startLine, startChar), + Position(endLine, endChar) + ), selectedText + ) + } } return result diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 84ff3fc10..d30a5d5fe 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID import com.github.continuedev.continueintellijextension.utils.getOS +import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil @@ -180,7 +181,7 @@ class IntelliJIDE( for (workspaceDir in workspaceDirs) { val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir) if (dir != null) { - val contents = dir.children.map { it.url } + val contents = dir.children.mapNotNull { it.toUriOrNull() } // Find any .continuerc.json files for (file in contents) { @@ -261,7 +262,7 @@ class IntelliJIDE( content } else { val file = File(URI(filepath)) - if (!file.exists()) return "" + if (!file.exists() || file.isDirectory) return "" withContext(Dispatchers.IO) { FileInputStream(file).use { fis -> val sizeToRead = minOf(100000, file.length()).toInt() @@ -269,6 +270,8 @@ class IntelliJIDE( val bytesRead = fis.read(buffer, 0, sizeToRead) if (bytesRead <= 0) return@use "" String(buffer, 0, bytesRead, Charset.forName("UTF-8")) + // `\r` takes up unnecessary tokens + .lineSequence().joinToString("\n") } } } @@ -307,16 +310,16 @@ class IntelliJIDE( override suspend fun getOpenFiles(): List { val fileEditorManager = FileEditorManager.getInstance(project) - return fileEditorManager.openFiles.map { it.url }.toList() + return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList() } override suspend fun getCurrentFile(): Map? { val fileEditorManager = FileEditorManager.getInstance(project) val editor = fileEditorManager.selectedTextEditor val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } - return virtualFile?.let { + return virtualFile?.toUriOrNull()?.let { mapOf( - "path" to it.url, + "path" to it, "contents" to editor.document.text, "isUntitled" to false ) @@ -382,7 +385,7 @@ class IntelliJIDE( problems.add( Problem( - filepath = psiFile.virtualFile?.url ?: "", + filepath = psiFile.virtualFile?.toUriOrNull() ?: "", range = Range( start = Position( line = startLineNumber, @@ -513,7 +516,7 @@ class IntelliJIDE( override suspend fun listDir(dir: String): List> { val files = File(URI(dir)).listFiles()?.map { - listOf(it.name, if (it.isDirectory) FileType.DIRECTORY else FileType.FILE) + listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value) } ?: emptyList() return files @@ -561,6 +564,6 @@ class IntelliJIDE( return dirs } - return listOfNotNull(project.guessProjectDir()?.url).toTypedArray() + return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 5523bdeff..b43cf62c9 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable import com.github.continuedev.continueintellijextension.constants.MessageTypes +import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService @@ -18,58 +19,6 @@ import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter class ContinueBrowser(val project: Project, url: String) { - private val PASS_THROUGH_TO_CORE = listOf( - "abort", - "history/list", - "history/delete", - "history/load", - "history/save", - "devdata/log", - "config/addModel", - "config/addContextProvider", - "config/newPromptFile", - "config/ideSettingsUpdate", - "config/getSerializedProfileInfo", - "config/deleteModel", - "config/listProfiles", - "config/openProfile", - "context/getContextItems", - "context/getSymbolsForFiles", - "context/loadSubmenuItems", - "context/addDocs", - "context/removeDocs", - "context/indexDocs", - "autocomplete/complete", - "autocomplete/cancel", - "autocomplete/accept", - "command/run", - "tts/kill", - "llm/complete", - "llm/streamComplete", - "llm/streamChat", - "llm/listModels", - "streamDiffLines", - "chatDescriber/describe", - "stats/getTokensPerDay", - "stats/getTokensPerModel", - // Codebase - "index/setPaused", - "index/forceReIndex", - "index/indexingProgressBarInitialized", - // Docs, etc. - "indexing/reindex", - "indexing/abort", - "indexing/setPaused", - "docs/getSuggestedDocs", - "docs/initStatuses", - // - "completeOnboarding", - "addAutocompleteModel", - "profiles/switch", - "didChangeSelectedProfile", - "tools/call", - ) - private fun registerAppSchemeHandler() { CefApp.getInstance().registerSchemeHandlerFactory( "http", @@ -82,14 +31,9 @@ class ContinueBrowser(val project: Project, url: String) { init { val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build() - - browser.jbCefClient.setProperty( - JBCefClient.Properties.JS_QUERY_POOL_SIZE, - JS_QUERY_POOL_SIZE - ) - registerAppSchemeHandler() browser.loadURL(url); Disposer.register(ContinuePluginDisposable.getInstance(project), browser) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt index fe29b6235..7e90ba99e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.utils +import com.intellij.openapi.vfs.VirtualFile import java.net.NetworkInterface import java.util.* import java.awt.event.KeyEvent.* @@ -77,4 +78,6 @@ fun getMachineUniqueID(): String { fun uuid(): String { return UUID.randomUUID().toString() -} \ No newline at end of file +} + +fun VirtualFile.toUriOrNull(): String? = fileSystem.getNioPath(this)?.toUri()?.toString()?.removeSuffix("/") \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt new file mode 100644 index 000000000..fdb271639 --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt @@ -0,0 +1,73 @@ +package com.github.continuedev.continueintellijextension.e2e + +import com.automation.remarks.junit5.Video +import com.github.continuedev.continueintellijextension.fixtures.dialog +import com.github.continuedev.continueintellijextension.fixtures.idea +import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame +import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension +import com.github.continuedev.continueintellijextension.utils.StepsLogger +import com.intellij.remoterobot.RemoteRobot +import com.intellij.remoterobot.fixtures.ComponentFixture +import com.intellij.remoterobot.search.locators.byXpath +import com.intellij.remoterobot.steps.CommonSteps +import com.intellij.remoterobot.utils.keyboard +import com.intellij.remoterobot.utils.waitFor +import com.intellij.remoterobot.utils.waitForIgnoringError +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import java.time.Duration.ofMinutes +import java.time.Duration.ofSeconds + +@ExtendWith(RemoteRobotExtension::class) +class Autocomplete { + init { + StepsLogger.init() + } + + @BeforeEach + fun waitForIde(remoteRobot: RemoteRobot) { + waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } + } + + @AfterEach + fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() + + // @Test + @Video + fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { + welcomeFrame { + createNewProjectLink.click() + dialog("New Project") { + findText("Java").click() + checkBox("Add sample code").select() + button("Create").click() + } + } + + // Wait for the default "Main.java" tab to load + // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. + waitFor(ofSeconds(20)) { + findAll( + byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']") + ).isNotEmpty() + } + + idea { + with(textEditor()) { + val userMsg = "TEST_USER_MESSAGE_0" + editor.insertTextAtLine(0, 0, userMsg) + editor.clickOnOffset(userMsg.length) + + keyboard { + enterText(" ") + } + + waitFor(ofSeconds(10)) { + editor.hasText("TEST_LLM_RESPONSE_0") + } + } + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt new file mode 100644 index 000000000..5672debba --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt @@ -0,0 +1,96 @@ +/** + * Currently we can't test any actions in the GUI that involve clicks. + * See this open issue for details: https://github.com/JetBrains/intellij-ui-test-robot/issues/491 + */ +package com.github.continuedev.continueintellijextension.e2e + +import com.automation.remarks.junit5.Video +import com.github.continuedev.continueintellijextension.fixtures.* +import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension +import com.github.continuedev.continueintellijextension.utils.StepsLogger +import com.github.continuedev.continueintellijextension.utils.getMetaKey +import com.intellij.remoterobot.RemoteRobot +import com.intellij.remoterobot.fixtures.ComponentFixture +import com.intellij.remoterobot.search.locators.byXpath +import com.intellij.remoterobot.steps.CommonSteps +import com.intellij.remoterobot.stepsProcessing.step +import com.intellij.remoterobot.utils.keyboard +import com.intellij.remoterobot.utils.waitFor +import com.intellij.remoterobot.utils.waitForIgnoringError +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import java.awt.event.KeyEvent.* +import java.time.Duration.ofMinutes +import java.time.Duration.ofSeconds + +@ExtendWith(RemoteRobotExtension::class) +class GUI { + init { + StepsLogger.init() + } + + @BeforeEach + fun waitForIde(remoteRobot: RemoteRobot) { + waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } + } + + @AfterEach + fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() + + // @Test + @Video + fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { + welcomeFrame { + createNewProjectLink.click() + dialog("New Project") { + findText("Java").click() + checkBox("Add sample code").select() + button("Create").click() + } + } + + // Wait for the default "Main.java" tab to load + // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. + // If we don't wait for this, clicking on the GUI may fail because a popup displays + // while the `continue_tutorial.java` is loading. + waitFor(ofSeconds(20)) { + findAll( + byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']") + ).isNotEmpty() + } + + idea { + step("Manually open the webview") { + // Manually open the webview + find(byXpath("//div[@text='Continue']"), ofSeconds((10))).click() + + waitFor(ofSeconds(10)) { + browser().isShowing + } + + // Arbitrary timeout due to a bug where the webview will refresh + // and clear the editor state on first load + Thread.sleep(5000) + } + + step("Verify we can highlight code and add to webview") { + val textToInsert = "Hello world!" + + with(textEditor()) { + editor.insertTextAtLine(0, 0, textToInsert) + editor.selectText(textToInsert) + + keyboard { + hotKey(getMetaKey(), VK_J) + } + } + + waitFor(ofSeconds(10)) { + browser().findElementByContainsText(textToInsert).html.isNotEmpty() + } + } + } + } +} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt new file mode 100644 index 000000000..3f667559d --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt @@ -0,0 +1,85 @@ +package com.github.continuedev.continueintellijextension.e2e + +import com.automation.remarks.junit5.Video +import com.github.continuedev.continueintellijextension.fixtures.dialog +import com.github.continuedev.continueintellijextension.fixtures.idea +import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame +import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension +import com.github.continuedev.continueintellijextension.utils.StepsLogger +import com.intellij.remoterobot.RemoteRobot +import com.intellij.remoterobot.fixtures.ComponentFixture +import com.intellij.remoterobot.search.locators.byXpath +import com.intellij.remoterobot.steps.CommonSteps +import com.intellij.remoterobot.stepsProcessing.step +import com.intellij.remoterobot.utils.waitFor +import com.intellij.remoterobot.utils.waitForIgnoringError +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import java.time.Duration.ofMinutes +import java.time.Duration.ofSeconds + +@ExtendWith(RemoteRobotExtension::class) +class Onboarding { + init { + StepsLogger.init() + } + + @BeforeEach + fun waitForIde(remoteRobot: RemoteRobot) { + waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } + } + + @AfterEach + fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() + + + // @Test + @Video + fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { + welcomeFrame { + createNewProjectLink.click() + dialog("New Project") { + findText("Java").click() + checkBox("Add sample code").select() + button("Create").click() + } + } + + idea { + // Wait for the default "Main.java" tab to load + // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. + // So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft" + waitFor(ofSeconds(20)) { + findAll( + byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']") + ).isNotEmpty() + } + + // TODO: Need a good way to ensure this is the first test ran in the entire suite +// step("Verify Continue tutorial file is loaded") { +// find(byXpath("//div[@visible_text='continue_tutorial.java']")) +// } + + step("Manually open the webview") { + // Manually open the webview + find(byXpath("//div[@text='Continue']"), ofSeconds((10))).click() + + waitFor(ofSeconds(10)) { + browser().isShowing + } + } + + step("Verify the onboarding card is present") { + waitFor(ofSeconds(30)) { + try { + browser().findElement("//*[@data-testid='onboarding-card']").html.isNotEmpty() + } catch (e: Exception) { + false + } + } + } + } + } +} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/TutorialTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/TutorialTest.kt deleted file mode 100644 index 8e43def29..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/TutorialTest.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.github.continuedev.continueintellijextension.e2e - -import com.automation.remarks.junit5.Video -import com.github.continuedev.continueintellijextension.pages.dialog -import com.github.continuedev.continueintellijextension.pages.idea -import com.github.continuedev.continueintellijextension.pages.welcomeFrame -import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension -import com.github.continuedev.continueintellijextension.utils.StepsLogger -import com.github.continuedev.continueintellijextension.utils.getMetaKey -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ComponentFixture -import com.intellij.remoterobot.fixtures.JCefBrowserFixture -import com.intellij.remoterobot.search.locators.Locator -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.steps.CommonSteps -import com.intellij.remoterobot.utils.keyboard -import com.intellij.remoterobot.utils.waitFor -import com.intellij.remoterobot.utils.waitForIgnoringError -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import java.awt.event.KeyEvent.* -import java.time.Duration.ofMinutes -import java.time.Duration.ofSeconds - -@ExtendWith(RemoteRobotExtension::class) -class TutorialTest { - init { - StepsLogger.init() - } - - @BeforeEach - fun waitForIde(remoteRobot: RemoteRobot) { - waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } - } - - @AfterEach - fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() - - @Test - @Video - fun completeTutorial(remoteRobot: RemoteRobot) = with(remoteRobot) { - welcomeFrame { - createNewProjectLink.click() - dialog("New Project") { - findText("Java").click() - checkBox("Add sample code").select() - button("Create").click() - } - } - - // Wait for the default "Main.java" tab to load - // Our "continue_tutorial.java" tab loads first, but then "Main.java" takes focus. - // So we need to wait for that to occur, and then focus on "continue_tutorial.java" - waitFor(ofSeconds(20)) { - findAll( - byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']") - ).isNotEmpty() - } - - val tutorialEditorTabLocator: Locator = - byXpath("//div[@accessiblename='continue_tutorial.java' and @class='EditorTabLabel']") - val tutorialEditorTab: ComponentFixture = - remoteRobot.find(ComponentFixture::class.java, tutorialEditorTabLocator) - tutorialEditorTab.click() - - // Manually open the webview - find(byXpath("//div[@text='Continue']")).click() - - // Arbitrary sleep while we wait for the webview to load - Thread.sleep(10000) - - val textToInsert = "Hello world!" - - idea { - with(textEditor()) { - editor.insertTextAtLine(0, 0, textToInsert) - editor.selectText(textToInsert) - keyboard { - hotKey(getMetaKey(), VK_J) - } - } - } - - // TODO: locator needs to be OS aware - // https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/remote-fixtures/src/main/kotlin/com/intellij/remoterobot/fixtures/CommonContainerFixture.kt#L203 - val jcefBrowser = find(JCefBrowserFixture.macLocator) - assert(jcefBrowser.getDom().isNotEmpty()) { "JCEF browser not found or empty" } - - val codeSnippetText = jcefBrowser.findElementByContainsText(textToInsert) - assert(codeSnippetText.html.isNotEmpty()) { "Failed to find code snippet in webview" } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json new file mode 100644 index 000000000..0160335f5 --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json @@ -0,0 +1,43 @@ +{ + "ui": { + "displayRawMarkdown": false + }, + "models": [ + { + "title": "TEST LLM", + "provider": "test", + "model": "this field is not used" + }, + { + "title": "Mock", + "provider": "mock", + "model": "this field is not used" + } + ], + "analytics": { + "provider": "continue-proxy" + }, + "tabAutocompleteModel": { + "title": "TEST LLM", + "provider": "test", + "model": "this field is not used" + }, + "tabAutocompleteOptions": { + "useCache": false + }, + "contextProviders": [ + { + "name": "docs" + }, + { + "name": "diff" + }, + { + "name": "url" + }, + { + "name": "folder" + } + ], + "docs": [] +} diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/DialogFixture.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt similarity index 95% rename from extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/DialogFixture.kt rename to extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt index 8bb5798e3..d9643a96b 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/DialogFixture.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt @@ -1,4 +1,4 @@ -package com.github.continuedev.continueintellijextension.pages +package com.github.continuedev.continueintellijextension.fixtures /* * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/DialogFixture.kt diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/IdeaFrame.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt similarity index 98% rename from extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/IdeaFrame.kt rename to extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt index b55432585..141677c15 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/IdeaFrame.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt @@ -1,4 +1,4 @@ -package com.github.continuedev.continueintellijextension.pages +package com.github.continuedev.continueintellijextension.fixtures /* * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/IdeaFrame.kt diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/WelcomeFrame.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt similarity index 94% rename from extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/WelcomeFrame.kt rename to extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt index ab59f72ab..70029fdaf 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/pages/WelcomeFrame.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt @@ -1,4 +1,4 @@ -package com.github.continuedev.continueintellijextension.pages +package com.github.continuedev.continueintellijextension.fixtures /* * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/WelcomeFrame.kt diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index c25ccff20..f4973fa87 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -5,6 +5,6 @@ }, "extends": ["../../.eslintrc.shared.json"], "rules": { - "@typescript-eslint/naming-convention": "warn" + "@typescript-eslint/naming-convention": "off" } } diff --git a/extensions/vscode/e2e/TestUtils.ts b/extensions/vscode/e2e/TestUtils.ts index e1ae22227..ad5bc8ede 100644 --- a/extensions/vscode/e2e/TestUtils.ts +++ b/extensions/vscode/e2e/TestUtils.ts @@ -1,9 +1,6 @@ import { expect } from "chai"; -import { - Key, - WebElement, - waitForAttributeValue, -} from "vscode-extension-tester"; +import { Key } from "vscode-extension-tester"; + import { DEFAULT_TIMEOUT } from "./constants"; export class TestUtils { diff --git a/extensions/vscode/e2e/actions/Autocomplete.actions.ts b/extensions/vscode/e2e/actions/Autocomplete.actions.ts index d8b43df29..c35c47a29 100644 --- a/extensions/vscode/e2e/actions/Autocomplete.actions.ts +++ b/extensions/vscode/e2e/actions/Autocomplete.actions.ts @@ -1,8 +1,9 @@ -import { TextEditor } from "vscode-extension-tester"; -import { TestUtils } from "../TestUtils"; -import { AutocompleteSelectors } from "../selectors/Autocomplete.selectors"; import { expect } from "chai"; +import { TextEditor } from "vscode-extension-tester"; + import { DEFAULT_TIMEOUT } from "../constants"; +import { AutocompleteSelectors } from "../selectors/Autocomplete.selectors"; +import { TestUtils } from "../TestUtils"; export class AutocompleteActions { public static async testCompletions(editor: TextEditor) { diff --git a/extensions/vscode/e2e/actions/Edit.actions.ts b/extensions/vscode/e2e/actions/Edit.actions.ts new file mode 100644 index 000000000..c53c2caba --- /dev/null +++ b/extensions/vscode/e2e/actions/Edit.actions.ts @@ -0,0 +1,40 @@ +import { TextEditor, WebView } from "vscode-extension-tester"; + +import { EditSelectors } from "../selectors/Edit.selectors"; +import { TestUtils } from "../TestUtils"; + +export class EditActions { + static async invokeEditShortcut(editor: TextEditor) { + editor + .getDriver() + .actions() + .keyDown(TestUtils.osControlKey) + .sendKeys("i") + .keyUp(TestUtils.osControlKey) + .perform(); + } + + static async acceptEditInGUI(view: WebView): Promise { + await TestUtils.waitForSuccess(async () => + (await EditSelectors.getEditAcceptButton(view)).click(), + ); + await view.switchBack(); + } + + static async rejectEditInGUI(view: WebView): Promise { + await TestUtils.waitForSuccess(async () => + (await EditSelectors.getEditRejectButton(view)).click(), + ); + await view.switchBack(); + } + + static async acceptEditWithCodeLens(editor: TextEditor): Promise { + const acceptCodeLens = await editor.getCodeLens("Accept"); + await acceptCodeLens?.click(); + } + + static async rejectEditWithCodeLens(editor: TextEditor): Promise { + const rejectCodeLens = await editor.getCodeLens("Reject"); + await rejectCodeLens?.click(); + } +} diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index 567a2f572..ace296ca3 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -6,9 +6,10 @@ import { WebView, Workbench, } from "vscode-extension-tester"; + +import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; import { TestUtils } from "../TestUtils"; -import { DEFAULT_TIMEOUT } from "../constants"; export class GUIActions { public static moveContinueToSidebar = async (driver: WebDriver) => { diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index b6d599089..aafd1040a 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -1,7 +1,29 @@ -import { VSBrowser, WebView } from "vscode-extension-tester"; +import { + EditorView, + InputBox, + TextEditor, + VSBrowser, + Workbench, +} from "vscode-extension-tester"; + +import { DEFAULT_TIMEOUT } from "../constants"; export class GlobalActions { public static async openTestWorkspace() { return VSBrowser.instance.openResources("e2e/test-continue"); } + + public static async createAndOpenNewTextFile(): Promise<{ + editor: TextEditor; + }> { + await new Workbench().executeCommand("Create: New File..."); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("Text File"); + const editor = (await new EditorView().openEditor( + "Untitled-1", + )) as TextEditor; + + return { editor }; + } } diff --git a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts index 0a4cc51ad..358d883bd 100644 --- a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts +++ b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts @@ -1,6 +1,4 @@ -import { TextEditor, WebDriver, WebView } from "vscode-extension-tester"; - -import { TestUtils } from "../TestUtils"; +import { TextEditor } from "vscode-extension-tester"; export class KeyboardShortcutsActions { /** diff --git a/extensions/vscode/e2e/selectors/Edit.selectors.ts b/extensions/vscode/e2e/selectors/Edit.selectors.ts new file mode 100644 index 000000000..aaebe576d --- /dev/null +++ b/extensions/vscode/e2e/selectors/Edit.selectors.ts @@ -0,0 +1,13 @@ +import { WebView } from "vscode-extension-tester"; + +import { SelectorUtils } from "./SelectorUtils"; + +export class EditSelectors { + public static getEditAcceptButton(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "edit-accept-button"); + } + + public static getEditRejectButton(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "edit-reject-button"); + } +} diff --git a/extensions/vscode/e2e/selectors/GUI.selectors.ts b/extensions/vscode/e2e/selectors/GUI.selectors.ts index 82c0292b4..e7f8c78d0 100644 --- a/extensions/vscode/e2e/selectors/GUI.selectors.ts +++ b/extensions/vscode/e2e/selectors/GUI.selectors.ts @@ -1,4 +1,5 @@ -import { By, until, WebDriver, WebView } from "vscode-extension-tester"; +import { By, WebDriver, WebView } from "vscode-extension-tester"; + import { SelectorUtils } from "./SelectorUtils"; export class GUISelectors { diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index 50ac6c341..836c2c60e 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,13 +1,8 @@ -import { - EditorView, - TextEditor, - InputBox, - Workbench, -} from "vscode-extension-tester"; +import { EditorView, TextEditor } from "vscode-extension-tester"; -import { DEFAULT_TIMEOUT } from "../constants"; -import { GlobalActions } from "../actions/Global.actions"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; describe("Autocomplete", () => { let editor: TextEditor; @@ -16,11 +11,7 @@ describe("Autocomplete", () => { this.timeout(DEFAULT_TIMEOUT.XL); await GlobalActions.openTestWorkspace(); - await new Workbench().executeCommand("Create: New File..."); - await ( - await InputBox.create(DEFAULT_TIMEOUT.MD) - ).selectQuickPick("Text File"); - editor = (await new EditorView().openEditor("Untitled-1")) as TextEditor; + ({ editor } = await GlobalActions.createAndOpenNewTextFile()); }); afterEach(async function () { diff --git a/extensions/vscode/e2e/tests/Edit.test.ts b/extensions/vscode/e2e/tests/Edit.test.ts new file mode 100644 index 000000000..e79dd010c --- /dev/null +++ b/extensions/vscode/e2e/tests/Edit.test.ts @@ -0,0 +1,125 @@ +import { + EditorView, + WebView, + WebDriver, + Key, + VSBrowser, + InputBox, + TextEditor, + Workbench, +} from "vscode-extension-tester"; + +import { EditActions } from "../actions/Edit.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { GUIActions } from "../actions/GUI.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { EditSelectors } from "../selectors/Edit.selectors"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import { TestUtils } from "../TestUtils"; + +describe("Edit Test", () => { + let view: WebView; + let editor: TextEditor; + let originalEditorText = "Hello world!"; + let { userMessage, llmResponse } = TestUtils.generateTestMessagePair(); + + before(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver); + await GlobalActions.openTestWorkspace(); + ({ editor } = await GlobalActions.createAndOpenNewTextFile()); + }); + + beforeEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await GUIActions.toggleGui(); + + await editor.typeTextAt(1, 1, originalEditorText); + await editor.selectText(originalEditorText); + + await EditActions.invokeEditShortcut(editor); + + ({ view } = await GUIActions.switchToReactIframe()); + + await GUIActions.sendMessage({ + view, + message: userMessage, + inputFieldIndex: 0, + }); + + await view.switchBack(); + + await TestUtils.waitForSuccess(async () => { + const editorText = await editor.getText(); + return editorText.includes(llmResponse); + }); + }); + + afterEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await editor.clearText(); + }); + + it("Accepts an Edit in the GUI", async () => { + ({ view } = await GUIActions.switchToReactIframe()); + + await EditActions.acceptEditInGUI(view); + + await view.switchBack(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + !editorText.includes(originalEditorText) && + editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Rejects an Edit in the GUI", async () => { + ({ view } = await GUIActions.switchToReactIframe()); + + await EditActions.rejectEditInGUI(view); + + await view.switchBack(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + editorText.includes(originalEditorText) && + !editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Accepts an Edit using CodeLens buttons", async () => { + const acceptCodeLens = await editor.getCodeLens("Accept"); + await acceptCodeLens?.click(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + !editorText.includes(originalEditorText) && + editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Rejects an Edit using CodeLens buttons", async () => { + const rejectCodeLens = await editor.getCodeLens("Reject"); + await rejectCodeLens?.click(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + !editorText.includes(originalEditorText) && + editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); +}); diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index b5e3cabc3..644cbaf64 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -1,3 +1,4 @@ +import { expect } from "chai"; import { EditorView, WebView, @@ -7,12 +8,12 @@ import { VSBrowser, until, } from "vscode-extension-tester"; -import { expect } from "chai"; + +import { GlobalActions } from "../actions/Global.actions"; import { GUIActions } from "../actions/GUI.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; import { TestUtils } from "../TestUtils"; -import { DEFAULT_TIMEOUT } from "../constants"; -import { GlobalActions } from "../actions/Global.actions"; describe("GUI Test", () => { let view: WebView; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 147a1f118..448e6baf2 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -739,10 +739,12 @@ const getCommandsMap: ( if (fullScreenTab && fullScreenPanel) { // Full screen open, but not focused - focus it fullScreenPanel.reveal(); - vscode.commands.executeCommand("continue.focusContinueInput"); return; } + // Clear the sidebar to prevent overwriting changes made in fullscreen + vscode.commands.executeCommand("continue.newSession") + // Full screen not open - open it captureCommandTelemetry("openFullScreen"); @@ -767,7 +769,7 @@ const getCommandsMap: ( true, ); - panel.onDidChangeViewState(() => { + const sessionLoader = panel.onDidChangeViewState(() => { vscode.commands.executeCommand("continue.newSession"); if (sessionId) { vscode.commands.executeCommand( @@ -775,6 +777,7 @@ const getCommandsMap: ( sessionId, ); } + sessionLoader.dispose() }); // When panel closes, reset the webview and focus diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index a3a7f651f..4d8a99020 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -359,7 +359,7 @@ export class VerticalDiffHandler implements vscode.Disposable { // Clear deletion buffer await this.insertDeletionBuffer(); - this.reapplyWithMeyersDiff(diffLines); + await this.reapplyWithMeyersDiff(diffLines); this.options.onStatusUpdate( "done", @@ -386,6 +386,7 @@ export class VerticalDiffHandler implements vscode.Disposable { startLine: number, numGreen: number, numRed: number, + skipStatusUpdate?: boolean, ) { if (numGreen > 0) { // Delete the editor decoration @@ -415,15 +416,18 @@ export class VerticalDiffHandler implements vscode.Disposable { // Shift the codelens objects this.shiftCodeLensObjects(startLine, offset); - const numDiffs = - this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0; + if (!skipStatusUpdate) { + const numDiffs = + this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0; - const status = numDiffs === 0 ? "closed" : undefined; - this.options.onStatusUpdate( - status, - numDiffs, - this.editor.document.getText(), - ); + const status = numDiffs === 0 ? "closed" : undefined; + + this.options.onStatusUpdate( + status, + numDiffs, + this.editor.document.getText(), + ); + } } private shiftCodeLensObjects(startLine: number, offset: number) { @@ -482,11 +486,15 @@ export class VerticalDiffHandler implements vscode.Disposable { * we have received all of the diff lines. */ async reapplyWithMeyersDiff(diffLines: DiffLine[]) { - // First, we reset the original diff by deleting any new lines and clearing decorations - for (const range of this.greenDecorationManager.getRanges()) { - await this.deleteLinesAt( - range.start.line, - range.end.line - range.start.line + 1, + // First, we reset the original diff by rejecting all pending diff blocks + for (const block of this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? + []) { + await this.acceptRejectBlock( + false, + block.start, + block.numGreen, + block.numRed, + true, ); } diff --git a/gui/.eslintrc.json b/gui/.eslintrc.json index 346c650fe..c902e379f 100644 --- a/gui/.eslintrc.json +++ b/gui/.eslintrc.json @@ -11,6 +11,9 @@ // "plugin:@typescript-eslint/recommended-requiring-type-checking" // "plugin:react/recommended" ], + "rules": { + "@typescript-eslint/naming-convention": "off" + }, "overrides": [ { "files": ["src/**/*.{js,ts,jsx,tsx}"] diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx index f915f27d7..3d59ac239 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx @@ -98,7 +98,7 @@ export default function CodeToEditListItem({ -
+
{showCodeSnippet ? ( + handleAcceptOrReject("rejectDiff")} + data-testid="edit-reject-button" > {isSingleRangeEdit ? ( @@ -53,6 +54,7 @@ export default function AcceptRejectAllButtons({