Merge branch 'main' into pe/search-and-replace-experiment

This commit is contained in:
Patrick Erichsen 2025-06-26 17:52:01 -07:00
commit ef412f97a9
71 changed files with 10071 additions and 744 deletions

View file

@ -0,0 +1,35 @@
---
name: New protocol message
description: Create a new protocol message from core/gui/ide to core/gui/ide
---
Create a new protocol message by taking the following steps:
## 1. Define the message type
Add your new message type definition to the appropriate file in the `protocol/` directory with correct TypeScript typing.
## 2. Check for duplicates
Verify that no existing message type already provides the same functionality.
## 3. Add to passThrough (if webview ↔ core)
If your message is between webview and core, add it to `core/protocol/passThrough.ts`.
## 4. Add to IntelliJ constants (if webview ↔ core)
If your message is between webview and core, add it to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`.
## 5. Implement the message handler
Implement the message in the appropriate location:
- **Messages to core**: `core/core.ts`
- **Messages to GUI**: `useWebviewListener` hook
- **Messages to VS Code IDE**: `VsCodeMessenger.ts`
- **Messages to JetBrains IDE**: `IdeProtocolClient.kt`
## 6. Test the implementation
Verify that your message works correctly in both VS Code and JetBrains IDEs if applicable.

View file

@ -0,0 +1,5 @@
---
name: Don't be overeager
---
Avoid over-eagerly adding new features. You should solve the problem at hand and then can propose further work.

View file

@ -104,6 +104,14 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Build packages (Windows)
run: ./scripts/build-packages.ps1
if: matrix.os == 'windows-latest'
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
if: matrix.os != 'windows-latest'
- name: Install extension Dependencies
run: |
cd extensions/vscode

View file

@ -99,6 +99,14 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Build packages (Windows)
run: ./scripts/build-packages.ps1
if: matrix.os == 'windows-latest'
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
if: matrix.os != 'windows-latest'
- name: Install extension Dependencies
run: |
cd extensions/vscode

View file

@ -9,38 +9,10 @@ on:
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Install dependencies
run: |
cd packages/config-yaml
npm ci
- name: Build
run: |
cd packages/config-yaml
npm run build
- name: Run tests
run: |
cd packages/config-yaml
npm test
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
cd packages/config-yaml
npx semantic-release
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "config-yaml"
package-path: "packages/config-yaml"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

18
.github/workflows/release-fetch.yml vendored Normal file
View file

@ -0,0 +1,18 @@
name: Release @continuedev/fetch
on:
push:
branches:
- main
paths:
- "packages/fetch/**"
jobs:
release:
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "fetch"
package-path: "packages/fetch"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

18
.github/workflows/release-llm-info.yml vendored Normal file
View file

@ -0,0 +1,18 @@
name: Release @continuedev/llm-info
on:
push:
branches:
- main
paths:
- "packages/llm-info/**"
jobs:
release:
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "llm-info"
package-path: "packages/llm-info"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

View file

@ -0,0 +1,18 @@
name: Release @continuedev/openai-adapters
on:
push:
branches:
- main
paths:
- "packages/openai-adapters/**"
jobs:
release:
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "openai-adapters"
package-path: "packages/openai-adapters"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

55
.github/workflows/reusable-release.yml vendored Normal file
View file

@ -0,0 +1,55 @@
name: Reusable Release Workflow
on:
workflow_call:
inputs:
package-name:
required: true
type: string
package-path:
required: true
type: string
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN:
required: true
SEMANTIC_RELEASE_NPM_TOKEN:
required: true
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
name: Release ${{ inputs.package-name }}
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ inputs.package-path }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Run tests
run: npm test
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
run: npx semantic-release

View file

@ -53,9 +53,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.13",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -106,7 +106,6 @@
"sqlite3": "^5.1.7",
"system-ca": "^1.0.3",
"tar": "^7.4.3",
"tree-sitter-structured-text": "^0.0.1",
"tree-sitter-wasms": "^0.1.11",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
@ -145,7 +144,6 @@
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"tree-sitter-cli": "^0.22.5",
"ts-jest": "^29.1.1",
"typescript": "^5.6.3",
"vitest": "^3.1.4"

View file

@ -39,7 +39,7 @@ import { GlobalContext } from "../../util/GlobalContext";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { baseToolDefinitions } from "../../tools";
import { getToolsForIde } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
@ -187,7 +187,7 @@ async function configYamlToContinueConfig(options: {
const continueConfig: ContinueConfig = {
slashCommands: [],
tools: [...baseToolDefinitions],
tools: await getToolsForIde(ide),
mcpServerStatuses: [],
contextProviders: [],
modelsByRole: {

2
core/index.d.ts vendored
View file

@ -731,6 +731,8 @@ export interface IDE {
isTelemetryEnabled(): Promise<boolean>;
isWorkspaceRemote(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;

View file

@ -124,14 +124,6 @@ describe("CodebaseIndexer", () => {
return updates;
}
async function refreshIndexFiles(files: string[]) {
const updates = [];
for await (const update of codebaseIndexer.refreshFiles(files)) {
updates.push(update);
}
return updates;
}
async function getAllIndexedFiles() {
const files = await testIndex.getIndexedFilesForTags(
await testIde.getTags(testIndex.artifactId),
@ -197,7 +189,7 @@ describe("CodebaseIndexer", () => {
test("should successfuly re-index specific files", async () => {
// Could add more specific tests for this but uses similar logic
const before = await getAllIndexedFiles();
await refreshIndexFiles(before);
await codebaseIndexer.refreshCodebaseIndexFiles(before);
const after = await getAllIndexedFiles();
expect(after.length).toBe(before.length);

View file

@ -43,7 +43,7 @@ export class CodebaseIndexer {
* - To limit memory usage for indexes that perform computations locally, e.g. FTS
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 500;
filesPerBatch = 200;
private indexingCancellationController: AbortController | undefined;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
@ -75,16 +75,10 @@ export class CodebaseIndexer {
this.pauseToken = new PauseToken(initialPaused);
}
/**
* Set the paused state of the indexer
*/
set paused(value: boolean) {
this.pauseToken.paused = value;
}
/**
* Get the current paused state of the indexer
*/
get paused(): boolean {
return this.pauseToken.paused;
}
@ -235,7 +229,9 @@ export class CodebaseIndexer {
}
}
async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
private async *refreshFiles(
files: string[],
): AsyncGenerator<IndexingProgressUpdate> {
let progress = 0;
if (files.length === 0) {
yield {
@ -525,7 +521,7 @@ export class CodebaseIndexer {
repoName,
)) {
yield {
progress: progress,
progress,
desc,
status: "indexing",
};

View file

@ -546,7 +546,7 @@ class Bedrock extends BaseLLM {
}
// EMBED //
async embed(chunks: string[]): Promise<number[][]> {
async _embed(chunks: string[]): Promise<number[][]> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,

View file

@ -25,16 +25,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
});
}
async embed(chunks: string[]) {
const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
batchedChunks.map((batch) => this.doEmbedRequest(batch)),
);
return results.flat();
}
async doEmbedRequest(batch: string[]): Promise<number[][]> {
async _embed(batch: string[]): Promise<number[][]> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};

View file

@ -141,7 +141,7 @@ class SageMaker extends BaseLLM {
}
}
async embed(chunks: string[]) {
async _embed(chunks: string[]) {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.region,

View file

@ -139,7 +139,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.94",
"version": "1.0.95",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -150,10 +150,15 @@
"config-yaml": "dist/cli.js"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/jest": "^29.5.14",
"@types/node": "^20.0.0",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"semantic-release": "^21.1.2",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2",
"zod-to-json-schema": "^3.24.5"
@ -161,7 +166,7 @@
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.0.40",
"version": "1.0.42",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",

View file

@ -60,6 +60,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
];
getAvailableThreads: [undefined, Thread[]];
isTelemetryEnabled: [undefined, boolean];
isWorkspaceRemote: [undefined, boolean];
getUniqueId: [undefined, string];
getTags: [string, IndexTag[]];
readSecrets: [{ keys: string[] }, Record<string, string>];

View file

@ -106,6 +106,10 @@ export class MessageIde implements IDE {
return this.request("isTelemetryEnabled", undefined);
}
isWorkspaceRemote(): Promise<boolean> {
return this.request("isWorkspaceRemote", undefined);
}
getUniqueId(): Promise<string> {
return this.request("getUniqueId", undefined);
}

10
core/rules.md Normal file
View file

@ -0,0 +1,10 @@
# `core` rules
Whenever a new protocol message is added to the `protocol/` directory, check the following:
- It's type is defined correctly
- If it is a message from webview to core or vice versa:
- It has been added to `core/protocol/passThrough.ts`
- It has been added to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`
- It is implemented in either `core/core.ts` (for messages to the core), in a `useWebviewListener` (for messages to the gui), or in `VsCodeMessenger.ts` for VS Code or `IdeProtocolClient.kt` for JetBriains (for messages to the IDE).
- It does not duplicate functionality from another message type that already exists.

View file

@ -1,4 +1,4 @@
import { ConfigDependentToolParams, Tool } from "..";
import { ConfigDependentToolParams, IDE, Tool } from "..";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
@ -16,11 +16,13 @@ import { viewDiffTool } from "./definitions/viewDiff";
import { viewRepoMapTool } from "./definitions/viewRepoMap";
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
export const localOnlyToolDefinitions = [grepSearchTool];
export const baseToolDefinitions = [
readFileTool,
createNewFileTool,
runTerminalCommandTool,
grepSearchTool,
globSearchTool,
searchWebTool,
viewDiffTool,
@ -38,3 +40,8 @@ export const getConfigDependentToolDefinitions = (
? [searchAndReplaceInFileTool, viewRepoMapTool, viewSubdirectoryTool]
: [editFileTool]),
];
export const getToolsForIde = async (ide: IDE) =>
(await ide.isWorkspaceRemote())
? baseToolDefinitions
: [...baseToolDefinitions, ...localOnlyToolDefinitions];

View file

@ -48,6 +48,10 @@ class FileSystemIde implements IDE {
return;
}
isWorkspaceRemote(): Promise<boolean> {
return Promise.resolve(false);
}
async getIdeSettings(): Promise<IdeSettings> {
return {
remoteConfigServerUrl: undefined,

View file

@ -5,93 +5,54 @@ title: Prompts
Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
:::info
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
Prompts were previously defined in a `.prompt` file format, but for consistency we now recommend using the same Markdown format as [rules](./rules.mdx) and adding `alwaysApply: false` to the frontmatter so that they are manually triggered.
:::
## Examples
Below are some examples to get you started.
### Security review
```text title="Security best practices review"
@open - Review these files for the following security best practices:
- Does the architecture follow security-by-design principles?
- Are there potential security vulnerabilities in the system design?
- Is sensitive data handled appropriately throughout the lifecycle?
```
### Reference best practice guides
```text title="Redux best practices review"
@https://redux.js.org/style-guide/
@currentFile
Review this code for adherence to Redux best practices.
```
### Pull in commonly used files for tasks
```text title="Generate a new TypeORM entity"
@src/db/dataSource.ts @src/db/entity/SampleEntity.ts
Use these files to generate a new TypeORM entity based on the following requirements:
```
## Including Context Providers in your prompts
Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is:
- `@terminal` - The contents of the terminal
- `@currentFile` - The currently active file
- `@open` - All open files
- `@os` - Information about the operating system
- `@problems` - Problems reported by the language server in the active file
- `@repo-map` - A map of files in the repository
- `@tree` - A tree view of the repository structure
Or you can directly type URLs and file paths:
- `@https://github.com/continuedev/continue` - The contents of a URL
- `@src/index.ts` - The contents of a file (VS Code only)
All references will be attached as context items, rather than injected directly inline.
## Local `.prompt` files
In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub.
### Quick Start
Below is a quick example of setting up a prompt file:
1. Create a folder called `.continue/prompts` at the top level of your workspace
2. Add a file called `test.prompt` to this folder.
3. Write the following contents to `test.prompt` and save.
1. Create a folder called `.continue/rules` at the top level of your workspace
2. Add a file called `review-prompt.md` to this folder.
3. Write the following contents to `review-prompt.md` and save.
```.prompt
name: Current file prompt
description: A test prompt using the current file context provider
```md title="review-prompt.md"
---
@currentFile
name: Redux best practices review
alwaysApply: false
---
Review the currently open file for adherence to Redux best practices, as explained in their style guide at https://redux.js.org/style-guide/.
```
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and add type out some additional text such as "Review the code for any issues".
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and type out any additional instructions you'd like to add.
### Format
## Further Examples
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts).
:::info
The current state of this format is experimental and subject to change
:::
### Security review
### Preamble
```md title="security-review.md"
---
name: Security best practices review
alwaysApply: false
---
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
Review the changes in the current git diff for these security best practices:
- `name` - The display title
- `description` - The description you will see in the dropdown
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
- Does the architecture follow security-by-design principles?
- Are there potential security vulnerabilities in the system design?
- Is sensitive data handled appropriately throughout the lifecycle?
```
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
### Pull in commonly used files for tasks
```md title="typeorm-entity-generator.md"
---
name: Generate a new TypeORM entity
alwaysApply: false
---
Referencing `src/db/dataSource.ts` and `src/db/entity/SampleEntity.ts`, generate a new TypeORM entity based on the following requirements:
```

View file

@ -55,19 +55,26 @@ For example, you can say "Create a rule for this", and a rule will be created fo
Rules can also be added to an Assistant on the Continue Hub.
Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally.
Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
### Syntax
:::info
Rules were originally defined in YAML format (demonstrated below), but we introduced Markdown for easier editing. While both are still supported, we recommend Markdown.
:::
Rules blocks can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties:
- `name` (**required** for YAML): A display name/title for the rule
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
- `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`).
- `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context.
- `alwaysApply`: true - Always include the rule, regardless of file context
- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description
- `alwaysApply`: undefined - Default behavior: include if no globs exist OR globs exist and match
- `alwaysApply`: Determines whether the rule is always included. Behavior is described below:
- `true`: Always included, regardless of file context
- `false`: Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description
- `undefined` (default behavior): Included if no globs exist OR globs exist and match
<Tabs groupId="rules-example">
<TabItem value="md" label="Markdown">
@ -97,10 +104,13 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark
```yaml title="doc-standards.yaml"
name: Documentation Standards
globs: docs/**/*.{md,mdx}
alwaysApply: false
version: 1.0.0
schema: v1
rules:
- name: Documentation Standards
globs: docs/**/*.{md,mdx}
alwaysApply: false
rule: >
- Follow Docusaurus documentation standards
- Include YAML frontmatter with title, description, and keywords
@ -164,7 +174,7 @@ Whenever you are writing React code, make sure to
Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output.
This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4)
This can be viewed in the rules section of the toolbar (see above), or in the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4).
Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models).
@ -172,7 +182,7 @@ Advanced users can override this system message for a specific model if needed b
:::warning
`.contninuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead.
`.continuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead.
:::

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.25
pluginVersion=1.0.26
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -2,9 +2,9 @@ package com.github.continuedev.continueintellijextension.auth
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.Desktop
import com.google.gson.Gson
import com.intellij.credentialStore.Credentials
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
@ -165,7 +165,7 @@ class ContinueAuthService {
// Still open the URL in the browser (keeping existing behavior)
if (authUrl != null) {
Desktop.browse(java.net.URI(authUrl))
BrowserUtil.open(authUrl!!)
}
return authUrl

View file

@ -10,6 +10,7 @@ import com.github.continuedev.continueintellijextension.utils.*
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.BrowserUtil
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.annotation.HighlightSeverity
@ -125,6 +126,10 @@ class IntelliJIDE(
return true
}
override suspend fun isWorkspaceRemote(): Boolean {
return this.getIdeInfo().remoteName != "local"
}
override suspend fun getUniqueId(): String {
return getMachineUniqueID()
}
@ -211,7 +216,7 @@ class IntelliJIDE(
override suspend fun openUrl(url: String) {
withContext(Dispatchers.IO) {
Desktop.browse(URI(url))
BrowserUtil.browse(url)
}
}

View file

@ -102,6 +102,8 @@ interface IDE {
suspend fun isTelemetryEnabled(): Boolean
suspend fun isWorkspaceRemote(): Boolean
suspend fun getUniqueId(): String
suspend fun getTerminalContents(): String

View file

@ -1,214 +0,0 @@
/*
* Copyright © 2017 jjYBdx4IL (https://github.com/jjYBdx4IL)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.continuedev.continueintellijextension.utils
import org.apache.commons.lang3.SystemUtils
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.net.URI
object Desktop {
private val LOG = LoggerFactory.getLogger(Desktop::class.java)
fun browse(uri: URI): Boolean {
if (browseDESKTOP(uri)) {
return true
}
if (openSystemSpecific(uri.toString())) {
return true
}
LOG.warn("failed to browse {}", uri)
return false
}
fun open(file: File): Boolean {
if (openDESKTOP(file)) {
return true
}
if (openSystemSpecific(file.path)) {
return true
}
LOG.warn("failed to open {}", file.absolutePath)
return false
}
fun edit(file: File): Boolean {
if (editDESKTOP(file)) {
return true
}
if (openSystemSpecific(file.path)) {
return true
}
LOG.warn("failed to edit {}", file.absolutePath)
return false
}
private fun openSystemSpecific(what: String): Boolean {
if (SystemUtils.IS_OS_LINUX) {
if (isXDG() && runCommand("xdg-open", "%s", what)) {
return true
}
if (isKDE() && runCommand("kde-open", "%s", what)) {
return true
}
if (isGNOME() && runCommand("gnome-open", "%s", what)) {
return true
}
if (runCommand("kde-open", "%s", what)) {
return true
}
if (runCommand("gnome-open", "%s", what)) {
return true
}
}
if (SystemUtils.IS_OS_MAC && runCommand("open", "%s", what)) {
return true
}
if (SystemUtils.IS_OS_WINDOWS && runCommand("explorer", "%s", what)) {
return true
}
return false
}
private fun browseDESKTOP(uri: URI): Boolean {
return try {
if (!java.awt.Desktop.isDesktopSupported()) {
LOG.debug("Platform is not supported.")
return false
}
if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) {
LOG.debug("BROWSE is not supported.")
return false
}
LOG.info("Trying to use Desktop.getDesktop().browse() with {}", uri.toString())
java.awt.Desktop.getDesktop().browse(uri)
true
} catch (t: Throwable) {
LOG.error("Error using desktop browse.", t)
false
}
}
private fun openDESKTOP(file: File): Boolean {
return try {
if (!java.awt.Desktop.isDesktopSupported()) {
LOG.debug("Platform is not supported.")
return false
}
if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.OPEN)) {
LOG.debug("OPEN is not supported.")
return false
}
LOG.info("Trying to use Desktop.getDesktop().open() with {}", file.toString())
java.awt.Desktop.getDesktop().open(file)
true
} catch (t: Throwable) {
LOG.error("Error using desktop open.", t)
false
}
}
private fun editDESKTOP(file: File): Boolean {
return try {
if (!java.awt.Desktop.isDesktopSupported()) {
LOG.debug("Platform is not supported.")
return false
}
if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.EDIT)) {
LOG.debug("EDIT is not supported.")
return false
}
LOG.info("Trying to use Desktop.getDesktop().edit() with {}", file)
java.awt.Desktop.getDesktop().edit(file)
true
} catch (t: Throwable) {
LOG.error("Error using desktop edit.", t)
false
}
}
private fun runCommand(command: String, args: String, file: String): Boolean {
LOG.info("Trying to exec:\n cmd = {}\n args = {}\n %s = {}", command, args, file)
val parts = prepareCommand(command, args, file)
return try {
val p = Runtime.getRuntime().exec(parts)
if (p == null) {
false
} else {
try {
val retval = p.exitValue()
if (retval == 0) {
LOG.error("Process ended immediately.")
false
} else {
LOG.error("Process crashed.")
false
}
} catch (itse: IllegalThreadStateException) {
LOG.error("Process is running.")
true
}
}
} catch (e: IOException) {
LOG.error("Error running command.", e)
false
}
}
private fun prepareCommand(command: String, args: String?, file: String): Array<String> {
val parts = mutableListOf<String>()
parts.add(command)
args?.split(" ")?.forEach { s ->
parts.add(String.format(s, file).trim())
}
return parts.toTypedArray()
}
private fun isXDG(): Boolean {
val xdgSessionId = System.getenv("XDG_SESSION_ID")
return !xdgSessionId.isNullOrEmpty()
}
private fun isGNOME(): Boolean {
val gdmSession = System.getenv("GDMSESSION")
return gdmSession?.lowercase()?.contains("gnome") == true
}
private fun isKDE(): Boolean {
val gdmSession = System.getenv("GDMSESSION")
return gdmSession?.lowercase()?.contains("kde") == true
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.50",
"version": "1.1.52",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.50",
"version": "1.1.52",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.50",
"version": "1.1.52",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -200,6 +200,10 @@ class VsCodeIde implements IDE {
return globalEnabled && continueEnabled;
}
isWorkspaceRemote(): Promise<boolean> {
return Promise.resolve(vscode.env.remoteName !== undefined);
}
getUniqueId(): Promise<string> {
return Promise.resolve(vscode.env.machineId);
}

7
gui/package-lock.json generated
View file

@ -215,7 +215,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.94",
"version": "1.0.95",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -226,10 +226,15 @@
"config-yaml": "dist/cli.js"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/jest": "^29.5.14",
"@types/node": "^20.0.0",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"semantic-release": "^21.1.2",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2",
"zod-to-json-schema": "^3.24.5"

View file

@ -11,8 +11,10 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { useAppSelector } from "../../../redux/hooks";
import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall";
import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice";
import {
selectApplyStateByStreamId,
selectApplyStateByToolCallId,
} from "../../../redux/slices/sessionSlice";
import { getFontSize } from "../../../util";
import Spinner from "../../gui/Spinner";
import { isTerminalCodeBlock } from "../utils";
@ -54,6 +56,7 @@ export interface StepContainerPreToolbarProps {
codeBlockIndex: number; // To track which codeblock we are applying
isLastCodeblock: boolean;
codeBlockStreamId: string;
forceToolCallId?: string; // If this is defined, we will use this streamId instead of the one from the codeBlock
range?: string;
children: any;
expanded?: boolean;
@ -68,6 +71,7 @@ export function StepContainerPreToolbar({
codeBlockIndex,
isLastCodeblock,
codeBlockStreamId,
forceToolCallId,
range,
children,
expanded,
@ -99,8 +103,8 @@ export function StepContainerPreToolbar({
const applyState = useAppSelector((state) =>
selectApplyStateByStreamId(state, codeBlockStreamId),
);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
const toolCallApplyState = useAppSelector((state) =>
selectApplyStateByToolCallId(state, forceToolCallId),
);
/**
@ -147,7 +151,7 @@ export function StepContainerPreToolbar({
setRelativeFilepathUri(resolvedUri);
}
};
getRelativeFilepathUri();
void getRelativeFilepathUri();
}, [relativeFilepath, ideMessenger.ide]);
async function getFileUriToApplyTo() {
@ -173,7 +177,7 @@ export function StepContainerPreToolbar({
async function onClickApply() {
const fileUri = await getFileUriToApplyTo();
if (!fileUri) {
ideMessenger.ide.showToast(
void ideMessenger.ide.showToast(
"error",
"Could not resolve filepath to apply changes",
);
@ -188,7 +192,7 @@ export function StepContainerPreToolbar({
});
setAppliedFileUri(fileUri);
refreshFileExists();
void refreshFileExists();
}
function onClickInsertAtCursor() {
@ -198,7 +202,7 @@ export function StepContainerPreToolbar({
async function handleDiffAction(action: "accept" | "reject") {
const filepath = await getFileUriToApplyTo();
if (!filepath) {
ideMessenger.ide.showToast(
void ideMessenger.ide.showToast(
"error",
`Could not resolve filepath to ${action} changes`,
);
@ -233,10 +237,7 @@ export function StepContainerPreToolbar({
}
const renderActionButtons = () => {
const isPendingToolCall =
currentToolCallApplyState &&
currentToolCallApplyState.streamId === applyState?.streamId &&
currentToolCallApplyState.status === "not-started";
const isPendingToolCall = toolCallApplyState?.status === "not-started";
if (isGeneratingCodeBlock || isPendingToolCall) {
const numLines = codeBlockContent.split("\n").length;
@ -271,7 +272,7 @@ export function StepContainerPreToolbar({
return (
<ApplyActions
disableManualApply={disableManualApply}
applyState={applyState}
applyState={toolCallApplyState ?? applyState}
onClickApply={onClickApply}
onClickAccept={() => handleDiffAction("accept")}
onClickReject={() => handleDiffAction("reject")}
@ -293,6 +294,7 @@ export function StepContainerPreToolbar({
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
<div className="max-w-[50% flex flex-row items-center">
<ChevronDownIcon
data-testid="toggle-codeblock"
onClick={() => setIsExpanded(!isExpanded)}
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"

View file

@ -126,7 +126,7 @@ interface StyledMarkdownPreviewProps {
itemIndex?: number;
useParentBackgroundColor?: boolean;
disableManualApply?: boolean;
forceStreamId?: string;
toolCallId?: string;
expandCodeblocks?: boolean;
}
@ -196,11 +196,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const itemIndexRef = useUpdatingRef(props.itemIndex);
const codeblockStreamIds = useRef<string[]>([]);
useEffect(() => {
if (props.forceStreamId) {
codeblockStreamIds.current = [props.forceStreamId];
}
}, [props.forceStreamId, codeblockStreamIds]);
const [reactContent, setMarkdownSource] = useRemark({
remarkPlugins: [
@ -295,8 +290,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const isLastCodeblock = preChildProps["data-islastcodeblock"];
if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
codeblockStreamIds.current[codeBlockIndex] =
props.forceStreamId ?? uuidv4();
codeblockStreamIds.current[codeBlockIndex] = uuidv4();
}
return (
@ -308,7 +302,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
relativeFilepath={relativeFilePath}
isLastCodeblock={isLastCodeblock}
range={range}
codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found
forceToolCallId={props.toolCallId}
expanded={props.expandCodeblocks}
disableManualApply={props.disableManualApply}
>

View file

@ -330,7 +330,10 @@ export function createEditorConfig(options: {
],
editorProps: {
attributes: {
class: "outline-none overflow-hidden",
"data-testid": props.isMainInput
? "editor-input-main"
: `editor-input-${props.inputId}`,
class: "ProseMirror outline-none overflow-hidden",
style: `font-size: ${getFontSize()}px;`,
},
},

View file

@ -1,7 +1,6 @@
import { IDE, PromptLog } from "core";
import { ChatMessage, IDE, PromptLog } from "core";
import { AuthType } from "core/control-plane/AuthTypes";
import {
FromIdeProtocol,
FromWebviewProtocol,
ToCoreProtocol,
ToWebviewProtocol,
@ -13,73 +12,83 @@ import {
GeneratorYieldType,
WebviewSingleProtocolMessage,
} from "core/protocol/util";
import { ChatMessage } from "../redux/store";
import { IIdeMessenger } from "./IdeMessenger";
async function defaultMockHandleMessage<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<FromWebviewProtocol[T][1]> {
function returnFor<K extends keyof FromWebviewProtocol>(
_: K,
value: FromWebviewProtocol[K][1],
): FromWebviewProtocol[T][1] {
return value as unknown as FromWebviewProtocol[T][1];
}
type MockResponses = Partial<{
[K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
}>;
switch (messageType) {
case "history/list":
return returnFor("history/list", [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
]);
case "getControlPlaneSessionInfo":
return returnFor("getControlPlaneSessionInfo", {
AUTH_TYPE: AuthType.WorkOsStaging,
accessToken: "",
account: {
label: "",
id: "",
},
});
case "config/getSerializedProfileInfo":
return returnFor("config/getSerializedProfileInfo", {
organizations: [],
profileId: "test-profile",
result: {
config: undefined,
errors: [],
configLoadInterrupted: false,
},
selectedOrgId: "local",
});
default:
throw new Error(`Unknown message type ${messageType}`);
}
}
const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
fileExists: true,
getCurrentFile: {
isUntitled: false,
contents: "Current file contents",
path: "file:///Users/user/workspace1/current_file.py",
},
"controlPlane/getFreeTrialStatus": {
autocompleteLimit: 1000,
optedInToFreeTrial: false,
chatLimit: 1000,
autocompleteCount: 0,
chatCount: 0,
},
getWorkspaceDirs: [
"file:///Users/user/workspace1",
"file:///Users/user/workspace2",
],
"history/list": [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
],
"history/save": undefined,
getControlPlaneSessionInfo: {
AUTH_TYPE: AuthType.WorkOsStaging,
accessToken: "",
account: {
label: "",
id: "",
},
},
"config/getSerializedProfileInfo": {
organizations: [],
profileId: "test-profile",
result: {
config: undefined,
errors: [],
configLoadInterrupted: false,
},
selectedOrgId: "local",
},
"chatDescriber/describe": "Session summary",
applyToFile: undefined,
acceptDiff: undefined,
};
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
{
role: "assistant",
content: "This is a test",
},
];
export class MockIdeMessenger implements IIdeMessenger {
ide: IDE;
private messageHandlers: Map<
keyof FromIdeProtocol,
Array<(data: any) => void>
> = new Map();
constructor() {
this.ide = new MessageIde(
(messageType, data) => {
throw new Error("Not implemented");
async (messageType, data) => {
const response = await this.request.bind(this)(messageType, data);
if (response.status === "error") {
throw new Error(response.error);
} else {
return response.content;
}
},
(messageType, callback) => {
// Store the callback in our handlers map
if (!this.messageHandlers.has(messageType)) {
this.messageHandlers.set(messageType, []);
}
this.messageHandlers.get(messageType)?.push(callback);
return;
},
);
}
@ -109,16 +118,38 @@ export class MockIdeMessenger implements IIdeMessenger {
);
}
responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
chatStreamDelay: number = 0;
setChatResponseText(text: string): void {
this.chatResponse = [
{
role: "assistant",
content: text,
},
];
}
async *llmStreamChat(
msg: ToCoreProtocol["llm/streamChat"][0],
cancelToken: AbortSignal,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
yield [
{
role: "assistant",
content: "This is a test",
},
];
for (const response of this.chatResponse) {
if (cancelToken.aborted) {
console.log("MockIdeMessenger: Stream aborted");
return undefined;
}
console.log(
"MockIdeMessenger: Yielding chunk",
JSON.stringify(response, null, 2),
);
yield [response];
if (this.chatStreamDelay > 0) {
await new Promise((resolve) =>
setTimeout(resolve, this.chatStreamDelay),
);
}
}
return undefined;
}
@ -133,12 +164,16 @@ export class MockIdeMessenger implements IIdeMessenger {
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<WebviewSingleProtocolMessage<T>> {
const content = await defaultMockHandleMessage(messageType, data);
return {
status: "success",
content,
done: true,
};
if (messageType in this.responses) {
const content = this.responses[messageType];
return {
status: "success",
content,
done: true,
};
}
console.error(messageType);
throw new Error("MockIdeMessenger: No response defined for " + messageType);
}
respond<T extends keyof ToWebviewProtocol>(
@ -157,4 +192,10 @@ export class MockIdeMessenger implements IIdeMessenger {
> {
return undefined;
}
resetMocks(): void {
this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
this.chatResponse = DEFAULT_CHAT_RESPONSE;
this.chatStreamDelay = 0;
}
}

View file

@ -20,6 +20,7 @@ import {
import {
acceptToolCall,
addContextItemsAtIndex,
selectCurrentToolCall,
setHasReasoningEnabled,
updateApplyState,
} from "../redux/slices/sessionSlice";
@ -244,6 +245,10 @@ function ParallelListeners() {
dispatch(updateIndexingStatus(data));
});
const autoAcceptEditToolDiffs = useAppSelector(
(store) => store.config.config.ui?.autoAcceptEditToolDiffs,
);
const currentToolCall = useAppSelector(selectCurrentToolCall);
useWebviewListener(
"updateApplyState",
async (state) => {
@ -259,30 +264,45 @@ function ParallelListeners() {
// Handle apply status updates that are associated with current tool call
if (
state.status === "closed" &&
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
if (state.status === "done" && autoAcceptEditToolDiffs) {
console.log("AUTO ACCEPTED");
ideMessenger.post("acceptDiff", {
streamId: state.streamId,
filepath: state.filepath,
});
}
if (state.status === "closed") {
if (currentToolCall?.status !== "canceled") {
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
// dispatch(setToolCallOutput([]));
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
}
}
},
[currentToolCallApplyState, history],
[
currentToolCall,
currentToolCallApplyState,
autoAcceptEditToolDiffs,
ideMessenger,
],
);
useEffect(() => {

View file

@ -1,161 +0,0 @@
import { screen, waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { renderWithProviders } from "../../util/test/render";
import { Chat } from "./Chat";
describe("Chat page test", () => {
it("should render input box", async () => {
await renderWithProviders(<Chat />);
expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument();
});
it("should be able to toggle modes", async () => {
await renderWithProviders(<Chat />);
expect(screen.getByText("Chat")).toBeInTheDocument();
// Simulate cmd+. keyboard shortcut to toggle modes
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// Check that it switched to Agent mode
expect(await screen.findByText("Agent")).toBeInTheDocument();
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// 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 () => {
const { user, container } = await renderWithProviders(<Chat />);
const inputBox = await waitFor(() =>
container.querySelector(".ProseMirror")!.querySelector("p"),
);
expect(inputBox).toBeDefined();
const sendButton = await screen.findByTestId("submit-input-button");
await act(async () => {
// Focus input box
inputBox!.focus();
// Type message
await user.type(inputBox!, "Hello, world!");
sendButton.click();
});
expect(await screen.findByText("Hello, world!")).toBeInTheDocument();
});
it("should handle apply updates and display the accept / reject all buttons", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Use queryByText which returns null when element isn't found
const acceptAllButton = screen.queryByText("Accept All");
const rejectAllButton = screen.queryByText("Reject All");
// Assert that the buttons don't exist
expect(acceptAllButton).not.toBeInTheDocument();
expect(rejectAllButton).not.toBeInTheDocument();
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId: "12345",
});
// Wait for the buttons to appear
await waitFor(() => {
expect(
screen.getByTestId("accept-reject-all-buttons"),
).toBeInTheDocument();
});
// IDE sends back message that it is done
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
// Wait for the buttons to disappear
await waitFor(() => {
expect(
screen.queryByTestId("edit-accept-button"),
).not.toBeInTheDocument();
expect(
screen.queryByTestId("edit-reject-button"),
).not.toBeInTheDocument();
});
});
it("should show apply cancellation", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Spy on the request method of ideMessenger
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
// Wait for applying toolbar to appear
await waitFor(() => {
const cancelApplyButton = screen.getByTestId(
"notch-applying-cancel-button",
);
const applyingText = screen.getByTestId("notch-applying-text");
expect(cancelApplyButton).toBeInTheDocument();
expect(applyingText).toBeInTheDocument();
});
const cancelApplyButton = screen.getByTestId(
"notch-applying-cancel-button",
);
cancelApplyButton.click();
// Verify that rejectDiff message has been posted to ideMessenger
expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
// Now simulate the IDE sending back a message that the apply state is closed
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
await waitFor(() => {
const cancelApplyButton = screen.queryByTestId(
"notch-applying-cancel-button",
);
const applyingText = screen.queryByTestId("notch-applying-text");
expect(cancelApplyButton).not.toBeInTheDocument();
expect(applyingText).not.toBeInTheDocument();
});
// Cleanup spy
messengerPostSpy.mockRestore();
});
});

View file

@ -1,12 +1,5 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
selectApplyStateByToolCallId,
updateApplyState,
} from "../../../redux/slices/sessionSlice";
type EditToolCallProps = {
relativeFilePath: string;
@ -17,24 +10,6 @@ type EditToolCallProps = {
};
export function EditFile(props: EditToolCallProps) {
const dispatch = useAppDispatch();
const applyState = useAppSelector((state) =>
selectApplyStateByToolCallId(state, props.toolCallId),
);
useEffect(() => {
if (!applyState) {
dispatch(
updateApplyState({
streamId: uuidv4(),
toolCallId: props.toolCallId,
status: "not-started",
}),
);
}
}, [applyState, props.toolCallId]);
if (!props.relativeFilePath || !props.changes) {
return null;
}
@ -47,7 +22,7 @@ export function EditFile(props: EditToolCallProps) {
isRenderingInStepContainer
disableManualApply
source={src}
forceStreamId={applyState?.streamId}
toolCallId={props.toolCallId}
itemIndex={props.historyIndex}
/>
);

View file

@ -0,0 +1,80 @@
import { act } from "@testing-library/react";
import { renderWithProviders } from "../../../util/test/render";
import {
getElementByTestId,
verifyNotPresentByTestId,
verifyNotPresentByText,
} from "../../../util/test/utils";
import { Chat } from "../Chat";
test("Chat apply scenarios: handle apply updates and display the accept / reject all buttons", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Use queryByText which returns null when element isn't found
await verifyNotPresentByText("Accept All");
await verifyNotPresentByText("Reject All");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId: "12345",
});
// Wait for the buttons to appear
await getElementByTestId("accept-reject-all-buttons");
// IDE sends back message that it is done
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
// Wait for the buttons to disappear
await verifyNotPresentByTestId("edit-accept-button");
await verifyNotPresentByTestId("edit-reject-button");
});
test("Chat apply scenarios: show apply cancellation", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Spy on the request method of ideMessenger
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
// Wait for applying toolbar to appear
await getElementByTestId("notch-applying-text");
await act(async () => {
const cancelApplyButton = await getElementByTestId(
"notch-applying-cancel-button",
);
cancelApplyButton.click();
});
// Verify that rejectDiff message has been posted to ideMessenger
expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
// Now simulate the IDE sending back a message that the apply state is closed
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
await verifyNotPresentByTestId("notch-applying-text");
await verifyNotPresentByTestId("notch-applying-cancel-button");
// Cleanup spy
messengerPostSpy.mockRestore();
});

View file

@ -0,0 +1,61 @@
import { act } from "@testing-library/react";
import { addAndSelectMockLlm } from "../../../util/test/config";
import { renderWithProviders } from "../../../util/test/render";
import {
getElementByTestId,
getElementByText,
sendInputWithMockedResponse,
} from "../../../util/test/utils";
import { Chat } from "../Chat";
test("should render input box", async () => {
await renderWithProviders(<Chat />);
await getElementByTestId("continue-input-box");
});
test("should be able to toggle modes", async () => {
await renderWithProviders(<Chat />);
await getElementByText("Chat");
// Simulate cmd+. keyboard shortcut to toggle modes
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// Check that it switched to Agent mode
await getElementByText("Agent");
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
await getElementByText("Chat");
});
test("should send a message and receive a response", async () => {
const { ideMessenger, store } = await renderWithProviders(<Chat />);
// First add and select the mock LLM
await act(async () => {
addAndSelectMockLlm(store, ideMessenger);
});
const CONTENT = "Expected response";
const INPUT = "User input";
await sendInputWithMockedResponse(ideMessenger, INPUT, [
{ role: "assistant", content: CONTENT },
]);
await getElementByText(CONTENT);
});

View file

@ -0,0 +1,231 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import {
addAndSelectMockLlm,
triggerConfigUpdate,
} from "../../../util/test/config";
import { renderWithProviders } from "../../../util/test/render";
import { Chat } from "../Chat";
import { waitFor } from "@testing-library/dom";
import { ChatMessage } from "core";
import { toggleToolSetting } from "../../../redux/slices/uiSlice";
import {
getElementByTestId,
getElementByText,
sendInputWithMockedResponse,
verifyNotPresentByTestId,
} from "../../../util/test/utils";
const EDIT_WORKSPACE_DIR = "file:///workspace";
const EDIT_FILEPATH = "test.txt";
const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`;
const EDIT_CHANGES = "New content";
const EDIT_TOOL_CALL_ID = "known-id";
const EDIT_MESSAGES: ChatMessage[] = [
{
role: "assistant",
content: "",
toolCalls: [
{
id: EDIT_TOOL_CALL_ID,
function: {
name: BuiltInToolNames.EditExistingFile,
arguments: JSON.stringify({
filepath: EDIT_FILEPATH,
changes: EDIT_CHANGES,
}),
},
},
],
},
];
const POST_EDIT_RESPONSE = "Edit applied successfully";
beforeEach(() => {
vi.clearAllMocks();
});
test("Edit run with ask first policy and no auto apply", async () => {
// Setup
const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
addAndSelectMockLlm(store, ideMessenger);
// Send the input that will respond with an edit tool call
await sendInputWithMockedResponse(
ideMessenger,
"Edit this file",
EDIT_MESSAGES,
);
// Toggle the codeblock and make sure the changes show
const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock");
await user.click(toggleCodeblockChevron);
await getElementByText(EDIT_CHANGES);
// Pending tool call - find and click the accept button
const acceptToolCallButton = await getElementByTestId(
"accept-tool-call-button",
);
await user.click(acceptToolCallButton);
// Tool call, check that applyToFile was called for edit
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
streamId: expect.any(String),
filepath: EDIT_FILE_URI,
text: EDIT_CHANGES,
toolCallId: EDIT_TOOL_CALL_ID,
});
});
// Extract stream ID and initiate mock streaming
const streamId = messengerPostSpy.mock.calls.find(
(call) => call[0] === "applyToFile",
)?.[1]?.streamId;
expect(streamId).toBeDefined();
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
// Mid stream, should show applying in notch
await getElementByTestId("notch-applying-text");
await getElementByTestId("notch-applying-cancel-button");
// Close the stream
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
// Verify accept/reject buttons are present
const acceptButton = await getElementByTestId("edit-accept-button");
await getElementByTestId("edit-reject-button");
// Accept the changes, which should trigger a response after the tool call
await user.click(acceptButton);
expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", {
streamId,
filepath: EDIT_FILE_URI,
});
ideMessenger.setChatResponseText(POST_EDIT_RESPONSE);
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
await verifyNotPresentByTestId("edit-accept-button");
await verifyNotPresentByTestId("edit-reject-button");
await getElementByText(POST_EDIT_RESPONSE);
});
test("Edit run with no policy and yolo mode", async () => {
// Setup
const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
addAndSelectMockLlm(store, ideMessenger);
// Enable automatic edit and yolo mode
store.dispatch(toggleToolSetting(BuiltInToolNames.EditExistingFile));
triggerConfigUpdate({
store,
ideMessenger,
editConfig: (current) => {
current.ui = {
...current.ui,
autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs
};
return current;
},
});
expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true);
// Send the input that will respond with an edit tool call
await sendInputWithMockedResponse(
ideMessenger,
"Edit this file",
EDIT_MESSAGES,
);
// Toggle the codeblock and make sure the changes show
const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock");
await user.click(toggleCodeblockChevron);
await getElementByText(EDIT_CHANGES);
// Make sure there's no pending tool call
verifyNotPresentByTestId("accept-tool-call-button");
// Tool call, check that applyToFile was called for edit
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
streamId: expect.any(String),
filepath: EDIT_FILE_URI,
text: EDIT_CHANGES,
toolCallId: EDIT_TOOL_CALL_ID,
});
});
// Extract stream ID and initiate mock streaming
const streamId = messengerPostSpy.mock.calls.find(
(call) => call[0] === "applyToFile",
)?.[1]?.streamId;
expect(streamId).toBeDefined();
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
// Mid stream, should show applying in notch
await getElementByTestId("notch-applying-text");
await getElementByTestId("notch-applying-cancel-button");
// Close the stream
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", {
streamId,
filepath: EDIT_FILE_URI,
});
});
// Close the stream, ensure response is shown and diff buttons are not present
ideMessenger.setChatResponseText(POST_EDIT_RESPONSE);
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
await verifyNotPresentByTestId("edit-accept-button");
await verifyNotPresentByTestId("edit-reject-button");
await getElementByText(POST_EDIT_RESPONSE);
});

View file

@ -657,7 +657,9 @@ export const selectApplyStateByToolCallId = createSelector(
(state: RootState, toolCallId?: string) => toolCallId,
],
(states, toolCallId) => {
return states.find((state) => state.toolCallId === toolCallId);
if (toolCallId) {
return states.find((state) => state.toolCallId === toolCallId);
}
},
);

View file

@ -23,11 +23,6 @@ import sessionReducer from "./slices/sessionSlice";
import tabsReducer from "./slices/tabsSlice";
import uiReducer from "./slices/uiSlice";
export interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
}
const rootReducer = combineReducers({
session: sessionReducer,
ui: uiReducer,

View file

@ -19,7 +19,6 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
async (_, { dispatch, extra, getState }) => {
const state = getState();
const toolCallState = selectCurrentToolCall(state);
if (!toolCallState) {
return;
}
@ -61,19 +60,15 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
) {
// Tool is called on client side
const {
output: clientToolOuput,
output: clientToolOutput,
respondImmediately,
errorMessage: clientToolError,
} = await callClientTool(toolCallState, {
dispatch,
ideMessenger: extra.ideMessenger,
streamId: state.session.codeBlockApplyStates.states.find(
(state) =>
state.toolCallId && state.toolCallId === toolCallState.toolCallId,
)?.streamId,
getState,
});
output = clientToolOuput;
output = clientToolOutput;
errorMessage = clientToolError;
streamResponse = respondImmediately;
} else {

View file

@ -17,6 +17,7 @@ import {
import {
newSession,
setActive,
setInactive,
setIsInEdit,
setMainEditorContentTrigger,
setMode,
@ -61,6 +62,8 @@ export const streamEditThunk = createAsyncThunk<
range: codeToEdit[0] as RangeInFileWithContents,
});
dispatch(setInactive());
if (response.status === "error") {
throw new Error(response.error);
}

View file

@ -8,6 +8,8 @@ import { selectSelectedChatModel } from "../slices/configSlice";
import {
abortStream,
addPromptCompletionPair,
setActive,
setInactive,
setToolGenerated,
streamUpdate,
} from "../slices/sessionSlice";
@ -53,6 +55,8 @@ export const streamNormalInput = createAsyncThunk<
};
}
dispatch(setActive());
// Send request
const gen = extra.ideMessenger.llmStreamChat(
{
@ -76,6 +80,8 @@ export const streamNormalInput = createAsyncThunk<
next = await gen.next();
}
dispatch(setInactive());
// Attach prompt log and end thinking for reasoning models
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));

View file

@ -4,11 +4,7 @@ import { constructMessages } from "core/llm/constructMessages";
import { renderContextItems } from "core/util/messageContent";
import { getBaseSystemMessage } from "../../util";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
addContextItemsAtIndex,
setActive,
streamUpdate,
} from "../slices/sessionSlice";
import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCall } from "../util";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
@ -63,8 +59,6 @@ export const streamResponseAfterToolCall = createAsyncThunk<
}),
);
dispatch(setActive());
const updatedHistory = getState().session.history;
const messageMode = getState().session.mode;

View file

@ -1,6 +1,5 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import StreamErrorDialog from "../../pages/gui/StreamError";
import { setInactive } from "../slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../slices/uiSlice";
import { ThunkApiType } from "../store";
import { cancelStream } from "./cancelStream";
@ -22,7 +21,6 @@ export const streamThunkWrapper = createAsyncThunk<
}),
);
}
dispatch(setInactive());
} catch (e) {
dispatch(cancelStream());
dispatch(setDialogMessage(<StreamErrorDialog error={e} />));

View file

@ -9,7 +9,6 @@ export interface ClientToolExtras {
getState: () => RootState;
dispatch: AppThunkDispatch;
ideMessenger: IIdeMessenger;
streamId?: string;
}
export interface ClientToolOutput {

View file

@ -1,14 +1,11 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { ClientToolImpl } from "./callClientTool";
export const editToolImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
if (!extras.streamId) {
throw new Error("Invalid apply state");
}
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
extras.ideMessenger.ide,
@ -16,30 +13,14 @@ export const editToolImpl: ClientToolImpl = async (
if (!firstUriMatch) {
throw new Error(`${args.filepath} does not exist`);
}
const apply = await extras.ideMessenger.request("applyToFile", {
streamId: extras.streamId,
const streamId = uuid();
extras.ideMessenger.post("applyToFile", {
streamId,
text: args.changes,
toolCallId,
filepath: firstUriMatch,
});
if (apply.status === "error") {
throw new Error(apply.error);
}
const state = extras.getState();
const autoAccept = !!state.config.config.ui?.autoAcceptEditToolDiffs;
if (autoAccept) {
const out = await extras.ideMessenger.request("acceptDiff", {
streamId: extras.streamId,
filepath: firstUriMatch,
});
if (out.status === "error") {
throw new Error(out.error);
}
return {
respondImmediately: true,
output: undefined, // TODO - feed edit results back to model (also in parallel listeners)
};
}
return {
respondImmediately: false,
output: undefined, // No immediate output.

View file

@ -0,0 +1,67 @@
import { EnhancedStore } from "@reduxjs/toolkit";
import { BrowserSerializedContinueConfig, ModelDescription } from "core";
import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
import { copyOf } from "core/util";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
interface TestConfigUpdateParams {
store: EnhancedStore;
ideMessenger: MockIdeMessenger;
newProfileId?: string;
newOrgId?: string;
newOrgs?: SerializedOrgWithProfiles[];
editConfig?: (
current: BrowserSerializedContinueConfig,
) => BrowserSerializedContinueConfig;
}
export function triggerConfigUpdate({
store,
ideMessenger,
editConfig,
newOrgs,
newOrgId,
newProfileId,
}: TestConfigUpdateParams) {
const state = store.getState();
ideMessenger.mockMessageToWebview("configUpdate", {
organizations: newOrgs ?? state.profiles.organizations,
selectedOrgId: newOrgId ?? state.profiles.selectedOrganizationId,
profileId: newProfileId ?? state.profiles.selectedProfileId,
result: {
config: editConfig
? editConfig(copyOf(state.config.config))
: state.config.config,
configLoadInterrupted: false,
errors: [],
},
});
}
export function addAndSelectChatModel(
store: EnhancedStore,
ideMessenger: MockIdeMessenger,
llmDesc: ModelDescription,
) {
triggerConfigUpdate({
store,
ideMessenger,
editConfig(current) {
current.modelsByRole.chat.push(llmDesc);
current.selectedModelByRole.chat = llmDesc;
return current;
},
});
}
export function addAndSelectMockLlm(
store: EnhancedStore,
ideMessenger: MockIdeMessenger,
) {
addAndSelectChatModel(store, ideMessenger, {
model: "mock",
provider: "mock",
title: "Mock LLM",
underlyingProviderName: "mock",
});
}

102
gui/src/util/test/utils.ts Normal file
View file

@ -0,0 +1,102 @@
import { screen, waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { Editor } from "@tiptap/core";
import { ChatMessage } from "core";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
function logDomText() {
const bodyText = document.body.innerHTML;
const parser = new DOMParser();
const doc = parser.parseFromString(bodyText, "text/html");
let cleaned = doc.body.textContent ?? "";
cleaned = cleaned?.replace(
"No resultsAaModelsRulesDocsPromptsToolsMCPCreate your first assistant",
"",
);
cleaned = cleaned?.replace(
"Alt⏎ Active file⏎ Enter⏎Log in to access a free trial of theModels Add-OnLog in to Continue HubOr, configure your own models",
"",
);
cleaned = cleaned.replaceAll("Select model", "");
cleaned = cleaned.replaceAll("Mock LLM", "");
cleaned = cleaned.replaceAll(/^Chat|Chat$/g, "");
console.log(cleaned || "No body content");
}
export function logAllTestIds() {
const elements = document.querySelectorAll("*");
const testIds = Array.from(elements)
.map((el) => Array.from(el.attributes))
.flat()
.filter((a) => a.name === "data-testid")
.map((a) => a.value);
console.log("Available test ids", testIds);
}
export async function getElementByTestId(testId: string): Promise<HTMLElement> {
try {
const testIdElement = await waitFor(() => screen.findByTestId(testId));
expect(testIdElement).toBeInTheDocument();
return testIdElement;
} catch (e) {
logAllTestIds();
throw new Error(`Element with testId "${testId}" not found`);
}
}
export async function verifyNotPresentByTestId(testId: string): Promise<void> {
const element = await waitFor(() => screen.queryByTestId(testId));
expect(element).not.toBeInTheDocument();
}
export async function verifyNotPresentByText(text: string): Promise<void> {
const element = screen.queryByText(text);
expect(element).not.toBeInTheDocument();
}
export async function getElementByText(text: string): Promise<HTMLElement> {
try {
const textElement = await waitFor(() => screen.findByText(text));
expect(textElement).toBeInTheDocument();
return textElement;
} catch (e) {
logDomText();
throw new Error(`Element with text "${text}" not found.`);
}
}
export async function getMainEditor(): Promise<Editor> {
const editorElement = await getElementByTestId("editor-input-main");
if ("editor" in editorElement) {
return editorElement.editor as Editor;
} else {
throw new Error("Main editor not found within editor container");
}
}
export async function sendInputWithMockedResponse(
ideMessenger: MockIdeMessenger,
input: string,
response: ChatMessage[],
): Promise<void> {
// Setup the mock response before any actions
ideMessenger.chatResponse = response;
// Wait for the editor to be in the document
const editor = await getMainEditor();
// Find the submit button
const sendButton = await getElementByTestId("submit-input-button");
// Insert content into the editor
await act(async () => {
editor.commands.insertContent(input);
});
await getElementByText(input);
// Click the send button
await act(async () => {
sendButton.click();
});
}

View file

@ -32,5 +32,18 @@ export default defineConfig({
globals: true,
environment: "jsdom",
setupFiles: "./src/util/test/setupTests.ts",
onConsoleLog(log, type) {
if (type === "stderr") {
if (
[
"contentEditable",
"An update to Chat inside a test was not wrapped in act",
].some((text) => log.includes(text))
) {
return false;
}
}
return true;
},
},
});

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.94",
"version": "1.0.95",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -13,7 +13,7 @@
}
},
"bin": {
"@continuedev/config-yaml": "./dist/cli.js"
"config-yaml": "./dist/cli.js"
},
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
@ -34,6 +34,11 @@
"jest": "^29.7.0",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2",
"zod-to-json-schema": "^3.24.5"
"zod-to-json-schema": "^3.24.5",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"semantic-release": "^21.1.2"
}
}

View file

@ -1,9 +1,3 @@
export default {
branches: ["main"],
plugins: [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/npm",
"@semantic-release/github",
],
};
import createReleaseConfig from "../shared-release.config.js";
export default createReleaseConfig("config-yaml");

View file

@ -0,0 +1,3 @@
import createReleaseConfig from "../shared-release.config.js";
export default createReleaseConfig("fetch");

View file

@ -0,0 +1,3 @@
import createReleaseConfig from "../shared-release.config.js";
export default createReleaseConfig("llm-info");

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.40",
"version": "1.0.42",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.40",
"version": "1.0.42",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.40",
"version": "1.0.42",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -0,0 +1,3 @@
import createReleaseConfig from "../shared-release.config.js";
export default createReleaseConfig("openai-adapters");

View file

@ -63,7 +63,11 @@ export class AzureApi extends OpenAIApi {
"`env.apiVersion` is a required configuration property for Azure OpenAI",
);
}
url.pathname = `${url.pathname}/openai/deployments/${config.env.deployment}`;
const basePathname = `openai/deployments/${config.env.deployment}`;
url.pathname =
url.pathname === "/" ? basePathname : `${url.pathname}/${basePathname}`;
queryParams["api-version"] = config.env.apiVersion;
}

View file

@ -173,4 +173,80 @@ describe("Configuration", () => {
"https://api.example.com",
);
});
it("should configure Azure OpenAI client with root URL and trailing slash", () => {
const azure = constructLlmApi({
provider: "azure",
apiKey: "sk-xxx",
apiBase: "https://test-azure-openai.azure.com/",
env: {
deployment: "gpt-4.1",
apiType: "azure-openai",
apiVersion: "2023-05-15",
},
});
// The Azure client modifies the baseURL to include the deployment
expect((azure as OpenAIApi).openai.baseURL).toBe(
"https://test-azure-openai.azure.com/openai/deployments/gpt-4.1",
);
expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx");
});
it("should configure Azure OpenAI client with path and trailing slash", () => {
const azure = constructLlmApi({
provider: "azure",
apiKey: "sk-xxx",
apiBase: "https://test-azure-openai.azure.com/v1/",
env: {
deployment: "gpt-4.1",
apiType: "azure-openai",
apiVersion: "2023-05-15",
},
});
// The Azure client modifies the baseURL to include the deployment
expect((azure as OpenAIApi).openai.baseURL).toBe(
"https://test-azure-openai.azure.com/v1/openai/deployments/gpt-4.1",
);
expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx");
});
it("should configure Azure OpenAI client with root URL and no trailing slash", () => {
const azure = constructLlmApi({
provider: "azure",
apiKey: "sk-xxx",
apiBase: "https://test-azure-openai.azure.com",
env: {
deployment: "gpt-4.1",
apiType: "azure-openai",
apiVersion: "2023-05-15",
},
});
// The Azure client modifies the baseURL to include the deployment
expect((azure as OpenAIApi).openai.baseURL).toBe(
"https://test-azure-openai.azure.com/openai/deployments/gpt-4.1",
);
expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx");
});
it("should configure Azure OpenAI client with path and no trailing slash", () => {
const azure = constructLlmApi({
provider: "azure",
apiKey: "sk-xxx",
apiBase: "https://test-azure-openai.azure.com/v1",
env: {
deployment: "gpt-4.1",
apiType: "azure-openai",
apiVersion: "2023-05-15",
},
});
// The Azure client modifies the baseURL to include the deployment
expect((azure as OpenAIApi).openai.baseURL).toBe(
"https://test-azure-openai.azure.com/v1/openai/deployments/gpt-4.1",
);
expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx");
});
});

View file

@ -0,0 +1,34 @@
export default function createReleaseConfig(packageName) {
return {
branches: ["main"],
tagFormat: `@continuedev/${packageName}@\${version}`,
plugins: [
[
"@semantic-release/commit-analyzer",
{
releaseRules: [
{ scope: `packages/${packageName}`, release: "patch" },
{ scope: `packages/${packageName}`, type: "fix", release: "patch" },
{ scope: "packages/config-yaml", type: "feat", release: "minor" },
{
scope: `packages/${packageName}`,
breaking: true,
release: "major",
},
],
},
],
"@semantic-release/release-notes-generator",
"@semantic-release/changelog",
"@semantic-release/npm",
[
"@semantic-release/git",
{
assets: ["CHANGELOG.md", "package.json"],
message: `chore(release): @continuedev/${packageName}@\${nextRelease.version} [skip ci]`,
},
],
"@semantic-release/github",
],
};
}

13
scripts/build-packages.ps1 Executable file
View file

@ -0,0 +1,13 @@
Push-Location packages
Push-Location "openai-adapters"
npm ci
npm run build
Pop-Location
Push-Location "config-yaml"
npm ci
npm run build
Pop-Location
Pop-Location

13
scripts/build-packages.sh Executable file
View file

@ -0,0 +1,13 @@
# Build @continuedev packages for monorepo style linking
cd packages
cd openai-adapters
npm ci
npm run build
cd ..
cd config-yaml
npm ci
npm run build

View file

@ -0,0 +1,35 @@
# create the docker file
cat > Dockerfile << 'EOF'
FROM ubuntu:latest
ENV DEBIAN_FRONTEND=noninteractive
# Install SSH server
RUN apt-get update && apt-get install -y openssh-server
# Configure SSH
RUN mkdir /var/run/sshd
RUN echo 'root:my_password' | chpasswd
# Allow root login
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
EOF
docker build -t continue-ubuntu-ssh . # build the image
rm Dockerfile # remove the created Dockerfile
container_name="continue-ssh-container"
docker run -d -p 2222:22 --name $container_name continue-ubuntu-ssh # run the container
echo "docker container ${container_name} running on port 2222"
# add the instructions
bold=$(tput bold)
normal=$(tput sgr0)
echo "\n--------------------------------------"
echo "now ssh into vscode (using remote explorer) with the following command: ${bold}ssh root@localhost -p 2222${normal}"
echo "use the following password - \"${bold}my_password${normal}\""