Merge branch 'main' of https://github.com/continuedev/continue into nate/cli-troubleshooting-section

This commit is contained in:
Dallin Romney 2025-08-05 13:19:25 -07:00
commit c29210dbc6
105 changed files with 2488 additions and 507 deletions

View file

@ -18,6 +18,9 @@ inputs:
description: 'Commit SHA for version modification (optional, uses first 7 chars)'
required: false
default: ''
github-token:
description: 'GitHub token for downloading ripgrep'
required: true
outputs:
target:
description: 'The target string used for the build'
@ -83,7 +86,7 @@ runs:
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ env.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ inputs.github-token }}
- name: Install gui dependencies
shell: bash
@ -98,6 +101,12 @@ runs:
npm ci
npm i vectordb
- name: Build GUI
shell: bash
run: |
cd gui
npm run build
- name: Prepackage the extension
shell: bash
run: |

View file

@ -28,6 +28,13 @@ runs:
cd core
npm ci
- name: Install gui node_modules and build
shell: bash
run: |
cd gui
npm ci
npm run build
- name: Setup Java
uses: actions/setup-java@v4.5.0
with:

View file

@ -14,7 +14,7 @@ jobs:
uses: pozil/auto-assign-issue@v2
with:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa
assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai
numOfAssignee: 1
# - name: "Add default labels"
# uses: actions-ecosystem/action-add-labels@v1

View file

@ -80,8 +80,7 @@ jobs:
arch: ${{ matrix.arch }}
npm_config_arch: ${{ matrix.npm_config_arch }}
pre-release: false
env:
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload .vsix artifact
uses: actions/upload-artifact@v4

View file

@ -36,8 +36,7 @@ jobs:
npm_config_arch: ${{ matrix.arch }}
pre-release: false
commit-sha: ${{ github.sha }}
env:
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload build artifact
uses: actions/upload-artifact@v4

View file

@ -269,8 +269,7 @@ jobs:
npm_config_arch: x64
pre-release: false
commit-sha: ${{ github.sha }}
env:
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload build artifact
uses: actions/upload-artifact@v4

View file

@ -80,8 +80,7 @@ jobs:
arch: ${{ matrix.arch }}
npm_config_arch: ${{ matrix.npm_config_arch }}
pre-release: true
env:
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload .vsix artifact
uses: actions/upload-artifact@v4

View file

@ -10,6 +10,11 @@ extensions/vscode/.vscode-test
extensions/vscode/bin
extensions/vscode/build
extensions/vscode/out
extensions/vscode/gui
extensions/vscode/e2e/.test-extensions
extensions/vscode/e2e/test-continue
extensions/vscode/models
extensions/intellij/src/main/resources
gui/dist
**/.continueignore
CHANGELOG.md
@ -19,7 +24,4 @@ CHANGELOG.md
core/vendor
coverage
e2e
extensions/vscode/gui
extensions/vscode/models
extensions/intellij/src/main/resources
packages/continue-sdk

132
.vscode/tasks.json vendored
View file

@ -12,24 +12,18 @@
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "new"
"group": "dev-watchers",
"panel": "dedicated",
"reveal": "always"
}
},
// Compile and bundle the extension
{
"label": "vscode-extension:build",
"dependsOn": [
// TSC type checking
"tsc:watch",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
// // To bundle the code the same way we do for publishing
"vscode-extension:esbuild",
// To ensure extension.js is regenerated even if
// vscode-extension:esbuild was already running in background
"vscode-extension:esbuild-notify",
// Start the React app that is used in the extension
"gui:dev"
],
"group": {
@ -42,7 +36,15 @@
"dependsOn": ["vscode-extension:esbuild"],
"type": "npm",
"script": "esbuild-notify",
"path": "extensions/vscode"
"path": "extensions/vscode",
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "silent",
"revealProblems": "onProblem",
"close": true,
"clear": true
}
},
{
"label": "vscode-extension:esbuild",
@ -51,6 +53,11 @@
"script": "esbuild-watch",
"path": "extensions/vscode",
"isBackground": true,
"presentation": {
"group": "dev-watchers",
"panel": "dedicated",
"reveal": "silent"
},
"problemMatcher": [
{
"pattern": [
@ -77,6 +84,11 @@
"type": "npm",
"script": "package",
"path": "extensions/vscode",
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "always"
},
"problemMatcher": [
{
"pattern": [
@ -99,7 +111,11 @@
"args": ["${workspaceFolder}/extensions/vscode/scripts/prepackage.js"],
"problemMatcher": ["$tsc"],
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "silent",
"revealProblems": "onProblem",
"close": true,
"clear": true
},
"options": {
@ -109,16 +125,18 @@
"cwd": "${workspaceFolder}/extensions/vscode"
}
},
// Install or update all dependencies for all projects in the monrepo
{
"label": "install-all-dependencies",
"type": "shell",
"windows": { "command": "./scripts/install-dependencies.ps1" },
"command": "./scripts/install-dependencies.sh",
"problemMatcher": [] // Empty so users are not prompted to select progress reporting
"problemMatcher": [],
"presentation": {
"group": "maintenance",
"panel": "shared",
"reveal": "always"
}
},
//
// Start the React App for debugging with Vite
{
"label": "gui:dev",
"type": "shell",
@ -128,6 +146,16 @@
},
"args": ["run", "dev"],
"isBackground": true,
"runOptions": {
"instanceLimit": 1
},
"presentation": {
"group": "dev-watchers",
"panel": "dedicated",
"reveal": "always",
"focus": false,
"showReuseMessage": false
},
"problemMatcher": [
{
"pattern": [
@ -146,14 +174,17 @@
}
]
},
//
// esbuild for the core binary
{
"label": "binary:esbuild",
"type": "shell",
"command": "npm",
"args": ["run", "esbuild"],
"problemMatcher": [],
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "always"
},
"options": {
"cwd": "binary"
}
@ -164,6 +195,11 @@
"command": "npm",
"args": ["run", "start", "--", "--no-open"],
"problemMatcher": [],
"presentation": {
"group": "docs",
"panel": "dedicated",
"reveal": "always"
},
"options": {
"cwd": "docs"
}
@ -173,7 +209,12 @@
"type": "shell",
"command": "node",
"args": ["${workspaceFolder}/scripts/uninstall.js"],
"problemMatcher": []
"problemMatcher": [],
"presentation": {
"group": "maintenance",
"panel": "shared",
"reveal": "always"
}
},
{
"label": "refresh-dependencies:core",
@ -185,6 +226,9 @@
"cwd": "${workspaceFolder}/core"
},
"presentation": {
"group": "maintenance",
"panel": "shared",
"reveal": "silent",
"close": true
}
},
@ -198,6 +242,9 @@
"cwd": "${workspaceFolder}/extensions/vscode"
},
"presentation": {
"group": "maintenance",
"panel": "shared",
"reveal": "silent",
"close": true
}
},
@ -211,6 +258,9 @@
"cwd": "${workspaceFolder}/gui"
},
"presentation": {
"group": "maintenance",
"panel": "shared",
"reveal": "silent",
"close": true
}
},
@ -222,35 +272,45 @@
"refresh-dependencies:vscode"
],
"type": "shell",
"problemMatcher": []
"problemMatcher": [],
"presentation": {
"group": "maintenance",
"panel": "shared",
"reveal": "always"
}
},
{
"label": "Build Continue packages",
"label": "continue-packages:build",
"type": "shell",
"command": "node ./scripts/build-packages.js",
"isBackground": true,
"problemMatcher": {
"pattern": {
"regexp": "__DUMMY_PATTERN_THAT_NEVER_MATCHES__",
"file": 1
},
"background": {
"activeOnStart": true,
"beginsPattern": ".",
"endsPattern": "."
}
},
"problemMatcher": [],
"presentation": {
"reveal": "silent",
"panel": "shared"
"group": "build-tasks",
"panel": "shared",
"reveal": "always",
"close": true,
"revealProblems": "onProblem"
}
},
{
"label": "vscode-extension:build-with-packages",
// "dependsOn": ["vscode-extension:build"],
"dependsOn": ["Build Continue packages", "vscode-extension:build"],
"dependsOn": ["continue-packages:build", "vscode-extension:build"],
"type": "shell",
"problemMatcher": []
"command": "echo",
"args": ["Build with packages completed"],
"problemMatcher": [],
"dependsOrder": "sequence",
"runOptions": {
"instanceLimit": 1,
"reevaluateOnRerun": true
},
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "silent",
"close": true,
"focus": false
}
}
]
}

View file

@ -20,19 +20,19 @@
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
- [Our Git Workflow](#our-git-workflow)
- [Development workflow](#development-workflow)
- [Development Workflow](#development-workflow)
- [Formatting](#formatting)
- [Theme Colors](#theme-colors)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
- [Getting Help](#getting-help)
- [Contributing new LLM Providers/Models](#contributing-new-llm-providersmodels)
- [Adding an LLM Provider](#adding-an-llm-provider)
- [Adding Models](#adding-models)
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
- [Continue JetBrains Extension](#continue-jetbrains-extension)
- [Contibutor License Agreement](#contributor-license-agreement-cla)
- [Contributor License Agreement](#contributor-license-agreement-cla)
# ❤️ Ways to Contribute
@ -212,17 +212,17 @@ Guidelines for using theme colors:
Guidelines for adding/updating theme colors:
- Choose sensible VS Code variables to add/update in [gui/src/styles/theme.ts](gui/src/styles/theme.ts) (see [here](https://code.visualstudio.com/api/references/theme-color) and [here](https://www.notion.so/1fa1d55165f78097b551e3bc296fcf76?pvs=25) for inspiration)
- Choose sensible Jetbrains named colors to add/update in `GetTheme.kt` (flagship LLMs can give you good suggestions to try)
- Choose sensible JetBrains named colors to add/update in `GetTheme.kt` (flagship LLMs can give you good suggestions to try)
- Update `tailwind.config.js` if needed
- Use the Theme Test Page to check colors. This can be accessed by going to `Settings` -> `Help` -> `Theme Test Page` in dev/debug mode.
### Testing
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on
each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we
each pull request. If your PR causes one of these tests to fail, we will ask you to resolve the issue before we
merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementation.
### Review Process
@ -231,11 +231,11 @@ When contributing, please update or create the appropriate tests to help verify
maintainable and follows our patterns.
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
### Getting help
### Getting Help
Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with maintainers and other contributors.
## Contribtuing new LLM Providers/Models
## Contributing New LLM Providers/Models
### Adding an LLM Provider

View file

@ -1,4 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../control-plane/client.js";
import {
@ -46,7 +46,7 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
totalConfigLoads: number = 0;
totalConfigReloads: number = 0;
public isInitialized: Promise<void>;
private initter: EventEmitter;
@ -121,7 +121,7 @@ export class ConfigHandler {
this.workspaceDirs = null; // forces workspace dirs reload
try {
const orgs = await this.getOrgs();
const { orgs, errors } = await this.getOrgs();
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
@ -136,21 +136,20 @@ export class ConfigHandler {
// note, ignoring case of zero orgs since should never happen
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
if (currentSelection) {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
} else {
selectedOrg = fallback;
}
if (signal.aborted) {
return; // local only case, no`fetch to throw abort error
}
this.initter.emit("init");
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
@ -161,28 +160,52 @@ export class ConfigHandler {
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig(reason);
await this.reloadConfig(reason, errors);
} catch (e) {
if (e instanceof Error && e.message.includes("AbortError")) {
if (signal.aborted) {
return;
} else {
this.initter.emit("init"); // Error case counts for initialization
this.initter.emit("init"); // Error case counts as init
throw e;
}
}
}
private async getOrgs(): Promise<OrgWithProfiles[]> {
private async getOrgs(): Promise<{
orgs: OrgWithProfiles[];
errors?: ConfigValidationError[];
}> {
const errors: ConfigValidationError[] = [];
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
return orgs;
} else {
return [await this.getLocalOrg()];
try {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
// TODO make try/catch more granular here, to catch specific org errors
return { orgs };
} catch (e) {
errors.push({
fatal: false,
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
}
}
// Load local org if not signed in or hub orgs fail
try {
const orgs = [await this.getLocalOrg()];
return { orgs };
} catch (e) {
errors.push({
fatal: true,
message: `Error loading local assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
return {
orgs: [],
errors,
};
}
}
@ -276,9 +299,7 @@ export class ConfigHandler {
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
let currentProfile: ProfileLifecycleManager | null;
if (!currentSelection) {
currentProfile = fallback;
} else {
if (currentSelection) {
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
@ -287,6 +308,8 @@ export class ConfigHandler {
} else {
currentProfile = fallback;
}
} else {
currentProfile = fallback;
}
if (currentProfile) {
@ -348,8 +371,8 @@ export class ConfigHandler {
// External actions that can cause a cascading config refresh
// Should not be used internally
//////////////////
async refreshAll() {
await this.cascadeInit("External refresh all");
async refreshAll(reason?: string) {
await this.cascadeInit(reason ?? "External refresh all");
}
// Ide settings change: refresh session and cascade refresh from the top
@ -460,14 +483,17 @@ export class ConfigHandler {
// IMPORTANT - must always refresh when switching profiles
// Because of e.g. MCP singleton and docs service using things from config
// Could improve this
async reloadConfig(reason: string) {
async reloadConfig(reason: string, injectErrors?: ConfigValidationError[]) {
const startTime = performance.now();
this.totalConfigLoads += 1;
this.totalConfigReloads += 1;
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
if (!this.currentProfile) {
return {
config: undefined,
errors: [{ message: "Current profile not found", fatal: true }],
errors: [
{ message: "Current profile not found", fatal: true },
...(injectErrors ?? []),
],
configLoadInterrupted: true,
};
}
@ -483,22 +509,35 @@ export class ConfigHandler {
}
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig(this.additionalContextProviders);
const {
config,
errors = [],
configLoadInterrupted,
} = await this.currentProfile.reloadConfig(this.additionalContextProviders);
if (injectErrors) {
errors.unshift(...injectErrors);
}
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
this.initter.emit("init");
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
duration,
reason,
totalConfigLoads: this.totalConfigLoads,
totalConfigLoads: this.totalConfigReloads,
configLoadInterrupted,
});
return { config, errors, configLoadInterrupted };
return {
config,
errors: errors.length ? errors : undefined,
configLoadInterrupted,
};
}
// Listeners setup - can listen to current profile updates

View file

@ -18,6 +18,7 @@ import {
SlashCommandDescWithSource,
Tool,
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
@ -216,15 +217,39 @@ export default async function doLoadConfig(options: {
}));
newConfig.tools.push(...serverTools);
// Fetch MCP prompt content during config load
const serverSlashCommands: SlashCommandDescWithSource[] =
server.prompts.map((prompt) => ({
name: prompt.name,
description: prompt.description ?? "MCP Prompt",
source: "mcp-prompt",
isLegacy: false,
mcpServerName: server.name, // Used in client to retrieve prompt
mcpArgs: prompt.arguments,
}));
await Promise.all(
server.prompts.map(async (prompt) => {
let promptContent: string | undefined;
try {
// Fetch the actual prompt content from the MCP server
const mcpPromptResponse = await mcpManager.getPrompt(
server.name,
prompt.name,
{}, // Empty args for now - TODO: handle prompt arguments
);
promptContent = stringifyMcpPrompt(mcpPromptResponse);
} catch (error) {
console.warn(
`Failed to fetch MCP prompt content for ${prompt.name} from server ${server.name}:`,
error,
);
// Keep promptContent as undefined so the UI can show a fallback
}
return {
name: prompt.name,
description: prompt.description ?? "MCP Prompt",
source: "mcp-prompt",
isLegacy: false,
prompt: promptContent, // Store the actual prompt content
mcpServerName: server.name, // Used in client to retrieve prompt
mcpArgs: prompt.arguments,
};
}),
);
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources

View file

@ -99,12 +99,32 @@ export class LocalPlatformClient implements PlatformClient {
const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
// For any secret that isn't found, look in .env files
// For any secret that isn't found, look in .env files, then process.env
for (let i = 0; i < results.length; i++) {
if (!results[i]?.found) {
const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]);
if (secretFromEnv?.found) {
results[i] = secretFromEnv;
let secretResult = await this.findSecretInEnvFiles(fqsns[i]);
// If not found in .env files, try process.env
if (!secretResult?.found) {
const secretValueFromProcessEnv = process.env[fqsns[i].secretName];
if (secretValueFromProcessEnv !== undefined) {
secretResult = {
found: true,
fqsn: fqsns[i],
value: secretValueFromProcessEnv,
secretLocation: {
secretName: fqsns[i].secretName,
// Cast to SecretType.ProcessEnv is necessary because the specific type
// ProcessEnvSecretLocation expects secretType to be exactly SecretType.ProcessEnv,
// not the general enum SecretType.
secretType: SecretType.ProcessEnv as SecretType.ProcessEnv,
},
};
}
}
if (secretResult?.found) {
results[i] = secretResult;
}
}
}

View file

@ -229,4 +229,185 @@ describe("LocalPlatformClient", () => {
).not.toContain(randomValueForWorkspaceDotEnv);
});
});
describe("should be able to get secrets from process.env", () => {
const ogProcessEnv = { ...process.env };
beforeEach(async () => {
// Ensure secrets are not found in ControlPlane initially for these tests
const mockResolveFQSNsNotFound = async (
fqsns: FQSN[],
): Promise<(SecretResult | undefined)[]> =>
fqsns.map((fqsn) => ({
found: false,
fqsn,
secretLocation: {
secretName: fqsn.secretName,
secretType: SecretType.NotFound as SecretType.NotFound,
},
}));
testControlPlaneClient.resolveFQSNs = vi.fn(mockResolveFQSNsNotFound);
// Ensure secrets are not found in local .env files
const utilPaths = await import("../../util/paths");
utilPaths.getContinueDotEnv = vi.fn(() => ({}));
// Ensure secrets are not found in workspace .env files
testIde.fileExists = vi.fn(async () => false);
testIde.readFile = vi.fn(async () => "");
// Clear any potentially set process.env variables from previous tests in this block
delete process.env[testFQSN.secretName];
delete process.env[testFQSN2.secretName];
});
afterEach(() => {
// Restore original process.env
process.env = { ...ogProcessEnv };
});
test("should resolve secret from process.env if not found elsewhere", async () => {
const processEnvSecretValue = "secret-from-process-env";
process.env[testFQSN.secretName] = processEnvSecretValue;
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
const result = resolvedFQSNs[0];
expect(result?.found).toBe(true);
expect((result as SecretResult & { value: unknown })?.value).toBe(
processEnvSecretValue,
);
expect(result?.secretLocation?.secretType).toBe(SecretType.ProcessEnv);
// Check if the specific ProcessEnvSecretLocation is correctly formed
expect(result?.secretLocation).toEqual(
expect.objectContaining({
secretName: testFQSN.secretName,
secretType: SecretType.ProcessEnv,
}),
);
});
test("should return not found if secret is not in process.env or other locations", async () => {
// Ensure it's not in process.env
expect(process.env[testFQSN.secretName]).toBeUndefined();
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
expect(resolvedFQSNs[0]?.found).toBe(false);
expect(resolvedFQSNs[0]?.secretLocation?.secretType).toBe(
SecretType.NotFound,
);
});
test("should prioritize ControlPlane over process.env", async () => {
const controlPlaneValue = "secret-from-control-plane";
const mockResolveFQSNsControlPlaneFound = async (): Promise<
(SecretResult | undefined)[]
> => [
{
found: true,
fqsn: testFQSN,
value: controlPlaneValue,
secretLocation: {
secretType: SecretType.Organization as SecretType.Organization,
orgSlug: (testResolvedFQSN.secretLocation as any).orgSlug,
secretName: testFQSN.secretName,
},
},
];
testControlPlaneClient.resolveFQSNs = vi.fn(
mockResolveFQSNsControlPlaneFound,
);
process.env[testFQSN.secretName] =
"secret-from-process-env-should-be-ignored";
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
const result = resolvedFQSNs[0];
expect(result?.found).toBe(true);
expect((result as SecretResult & { value: unknown })?.value).toBe(
controlPlaneValue,
);
expect(result?.secretLocation?.secretType).toBe(SecretType.Organization);
});
test("should prioritize local ~/.continue/.env file over process.env", async () => {
const localEnvFileValue = "secret-from-local-dot-continue-env";
const utilPaths = await import("../../util/paths");
utilPaths.getContinueDotEnv = vi.fn(() => ({
[testFQSN.secretName]: localEnvFileValue,
}));
process.env[testFQSN.secretName] =
"secret-from-process-env-should-be-ignored";
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
const result = resolvedFQSNs[0];
expect(result?.found).toBe(true);
expect((result as SecretResult & { value: unknown })?.value).toBe(
localEnvFileValue,
);
expect(result?.secretLocation?.secretType).toBe(SecretType.LocalEnv);
});
test("should prioritize workspace .env files over process.env", async () => {
const workspaceContinueEnvValue = "secret-from-workspace-continue-env";
testIde.fileExists = vi.fn(async (fileUri: string) =>
// Only mock existence for <workspace>/.continue/.env
fileUri.includes(".continue/.env"),
);
testIde.readFile = vi.fn(async (fileUri: string) => {
if (fileUri.includes(".continue/.env")) {
return `${testFQSN.secretName}=${workspaceContinueEnvValue}`;
}
return "";
});
process.env[testFQSN.secretName] =
"secret-from-process-env-should-be-ignored";
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
const result = resolvedFQSNs[0];
expect(result?.found).toBe(true);
expect((result as SecretResult & { value: unknown })?.value).toBe(
workspaceContinueEnvValue,
);
// This should be LocalEnv because findSecretInEnvFiles returns LocalEnv for workspace files too
expect(result?.secretLocation?.secretType).toBe(SecretType.LocalEnv);
});
});
});

View file

@ -119,11 +119,11 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
results.sort(
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
);
results = results.slice(-this.options.nFinal);
results = results.slice(0, this.options.nFinal);
return results;
} catch (e) {
console.warn(`Failed to rerank retrieval results\n${e}`);
return chunks.slice(-this.options.nFinal);
return chunks.slice(0, this.options.nFinal);
}
}

View file

@ -337,22 +337,17 @@ export class Core {
);
});
on("config/reload", async (msg) => {
// User force reloading will retrigger colocated rules
const codebaseRulesCache = CodebaseRulesCache.getInstance();
await codebaseRulesCache.refresh(this.ide);
void this.configHandler.reloadConfig(
"Force reloaded (config/reload message)",
);
});
on("config/ideSettingsUpdate", async (msg) => {
await this.configHandler.updateIdeSettings(msg.data);
});
on("config/refreshProfiles", async (msg) => {
const { selectOrgId, selectProfileId } = msg.data ?? {};
await this.configHandler.refreshAll();
// User force reloading will retrigger colocated rules
const codebaseRulesCache = CodebaseRulesCache.getInstance();
await codebaseRulesCache.refresh(this.ide);
const { selectOrgId, selectProfileId, reason } = msg.data ?? {};
await this.configHandler.refreshAll(reason);
if (selectOrgId) {
await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
} else if (selectProfileId) {
@ -724,7 +719,7 @@ export class Core {
}
}
if (localAssistantCreated) {
await this.configHandler.refreshAll();
await this.configHandler.refreshAll("Local assistant file created");
}
}
});

View file

@ -0,0 +1,713 @@
import { findSearchMatch, SearchMatchResult } from "./findSearchMatch";
/**
* Helper function to perform a replacement using the match result
* This simulates what the actual replacement tool would do
*/
function performReplacement(
fileContent: string,
match: SearchMatchResult,
replacement: string,
): string {
return (
fileContent.substring(0, match.startIndex) +
replacement +
fileContent.substring(match.endIndex)
);
}
/**
* Helper function to test a specific strategy by crafting inputs that
* will fail all previous strategies
*/
function testSpecificStrategy(
fileContent: string,
searchContent: string,
expectedStrategy: string,
): SearchMatchResult | null {
const result = findSearchMatch(fileContent, searchContent);
if (result && result.strategyName !== expectedStrategy) {
throw new Error(
`Expected strategy ${expectedStrategy} but got ${result.strategyName}`,
);
}
return result;
}
/**
* Helper function to verify that a match result correctly identifies
* the intended content and replacement works properly
*/
function verifyMatchAndReplacement(
fileContent: string,
searchContent: string,
expectedMatchedText: string,
replacementText: string,
expectedResult: string,
): void {
const match = findSearchMatch(fileContent, searchContent);
if (!match) {
throw new Error("No match found");
}
// Verify the match captures the expected text
const actualMatchedText = fileContent.substring(
match.startIndex,
match.endIndex,
);
expect(actualMatchedText).toBe(expectedMatchedText);
// Verify replacement works correctly
const result = performReplacement(fileContent, match, replacementText);
expect(result).toBe(expectedResult);
}
describe("Strategy-specific tests", () => {
describe("exactMatch strategy", () => {
it("should handle exact match at various positions", () => {
const testCases = [
{
name: "at start",
fileContent: "abc def ghi",
searchContent: "abc",
expectedStart: 0,
expectedEnd: 3,
},
{
name: "in middle",
fileContent: "abc def ghi",
searchContent: "def",
expectedStart: 4,
expectedEnd: 7,
},
{
name: "at end",
fileContent: "abc def ghi",
searchContent: "ghi",
expectedStart: 8,
expectedEnd: 11,
},
{
name: "entire content",
fileContent: "abc def ghi",
searchContent: "abc def ghi",
expectedStart: 0,
expectedEnd: 11,
},
];
testCases.forEach(
({ name, fileContent, searchContent, expectedStart, expectedEnd }) => {
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(expectedStart);
expect(result!.endIndex).toBe(expectedEnd);
// Verify the matched content
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
},
);
});
it("should handle multiline exact matches", () => {
const fileContent = `line1
line2
line3
line4`;
const searchContent = `line2
line3`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(6); // After "line1\n"
expect(result!.endIndex).toBe(17); // End of "line3"
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should handle content with special characters", () => {
const fileContent = `const regex = /[a-z]+/gi;
const str = "Hello, World!";
const result = str.match(regex);`;
const searchContent = `const str = "Hello, World!";`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should verify replacement works correctly for exact matches", () => {
verifyMatchAndReplacement(
"const a = 1;\nconst b = 2;\nconst c = 3;",
"const b = 2;",
"const b = 2;",
"const b = 42;",
"const a = 1;\nconst b = 42;\nconst c = 3;",
);
});
it("should handle Windows-style line endings", () => {
const fileContent = "line1\r\nline2\r\nline3";
const searchContent = "line2";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(7); // After "line1\r\n"
expect(result!.endIndex).toBe(12); // End of "line2"
});
it("should handle mixed line endings", () => {
const fileContent = "line1\nline2\r\nline3\rline4";
const searchContent = "line2\r\nline3";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
});
describe("trimmedMatch strategy", () => {
it("should match when only whitespace differs at edges", () => {
const testCases = [
{
name: "leading spaces",
fileContent: "abc\n def\nghi",
searchContent: " def",
trimmedSearch: "def",
},
{
name: "trailing spaces",
fileContent: "abc\ndef \nghi",
searchContent: "def ",
trimmedSearch: "def",
},
{
name: "both leading and trailing",
fileContent: "abc\n def \nghi",
searchContent: " def ",
trimmedSearch: "def",
},
{
name: "tabs and spaces",
fileContent: "abc\n\t def \t\nghi",
searchContent: "\t def \t",
trimmedSearch: "def",
},
];
testCases.forEach(
({ name, fileContent, searchContent, trimmedSearch }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// For cases where exact match exists, it should be preferred
if (fileContent.indexOf(searchContent) !== -1) {
expect(result!.strategyName).toBe("exactMatch");
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
} else {
expect(result!.strategyName).toBe("trimmedMatch");
// The match should find the trimmed content with surrounding whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(trimmedSearch);
}
},
);
});
it("should handle multiline content with edge whitespace", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2; `;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used
expect(result!.strategyName).toBe("trimmedMatch");
});
it("should verify replacement with trimmed matches", () => {
const fileContent = "start\n targetContent \nend";
const searchContent = " targetContent ";
const replacement = "newContent";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("trimmedMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe("start\nnewContent\nend");
});
it("should handle edge case with only whitespace", () => {
const fileContent = " \n \n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find exact match since the content matches exactly
expect(result!.strategyName).toBe("exactMatch");
});
});
describe("whitespaceIgnoredMatch strategy", () => {
it("should match content with different indentation", () => {
const fileContent = `function test() {
const x = 1;
if (x > 0) {
return true;
}
}`;
const searchContent = `const x=1;
if(x>0){
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the match covers the intended code block
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("const x = 1");
expect(matchedContent).toContain("return true");
});
it("should handle complex whitespace variations", () => {
const testCases = [
{
name: "spaces vs tabs",
fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}",
searchContent: "if (condition) { return true; }",
},
{
name: "multiple spaces collapsed",
fileContent: "const result = calculate( x , y );",
searchContent: "const result=calculate(x,y);",
},
{
name: "newlines removed",
fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}",
searchContent: "function test(){return 1;}",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the entire content is matched
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent.replace(/\s/g, "")).toBe(
searchContent.replace(/\s/g, ""),
);
});
});
it("should handle partial matches with whitespace differences", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.items = [];
}
addItem(item) {
this.items.push(item);
}
}`;
const searchContent = `constructor(name){this.name=name;this.items=[];}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// The match should cover the constructor method
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("constructor");
expect(matchedContent).toContain("this.items = []");
});
it("should verify replacement with whitespace-ignored matches", () => {
const fileContent = `function calculate ( a , b ) {
return a + b ;
}`;
const searchContent = `function calculate(a,b){return a+b;}`;
const replacement = `function calculate(x, y) {
return x + y;
}`;
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("whitespaceIgnoredMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge cases with empty content after whitespace removal", () => {
const fileContent = " \n\t\r\n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
// Since search content doesn't exist in file but trims to empty, should return emptySearch
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("emptySearch");
});
it("should match correctly when multiple potential matches exist", () => {
const fileContent = `const a=1;
const a = 1 ;
const a = 1;`;
const searchContent = "const a = 1;";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find the exact match first (third occurrence)
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(33); // After first two lines
});
});
describe("jaroWinklerFuzzyMatch strategy", () => {
it("should match similar code with variable name differences", () => {
const fileContent = `function calculateTotal(items) {
let sum = 0;
for (const item of items) {
sum += item.price;
}
return sum;
}`;
const searchContent = `function calculateTotal(products) {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
it("should match code with minor typos", () => {
const testCases = [
{
name: "typo in function name",
fileContent: "function getUserName() { return this.name; }",
searchContent: "function getUserNaem() { return this.name; }",
},
{
name: "typo in variable",
fileContent: "const message = 'Hello World';",
searchContent: "const mesage = 'Hello World';",
},
{
name: "missing character",
fileContent: "console.log('Debug info');",
searchContent: "console.log('Debug nfo');",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
});
it("should not match when similarity is too low", () => {
const fileContent = "function add(a, b) { return a + b; }";
const searchContent =
"class Calculator { multiply(x, y) { return x * y; } }";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiline fuzzy matches", () => {
const fileContent = `if (userIsLoggedIn) {
showDashboard();
loadUserData();
}`;
const searchContent = `if (isUserLoggedIn) {
displayDashboard();
fetchUserData();
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
it("should verify replacement with fuzzy matches", () => {
const fileContent = "const userName = 'John';";
const searchContent = "const usrName = 'John';"; // Typo in variable name
const replacement = "const userName = 'Jane';";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("jaroWinklerFuzzyMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge case with very short strings", () => {
const fileContent = "ab";
const searchContent = "ac";
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to low similarity on short strings
expect(result).toBeNull();
});
});
describe("Empty search content", () => {
it("should always return position 0 for empty search", () => {
const testCases = [
{ fileContent: "some content" },
{ fileContent: "" },
{ fileContent: "line1\nline2\nline3" },
{ fileContent: " spaces " },
];
testCases.forEach(({ fileContent }) => {
const result = findSearchMatch(fileContent, "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
it("should treat whitespace-only search as empty", () => {
const searchVariants = [" ", "\n\n", "\t\t", " \n\t "];
searchVariants.forEach((searchContent) => {
const result = findSearchMatch("test content", searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
});
describe("Strategy precedence", () => {
it("should always prefer exact match over other strategies", () => {
const fileContent = `exact match
exact match with spaces
exactmatch`;
// This should find exact match even though fuzzy would also work
const result = findSearchMatch(fileContent, "exact match");
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(0);
});
it("should prefer trimmed match over whitespace-ignored", () => {
const fileContent = " content ";
const searchContent = " content ";
// Should find exact match
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("exactMatch");
});
it("should prefer whitespace-ignored over fuzzy", () => {
const fileContent = "const x = 1;";
const searchContent = "const x=1;";
// Should use whitespace-ignored, not fuzzy
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
});
});
describe("Replacement verification tests", () => {
it("should correctly replace content found by each strategy", () => {
const testCases = [
{
name: "exact match replacement",
fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;",
searchContent: "const b = 2;",
replacement: "const b = 42;",
expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;",
expectedStrategy: "exactMatch",
},
{
name: "trimmed match replacement",
fileContent: "start\n target \nend",
searchContent: " target ",
replacement: "replaced",
expectedResult: "start\nreplaced\nend",
expectedStrategy: "trimmedMatch",
},
{
name: "whitespace-ignored replacement",
fileContent: "if ( x > 0 ) { return true; }",
searchContent: "if(x>0){return true;}",
replacement: "if (x > 0) { return false; }",
expectedResult: "if (x > 0) { return false; }",
expectedStrategy: "whitespaceIgnoredMatch",
},
];
testCases.forEach(
({
name,
fileContent,
searchContent,
replacement,
expectedResult,
expectedStrategy,
}) => {
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe(expectedStrategy);
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(expectedResult);
},
);
});
it("should handle edge cases in replacement", () => {
// Empty replacement
verifyMatchAndReplacement(
"before target after",
"target",
"target",
"",
"before after",
);
// Replacement longer than original
verifyMatchAndReplacement(
"short",
"short",
"short",
"much longer replacement",
"much longer replacement",
);
// Multiline replacement
verifyMatchAndReplacement(
"single line",
"single",
"single",
"multi\nline\nreplacement",
"multi\nline\nreplacement line",
);
});
});
describe("Performance and edge cases", () => {
it("should handle very long content efficiently", () => {
const longContent = "x".repeat(10000) + "target" + "y".repeat(10000);
const result = findSearchMatch(longContent, "target");
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(10000);
expect(result!.endIndex).toBe(10006);
});
it("should handle unicode and special characters", () => {
const testCases = [
{
fileContent: "const emoji = '🚀🌟🎉';",
searchContent: "🚀🌟🎉",
},
{
fileContent: "const chinese = '你好世界';",
searchContent: "你好世界",
},
{
fileContent: "const regex = /\\d+/g;",
searchContent: "/\\d+/g",
},
];
testCases.forEach(({ fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(searchContent);
});
});
it("should handle null bytes and control characters", () => {
const fileContent = "before\x00null\x01byte\x02after";
const searchContent = "\x00null\x01byte\x02";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("exactMatch");
});
});
});

View file

@ -43,20 +43,48 @@ function exactMatch(
/**
* Trimmed content matching strategy
* Finds content where the search content (when trimmed) matches content in the file,
* and returns the span that includes the file content's whitespace
*/
function trimmedMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const trimmedSearchContent = searchContent.trim();
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedIndex !== -1) {
return {
startIndex: trimmedIndex,
endIndex: trimmedIndex + trimmedSearchContent.length,
};
// Don't apply if search content has no leading/trailing whitespace to trim
if (trimmedSearchContent === searchContent) {
return null;
}
return null;
// Don't match if trimmed content is empty
if (trimmedSearchContent === "") {
return null;
}
// Look for the trimmed content in the file
const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedContentIndex === -1) {
return null;
}
// Find the boundaries that include surrounding whitespace (but not newlines)
// Look backwards for horizontal whitespace (spaces and tabs)
let startIndex = trimmedContentIndex;
while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) {
startIndex--;
}
// Look forwards for horizontal whitespace (spaces and tabs)
let endIndex = trimmedContentIndex + trimmedSearchContent.length;
while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) {
endIndex++;
}
return {
startIndex,
endIndex,
};
}
/**
@ -298,10 +326,24 @@ export function findSearchMatch(
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
const trimmedSearchContent = searchContent.trim();
// Handle truly empty search content
if (searchContent === "") {
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Handle whitespace-only search content that trims to empty
const trimmedSearchContent = searchContent.trim();
if (trimmedSearchContent === "") {
// Empty search content matches the beginning of the file
// Check if the whitespace-only search content has an exact match first
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
strategyName: "exactMatch",
};
}
// If no exact match for whitespace-only content, treat as empty search
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}

6
core/index.d.ts vendored
View file

@ -1069,6 +1069,11 @@ export interface ToolExtras {
codeBaseIndexer?: CodebaseIndexer;
}
export type ToolPolicy =
| "allowedWithPermission"
| "allowedWithoutPermission"
| "disabled";
export interface Tool {
type: "function";
function: {
@ -1089,6 +1094,7 @@ export interface Tool {
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
defaultToolPolicy?: ToolPolicy;
}
interface ToolChoice {

View file

@ -155,6 +155,24 @@ function llmCanGenerateInParallel(provider: string, model: string): boolean {
return PARALLEL_PROVIDERS.includes(provider);
}
function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
modelName: string,
): boolean {
return (
modelName.includes("gpt") ||
modelName.includes("command") ||
modelName.includes("aya") ||
modelName.includes("chat-bison") ||
modelName.includes("pplx") ||
modelName.includes("gemini") ||
modelName.includes("grok") ||
modelName.includes("moonshot") ||
modelName.includes("kimi") ||
modelName.includes("mercury") ||
/^o\d/.test(modelName)
);
}
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
@ -162,20 +180,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "codellama-70b";
}
if (
lower.includes("gpt") ||
lower.includes("command") ||
lower.includes("aya") ||
lower.includes("chat-bison") ||
lower.includes("pplx") ||
lower.includes("gemini") ||
lower.includes("grok") ||
lower.includes("moonshot") ||
lower.includes("mercury") ||
/^o\d/.test(lower)
) {
if (isProviderHandlesTemplatingOrNoTemplateTypeRequired(lower)) {
return undefined;
}
if (lower.includes("llama3") || lower.includes("llama-3")) {
return "llama3";
}

View file

@ -9,6 +9,22 @@ import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
const errorMessages = {
invalid_request_error:
"There was an issue with the format or content of your request.",
authentication_error: "There's an issue with your API key.",
permission_error:
"Your API key does not have permission to use the specified resource.",
not_found_error: "The requested resource was not found.",
request_too_large:
"Request exceeds the maximum allowed number of bytes (32 MB limit).",
rate_limit_error: "Your account has hit a rate limit.",
api_error:
"An unexpected error has occurred internal to Anthropic's systems.",
overloaded_error:
"Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
};
class Anthropic extends BaseLLM {
static providerName = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
@ -183,9 +199,9 @@ class Anthropic extends BaseLLM {
if (!response.ok) {
const json = await response.json();
if (json.type === "error") {
if (json.error?.type === "overloaded_error") {
if (json.error?.type in errorMessages) {
throw new Error(
"The Anthropic API is currently overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
errorMessages[json.error.type as keyof typeof errorMessages],
);
}
throw new Error(json.message);

View file

@ -1,64 +0,0 @@
import path from "node:path";
import { parentPort } from "node:worker_threads";
import {
env,
pipeline,
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
env.allowLocalModels = true;
env.allowRemoteModels = false;
if (typeof window === "undefined") {
// The embeddings provider should just never be called in the browser
env.localModelPath = path.join(__dirname, "..", "models");
}
class EmbeddingsPipeline {
static task = "feature-extraction";
static model = TransformersJsEmbeddingsProvider.ModelName;
static instance = null;
static async getInstance() {
if (EmbeddingsPipeline.instance === null) {
EmbeddingsPipeline.instance = await pipeline(
EmbeddingsPipeline.task,
EmbeddingsPipeline.model,
);
}
return EmbeddingsPipeline.instance;
}
}
parentPort.on("message", async (chunks) => {
try {
const extractor = await EmbeddingsPipeline.getInstance();
if (!extractor) {
throw new Error("TransformerJS embeddings pipeline is not initialized");
}
const outputs = [];
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.maxGroupSize
) {
const chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.maxGroupSize,
);
const output = await extractor(chunkGroup, {
pooling: "mean",
normalize: true,
});
outputs.push(...output.tolist());
}
parentPort.postMessage(outputs);
} catch (error) {
parentPort.postMessage({ error: error.message });
}
});

View file

@ -132,7 +132,7 @@ const isFileInDirectory = (
* Checks if a rule is a root-level rule (.continue directory or no file path)
*/
const isRootLevelRule = (rule: RuleWithSource): boolean => {
return !rule.ruleFile || rule.ruleFile.startsWith(".continue/");
return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between
};
/**

View file

@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: ".continue/rules.md",
ruleFile: "/path/to/repo/.continue/rules.md",
// No restriction, should apply to all files
};
@ -212,7 +212,7 @@ describe("Rule policies", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: ".continue/rules.md",
ruleFile: "/my/project/.continue/rules.md",
};
// Off policy should override even global rules

View file

@ -30,6 +30,11 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
).toBe(true);
});
it("should return true for Gemma models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/gemma")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/gemma3")).toBe(true);
});
it("should return true for O3 models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true);
});
@ -56,6 +61,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"),
).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma3")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
});
});
@ -98,6 +104,11 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("o3-preview")).toBe(true);
});
it("should return true for Gemma models", () => {
expect(supportsFn("gemma")).toBe(true);
expect(supportsFn("gemma3")).toBe(true);
});
it("should return undefined for unsupported models", () => {
expect(supportsFn("gpt-3.5-turbo")).toBe(false);
expect(supportsFn("davinci")).toBe(false);
@ -106,6 +117,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should handle case insensitivity", () => {
expect(supportsFn("GPT-4-turbo")).toBe(true);
expect(supportsFn("O3-preview")).toBe(true);
expect(supportsFn("Gemma3")).toBe(true);
});
});

View file

@ -25,6 +25,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"o3",
"gemini",
"claude-opus-4",
"gemma",
].some((part) => model.toLowerCase().startsWith(part));
},
anthropic: (model) => {
@ -60,6 +61,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
) {
return true;
}
// https://ai.google.dev/gemma/docs/capabilities/function-calling
if (model.toLowerCase().startsWith("gemma")) {
return true;
}
// firworks-ai https://docs.fireworks.ai/guides/function-calling
if (model.startsWith("accounts/fireworks/models/")) {
switch (model.substring(26)) {
@ -286,6 +291,22 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
}
}
return false;
},
moonshot: (model) => {
// support moonshot models
// https://platform.moonshot.ai/docs/pricing/chat#concepts
if (
model.toLowerCase().startsWith("kimi") &&
model.toLowerCase() !== "kimi-thinking-preview"
) {
return true;
}
if (model.toLowerCase().startsWith("moonshot")) {
return true;
}
return false;
},
};

View file

@ -94,11 +94,11 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, void];
"config/refreshProfiles": [
(
| undefined
| {
reason?: string;
selectOrgId?: string;
selectProfileId?: string;
}

View file

@ -52,7 +52,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
newSessionWithPrompt: [{ prompt: string }, void];
userInput: [{ input: string }, void];
focusContinueInput: [undefined, void];

View file

@ -27,6 +27,7 @@ export const codebaseTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CodebaseTool,
`To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,

View file

@ -31,6 +31,7 @@ export const createNewFileTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateNewFile,
`To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`,

View file

@ -60,6 +60,7 @@ export const createRuleBlock: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateRuleBlock,
`Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions.

View file

@ -40,6 +40,7 @@ export const editFileTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.EditExistingFile,
`To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with

View file

@ -26,6 +26,7 @@ export const fetchUrlContentTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FetchUrlContent,
`To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,

View file

@ -26,6 +26,7 @@ export const globSearchTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FileGlobSearch,
`To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,

View file

@ -27,6 +27,7 @@ export const grepSearchTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.GrepSearch,
`To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,

View file

@ -0,0 +1,17 @@
export { codebaseTool } from "./codebaseTool";
export { createNewFileTool } from "./createNewFile";
export { createRuleBlock } from "./createRuleBlock";
export { editFileTool } from "./editFile";
export { fetchUrlContentTool } from "./fetchUrlContent";
export { globSearchTool } from "./globSearch";
export { grepSearchTool } from "./grepSearch";
export { lsTool } from "./ls";
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
export { readFileTool } from "./readFile";
export { requestRuleTool } from "./requestRule";
export { runTerminalCommandTool } from "./runTerminalCommand";
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
export { searchWebTool } from "./searchWeb";
export { viewDiffTool } from "./viewDiff";
export { viewRepoMapTool } from "./viewRepoMap";
export { viewSubdirectoryTool } from "./viewSubdirectory";

View file

@ -31,6 +31,7 @@ export const lsTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.LSTool,
`To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,

View file

@ -20,6 +20,7 @@ export const readCurrentlyOpenFileTool: Tool = {
properties: {},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadCurrentlyOpenFile,
`To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.

View file

@ -27,6 +27,7 @@ export const readFileTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadFile,
`To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`,

View file

@ -60,6 +60,7 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
},
},
},
defaultToolPolicy: "disabled",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RequestRule,
getRequestRuleSystemMessageDescription(rules),

View file

@ -56,6 +56,7 @@ export const runTerminalCommandTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RunTerminalCommand,
`To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool

View file

@ -120,4 +120,5 @@ ${SEARCH_AND_REPLACE_RULES}
],
],
),
defaultToolPolicy: "allowedWithPermission",
};

View file

@ -26,6 +26,7 @@ export const searchWebTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchWeb,
`To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,

View file

@ -0,0 +1,54 @@
import { describe, expect, it } from "@jest/globals";
import { ConfigDependentToolParams, GetTool, Tool } from "../..";
import * as toolDefinitions from "./index";
describe("Tool Definitions", () => {
// Mock params for tools that need them
const mockParams: ConfigDependentToolParams = {
rules: [],
enableExperimentalTools: false,
};
// Helper function to get the actual tool object
const getToolObject = (toolDefinition: Tool | GetTool): Tool => {
if (typeof toolDefinition === "function") {
return toolDefinition(mockParams);
}
return toolDefinition;
};
it("should have all required parameters defined in properties for each tool", () => {
const exportedTools = Object.values(toolDefinitions);
exportedTools.forEach((toolDefinition) => {
const tool = getToolObject(toolDefinition);
// Each tool should have the required structure
expect(tool).toHaveProperty("type", "function");
expect(tool).toHaveProperty("function");
expect(tool.function).toHaveProperty("parameters");
const parameters = tool.function.parameters;
// If there are required parameters, they should be defined in properties
if (
parameters &&
parameters.required &&
Array.isArray(parameters.required)
) {
expect(parameters).toHaveProperty("properties");
expect(typeof parameters.properties).toBe("object");
// Check each required parameter is defined in properties
parameters.required.forEach((requiredParam: string) => {
expect(parameters.properties).toHaveProperty(requiredParam);
// Each property should have at least a type
const property = parameters.properties[requiredParam];
expect(property).toHaveProperty("type");
expect(typeof property.type).toBe("string");
});
}
});
});
});

View file

@ -20,6 +20,7 @@ export const viewDiffTool: Tool = {
properties: {},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewDiff,
`To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,

View file

@ -20,6 +20,7 @@ export const viewRepoMapTool: Tool = {
properties: {},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewRepoMap,
`To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,

View file

@ -26,6 +26,7 @@ export const viewSubdirectoryTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewSubdirectory,
`To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`,

View file

@ -1,50 +1,38 @@
import { ConfigDependentToolParams, IDE, Tool } from "..";
import { codebaseTool } from "./definitions/codebaseTool";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
import { fetchUrlContentTool } from "./definitions/fetchUrlContent";
import { globSearchTool } from "./definitions/globSearch";
import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/ls";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
import { requestRuleTool } from "./definitions/requestRule";
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
import { searchAndReplaceInFileTool } from "./definitions/searchAndReplaceInFile";
import { searchWebTool } from "./definitions/searchWeb";
import { viewDiffTool } from "./definitions/viewDiff";
import { viewRepoMapTool } from "./definitions/viewRepoMap";
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
import * as toolDefinitions from "./definitions";
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
const getLocalOnlyToolDefinitions = () => [grepSearchTool];
const getLocalOnlyToolDefinitions = () => [toolDefinitions.grepSearchTool];
const getBaseToolDefinitions = () => [
readFileTool,
createNewFileTool,
runTerminalCommandTool,
globSearchTool,
searchWebTool,
viewDiffTool,
readCurrentlyOpenFileTool,
lsTool,
createRuleBlock,
fetchUrlContentTool,
toolDefinitions.readFileTool,
toolDefinitions.createNewFileTool,
toolDefinitions.runTerminalCommandTool,
toolDefinitions.globSearchTool,
toolDefinitions.searchWebTool,
toolDefinitions.viewDiffTool,
toolDefinitions.readCurrentlyOpenFileTool,
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
];
export const getConfigDependentToolDefinitions = (
params: ConfigDependentToolParams,
): Tool[] => [
requestRuleTool(params),
toolDefinitions.requestRuleTool(params),
// Search and replace is now generally available
searchAndReplaceInFileTool,
toolDefinitions.searchAndReplaceInFileTool,
// Keep edit file tool available for models that need it
editFileTool,
toolDefinitions.editFileTool,
...(params.enableExperimentalTools
? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool]
? [
toolDefinitions.viewRepoMapTool,
toolDefinitions.viewSubdirectoryTool,
toolDefinitions.codebaseTool,
]
: []),
];

View file

@ -1,6 +1,6 @@
---
title: "Configuration"
description: Configuration
description: Learn how to access and manage Continue assistant configurations through Hub or local YAML files
keywords: [config, settings, customize]
---
@ -82,4 +82,4 @@ export function modifyConfig(config: Config): Config {
});
return config;
}
```
```

View file

@ -104,17 +104,17 @@ server block to your [config file](./configuration.md):
MCP blocks follow the established syntax for blocks, with a few additional properties specific to MCP servers.
- `name` (**required**): A display name for the MCP server.
- `command` (**required**): The command to run to start the MCP server.
- `type` (optional): The type of the MCP server: `sse`, `stdio`, `streamable-http`
- `args` (optional): Arguments to pass to the command.
- `env` (optional): Secrets to be injected into the command as environment variables.
- `name`: A display name for the MCP server.
- `type`: The type of the MCP server: `sse`, `stdio`, `streamable-http`
- `command`: The command to run to start the MCP server.
- `args`: Arguments to pass to the command.
- `env`: Secrets to be injected into the command as environment variables.
### Transport Types
MCP now supports remote server connections through HTTP-based transports, expanding beyond the traditional local stdio transport method. This enables integration with cloud-hosted MCP servers and distributed architectures.
#### Server-Sent Events (SSE) Transport
#### Server-Sent Events Transport (`sse`)
For real-time streaming communication, use the SSE transport:
@ -125,7 +125,7 @@ mcpServers:
url: https://....
```
#### Standard Input/Output (stdio)
#### Standard Input/Output (`stdio`)
For local MCP servers that communicate via standard input and output:
@ -139,7 +139,7 @@ mcpServers:
- "/path/to/your/database.db"
```
#### Streamable HTTP Transport
#### Streamable HTTP Transport (`streamable-http`)
For standard HTTP-based communication with streaming capabilities:

View file

@ -0,0 +1,246 @@
---
title: Model Capabilities
description: Understanding and configuring model capabilities for tools and image support
keywords: [capabilities, tools, function calling, image input, config]
---
Continue needs to know what features your models support to provide the best experience. This guide explains how model capabilities work and how to configure them.
## What are Model Capabilities?
Model capabilities tell Continue what features a model supports:
- **`tool_use`** - Whether the model can use tools and functions
- **`image_input`** - Whether the model can process images
Without proper capability configuration, you may encounter issues like:
- Agent mode being unavailable (requires tools)
- Tools not working at all
- Image uploads being disabled
## How Continue Detects Capabilities
Continue uses a two-tier system for determining model capabilities:
### 1. Automatic Detection (Default)
Continue automatically detects capabilities based on your provider and model name. For example:
- **OpenAI**: GPT-4 and GPT-3.5 Turbo models support tools
- **Anthropic**: Claude 3.5+ models support both tools and images
- **Ollama**: Most models support tools, vision models support images
- **Google**: All Gemini models support function calling
This works well for popular models, but may not cover custom deployments or newer models.
For implementation details, see:
- [toolSupport.ts](https://github.com/continuedev/continue/blob/main/core/llm/toolSupport.ts) - Tool capability detection logic
- [@continuedev/llm-info](https://www.npmjs.com/package/@continuedev/llm-info) - Image support detection
### 2. Manual Configuration
You can add capabilities to models that Continue doesn't automatically detect in your `config.yaml`.
<Note>
You cannot override autodetection - you can only add capabilities. Continue will always use its built-in knowledge about your model in addition to any capabilities you specify.
</Note>
```yaml
models:
- name: my-custom-gpt4
provider: openai
apiBase: https://my-deployment.com/v1
model: gpt-4-custom
capabilities:
- tool_use
- image_input
```
## When to Add Capabilities
Add capabilities when:
1. **Using custom deployments** - Your API endpoint serves a model with different capabilities than the standard version
2. **Using newer models** - Continue doesn't yet recognize a newly released model
3. **Experiencing issues** - Autodetection isn't working correctly for your setup
4. **Using proxy services** - Some proxy services modify model capabilities
## Configuration Examples
### Basic Configuration
Add tool support for a model that Continue doesn't recognize:
```yaml
models:
- name: custom-model
provider: openai
model: my-fine-tuned-gpt4
capabilities:
- tool_use
```
<Info>
The `tool_use` capability is for native tool/function calling support. The
model must actually support tools for this to work.
</Info>
<Warning>
**Experimental**: System message tools are available as an experimental feature
for models without native tool support. These are not automatically used as a
fallback and must be explicitly configured. Most models are trained for native
tools, so system message tools may not work as well.
</Warning>
### Disable Capabilities
Explicitly set no capabilities (autodetection will still apply):
```yaml
models:
- name: limited-claude
provider: anthropic
model: claude-4.0-sonnet
capabilities: [] # Empty array doesn't disable autodetection
```
<Warning>
An empty capabilities array does not disable autodetection. Continue will
still detect and use the model's actual capabilities. To truly limit a model's
capabilities, you would need to use a model that doesn't support those
features.
</Warning>
### Multiple Capabilities
Enable both tools and image support:
```yaml
models:
- name: multimodal-gpt
provider: openai
model: gpt-4-vision-preview
capabilities:
- tool_use
- image_input
```
## Common Scenarios
Some providers and custom deployments may require explicit capability configuration:
- **OpenRouter**: May not preserve the original model's capabilities
- **Custom API endpoints**: May have different capabilities than standard models
- **Local models**: May need explicit capabilities if using non-standard model names
Example configuration:
```yaml
models:
- name: custom-deployment
provider: openai
apiBase: https://custom-api.company.com/v1
model: custom-gpt
capabilities:
- tool_use # If supports function calling
- image_input # If supports vision
```
## Troubleshooting
For troubleshooting capability-related issues like Agent mode being unavailable or tools not working, see the [Troubleshooting guide](/troubleshooting#agent-mode-is-unavailable-or-tools-arent-working).
## Best Practices
1. **Start with autodetection** - Only override if you experience issues
2. **Test after changes** - Verify tools and images work as expected
3. **Keep Continue updated** - Newer versions improve autodetection
Remember: Setting capabilities only adds to autodetection. Continue will still use its built-in knowledge about your model in addition to your specified capabilities.
## Model Capability Support
This matrix shows which models support tool use and image input capabilities. Continue auto-detects these capabilities, but you can override them if needed.
### OpenAI
| Model | Tool Use | Image Input | Context Window |
| :------------ | -------- | ----------- | -------------- |
| o3 | Yes | No | 128k |
| o3-mini | Yes | No | 128k |
| GPT-4o | Yes | Yes | 128k |
| GPT-4 Turbo | Yes | Yes | 128k |
| GPT-4 | Yes | No | 8k |
| GPT-3.5 Turbo | Yes | No | 16k |
### Anthropic
| Model | Tool Use | Image Input | Context Window |
| :---------------- | -------- | ----------- | -------------- |
| Claude 4 Sonnet | Yes | Yes | 200k |
| Claude 3.5 Sonnet | Yes | Yes | 200k |
| Claude 3.5 Haiku | Yes | Yes | 200k |
### Google
| Model | Tool Use | Image Input | Context Window |
| :--------------- | -------- | ----------- | -------------- |
| Gemini 2.5 Pro | Yes | Yes | 2M |
| Gemini 2.0 Flash | Yes | Yes | 1M |
### Mistral
| Model | Tool Use | Image Input | Context Window |
| :-------------- | -------- | ----------- | -------------- |
| Devstral Medium | Yes | No | 32k |
| Mistral | Yes | No | 32k |
### DeepSeek
| Model | Tool Use | Image Input | Context Window |
| :---------------- | -------- | ----------- | -------------- |
| DeepSeek V3 | Yes | No | 128k |
| DeepSeek Coder V2 | Yes | No | 128k |
| DeepSeek Chat | Yes | No | 64k |
### xAI
| Model | Tool Use | Image Input | Context Window |
| :----- | -------- | ----------- | -------------- |
| Grok 4 | Yes | Yes | 128k |
### Moonshot AI
| Model | Tool Use | Image Input | Context Window |
| :------ | -------- | ----------- | -------------- |
| Kimi K2 | Yes | Yes | 128k |
### Qwen
| Model | Tool Use | Image Input | Context Window |
| :---------------- | -------- | ----------- | -------------- |
| Qwen Coder 3 480B | Yes | No | 128k |
### Ollama (Local Models)
| Model | Tool Use | Image Input | Context Window |
| :------------- | -------- | ----------- | -------------- |
| Qwen 3 Coder | Yes | No | 32k |
| Devstral Small | Yes | No | 32k |
| Llama 3.1 | Yes | No | 128k |
| Llama 3 | Yes | No | 8k |
| Mistral | Yes | No | 32k |
| Codestral | Yes | No | 32k |
| Gemma 3 4B | Yes | No | 8k |
### Notes
- **Tool Use**: Function calling support (tools are required for Agent mode)
- **Image Input**: Processing images
- **Context Window**: Maximum number of tokens the model can process in a single request
---
**Is your model missing or incorrect?** Help improve this documentation! You can edit this page on GitHub using the link below.

View file

@ -71,3 +71,50 @@ For example, to prevent extra long prompts from being compressed, you can explic
</Tabs>
Learn more about available settings [here](https://openrouter.ai/docs).
## Model Capabilities
OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the original model's function calling support.
<Info>
Continue automatically uses system message tools for models that don't support native function calling, so Agent mode should work even without explicit capability configuration. However, you can still override capabilities if needed.
</Info>
If you're experiencing issues with Agent mode or tools not working, you can add the capabilities field:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Claude via OpenRouter
provider: openrouter
model: anthropic/claude-3.5-sonnet
apiBase: https://openrouter.ai/api/v1
apiKey: <YOUR_OPEN_ROUTER_API_KEY>
capabilities:
- tool_use # Enable function calling for Agent mode
- image_input # Enable image upload support
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Claude via OpenRouter",
"provider": "openrouter",
"model": "anthropic/claude-3.5-sonnet",
"apiBase": "https://openrouter.ai/api/v1",
"apiKey": "<YOUR_OPEN_ROUTER_API_KEY>",
"capabilities": {
"tools": true,
"uploadImage": true
}
}
]
}
```
</Tab>
</Tabs>
Note: Not all models support function calling. Check the [OpenRouter models page](https://openrouter.ai/models) for specific model capabilities.

View file

@ -123,3 +123,42 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m
```
</Tab>
</Tabs>
## Model Capabilities
Ollama models usually have their capabilities auto-detected correctly. However, if you're using custom model names or experiencing issues with tools/images not working, you can explicitly set capabilities:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Custom Vision Model
provider: ollama
model: my-custom-llava
capabilities:
- tool_use # Enable if your model supports function calling
- image_input # Enable for vision models like llava
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Custom Vision Model",
"provider": "ollama",
"model": "my-custom-llava",
"capabilities": {
"tools": true,
"uploadImage": true
}
}
]
}
```
</Tab>
</Tabs>
<Note>
Most standard Ollama models (like llama3.1, mistral, etc.) support tool use by default. Vision models (like llava) also support image input.
</Note>

View file

@ -168,7 +168,8 @@
"customize/deep-dives/autocomplete",
"customize/deep-dives/development-data",
"customize/deep-dives/vscode-actions",
"customize/deep-dives/mcp"
"customize/deep-dives/mcp",
"customize/deep-dives/model-capabilities"
]
},
{
@ -239,6 +240,7 @@
"group": "Guides",
"pages": [
"guides/overview",
"guides/understanding-assistants",
"guides/cli",
"guides/plan-mode-guide",
"guides/ollama-guide",

View file

@ -1,3 +1,37 @@
The models you set up for Chat mode will be used with Agent mode if the model supports tool calling.
The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/features/chat/model-setup).
The recommended models and how to set them up can be found [here](/features/chat/model-setup).
## System Message Tools
<Info>
System message tools are experimental and may change in future releases.
</Info>
Continue implements an innovative approach called **system message tools** that ensures consistent tool functionality across all models, regardless of their native capabilities. This allows Agent mode to work seamlessly with a wider range of models and providers.
### How It Works
Instead of relying solely on native tool calling APIs (which vary between providers), Continue converts tools into XML format and includes them in the system message. The model generates tool calls as structured XML within its response, which Continue then parses and executes. This approach provides:
- **Universal compatibility** - Any model capable of following instructions can use tools, not just those with native tool support
- **Consistent behavior** - Tool calls work identically across OpenAI, Anthropic, local models, and others
- **Better reliability** - Models that struggle with native tools often perform better with system message tools
- **Seamless switching** - Change between providers without modifying your workflow
### Recommended Models
For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
**Premium Models:**
- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
- **GPT-4** models (OpenAI) - Excellent native tool support
- **DeepSeek** models - Strong performance with competitive pricing
**Local Models:**
While more limited in capabilities, these models can work with system message tools:
- Qwen2.5-Coder 32B - Best local option for Agent mode
- Devstral 27B - Good for code-specific tasks
- Smaller models (7B-13B) - May struggle with complex tool interactions
### Configuration
Agent mode automatically determines whether to use native or system message tools based on the model's capabilities. No additional configuration is required - simply select your model and Continue handles the rest.

View file

@ -43,3 +43,7 @@ This model provides good suggestions while keeping your code completely private.
## Need Help?
If you're not seeing any completions or need more detailed configuration options, check out our comprehensive [autocomplete deep dive guide](/customize/deep-dives/autocomplete).
## Model Compatibility
To see a complete list of models and their capabilities, visit our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).

View file

@ -97,4 +97,8 @@ Their limited tool calling and reasoning capabilities will make it challenging t
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
3. Click `Reload config` in the assistant selector in the Continue IDE extension
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model)
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
## Model Compatibility
To see which models support specific features like tool use (for Agent mode) and image input, check out our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).

View file

@ -10,3 +10,7 @@ We also recommend setting up an Apply model for the best Edit experience.
- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
## Model Compatibility
For a complete overview of which models support various features, see our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).

View file

@ -0,0 +1,6 @@
---
title: "Understanding Assistants"
description: "Continue offers two ways to configure your AI assistants"
---
This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants)

View file

@ -3,6 +3,8 @@ title: "Overview"
description: "To quickly understand what you can do with Continue, check out each tab below."
---
## Features
<Tabs>
<Tab title="Agent">
[Agent](/features/agent/quick-start) equips the Chat model with the tools needed to handle a wide range of coding tasks
@ -54,3 +56,8 @@ description: "To quickly understand what you can do with Continue, check out eac
</Info>
</Tab>
</Tabs>
## AI Coding Assistants
Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Assistants** for easy setup and synchronization, or **Local Assistants** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).

View file

@ -35,9 +35,9 @@ After installing Ollama, download the models you want to use. Here are some popu
```
# Popular models for development
ollama pull llama2
ollama pull codellama
ollama pull mistral
ollama pull qwen2.5-coder:1.5b-base
ollama pull nomic-embed-text:latest
```
## Configuration
@ -46,19 +46,32 @@ Configure Continue to work with your local Ollama instance:
### Continue Configuration
```json
{
"models": [
{
"title": "Ollama",
"provider": "ollama",
"model": "llama2",
"apiBase": "http://localhost:11434"
}
]
}
```yaml
models:
- name: mistral
provider: ollama
apiBase: http://localhost:11434
model: mistral
roles:
- chat
- edit
- apply
- name: Qwen2.5-Coder 1.5B
provider: ollama
apiBase: http://localhost:11434
model: qwen2.5-coder:1.5b-base
roles:
- autocomplete
- name: Nomic Embed
provider: ollama
apiBase: http://localhost:11434
model: nomic-embed-text:latest
roles:
- embed
```
You can update `apiBase` with the IP address of a remote machine serving Ollama.
### Advanced Settings
For optimal performance, consider these advanced configuration options:

View file

@ -0,0 +1,186 @@
---
title: "Understanding Assistants: Hub vs Local Configuration"
description: "Master the two approaches to configuring AI assistants in Continue - choosing the right path for your development workflow"
---
Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow.
## The Two Paths to AI Assistance
Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly.
### Accessing Your Assistant Configuration
Before we dive into the specifics, let's understand how to access your configuration:
1. Open the Continue Chat sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)
2. Click the Assistant selector above the main chat input
3. Hover over an assistant and click:
- `new window` icon for Hub assistants
- `gear` icon for Local assistants
![configure an assistant](/images/configure-continue.png)
## Hub Assistants: The Managed Experience
Hub Assistants represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured assistants that sync seamlessly across all your development environments.
### Why Choose Hub Assistants?
**The Power of Simplicity**
- **Instant Setup**: Browse the [assistant marketplace](https://hub.continue.dev/explore/assistants) and add any assistant to your account with a single click
- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required
- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances
- **Team Collaboration**: Share custom assistants with your team, ensuring everyone uses the same optimized configurations
![nextjs assistant](/images/nextjs-assistant.png)
### Getting Started with Hub Assistants
The journey from zero to AI-powered coding takes just four steps:
1. **Select Your Assistant**: Click the assistant selector in your IDE's Continue panel
2. **Explore or Create**: Browse community assistants or craft your own specialized helper
3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed
4. **Sync and Code**: Click "Reload config" to pull your latest settings
Pro tip: Hub Assistants are perfect for teams. Create a custom assistant with your team's coding standards, preferred models, and context sources, then share it with a simple link.
### Managing Hub Assistants
All Hub Assistant management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Assistant](/hub/assistants/edit-an-assistant).
## Local Assistants: The Power User's Choice
Local Assistants put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI assistant's behavior, with all configuration stored directly on your machine.
### Why Choose Local Assistants?
**Complete Control and Privacy**
- **Your Data, Your Rules**: All configuration stays on your machine—perfect for air-gapped environments or strict data policies
- **Version Control Integration**: Check your `config.yaml` into git alongside your code, ensuring reproducible environments
- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models)
- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting
### Setting Up Local Assistants
Local configuration lives in a single YAML file in your home directory:
**File Locations:**
- macOS/Linux: `~/.continue/config.yaml`
- Windows: `%USERPROFILE%\.continue\config.yaml`
**Quick Access Method:**
1. Open the assistants dropdown in your IDE
2. Click the gear icon next to "Local Assistant"
3. The `config.yaml` file opens in your editor
![local-config-open-steps](/images/local-config-open-steps.png)
### The Local Assistant Experience
When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required.
The first time you use Continue, it generates a `config.yaml` with sensible defaults. From there, you can customize everything from model selection to context providers, slash commands, and more.
For the complete configuration reference, see our [config.yaml documentation](/reference).
## Making the Right Choice
The decision between Hub and Local assistants often comes down to your specific needs and constraints. Here's a framework to help you decide:
### Choose Hub Assistants When You:
**Value Convenience Over Control**
- Want to start coding with AI assistance in under 60 seconds
- Prefer visual interfaces over editing configuration files
- Need to switch between multiple machines frequently
- Work in a team that needs standardized AI assistance
**Need Advanced Collaboration**
- Want to share custom assistants with teammates
- Need centralized API key management
- Require quick updates across your entire organization
**Are Getting Started**
- New to AI-powered development
- Want to experiment with different models and configurations
- Prefer guided setup experiences
### Choose Local Assistants When You:
**Require Maximum Control**
- Need to version control your exact configuration
- Want to customize every aspect of the AI behavior
- Require reproducible development environments
**Have Privacy Requirements**
- Work with sensitive code that requires air-gapped environments
- Need to ensure all configuration data stays local
- Have strict compliance requirements about data storage
**Are a Power User**
- Comfortable editing YAML/JSON files
- Want access to experimental features
- Need to integrate with local tools and scripts
## The Hybrid Approach
Here's a secret: you don't have to choose just one. Many developers use both approaches:
- **Hub Assistants** for general development and experimentation
- **Local Assistants** for production work or client projects with specific requirements
You can switch between them seamlessly using the assistant selector in your IDE.
## Common Patterns and Best Practices
### For Hub Assistant Users
1. **Start with Community Assistants**: Before creating your own, explore what others have built
2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature
3. **Create Specialized Assistants**: Make different assistants for different contexts (frontend, backend, DevOps)
4. **Share Liberally**: If you create something useful, share it with the community
### For Local Assistant Users
1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history
2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values
3. **Document Your Setup**: Add comments to your config explaining non-obvious choices
4. **Keep a Backup**: Before major changes, save a working copy of your configuration
## Troubleshooting and Tips
### Hub Assistant Issues
**Changes Not Reflecting?**
- Click "Reload config" in your IDE
- Check your internet connection
- Ensure you're signed in to the correct account
**Assistant Not Available?**
- Verify it's added to your account on the hub
- Check if it requires specific API keys
### Local Assistant Issues
**Config Not Loading?**
- Verify file location matches your OS
- Check YAML syntax (Continue will show errors)
- Ensure file permissions allow reading
**Autocomplete Not Working?**
- Update to the latest Continue version
- Check that you're editing the correct file
## Next Steps
Now that you understand both configuration approaches, you're ready to dive deeper:
- **For Hub Users**: [Create Your First Assistant](/hub/assistants/create-an-assistant)
- **For Local Users**: [Explore the Config Reference](/reference)
- **For Everyone**: [Discover Available Models](/customize/model-providers/overview)
Remember, the best configuration is the one that helps you code more effectively. Start simple, experiment freely, and gradually refine your setup as you discover what works best for your workflow.
Happy coding with Continue! 🚀

View file

@ -34,11 +34,11 @@ This is the only configuration necessary, but you can view the full list of opti
### 4. Commit and push
Add the [YAML for your assistants and blocks](/reference) to the appropriate directories:
Add the [YAML for your assistants and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the assistant/block.
- `assistants/public` for public assistants
- `assistants/private` for private (visible only within your organization) assistants
- `blocks/public` for public blocks
- `blocks/private` for private blocks
Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev.
Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s).

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

14
docs/package-lock.json generated
View file

@ -2801,14 +2801,14 @@
}
},
"node_modules/axios": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz",
"integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==",
"dev": true,
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@ -4948,9 +4948,9 @@
}
},
"node_modules/form-data": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.3.tgz",
"integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"dev": true,
"license": "MIT",
"dependencies": {

View file

@ -175,7 +175,11 @@ The `models` section defines the language models used in your configuration. Mod
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include:
- `tool_use`: Enables function/tool calling support (required for Agent mode)
- `image_input`: Enables image upload and processing support
Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information.
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.

View file

@ -135,6 +135,64 @@ If you are having persistent errors with indexing, our recommendation is to rebu
This can be accomplished using the following command: `Continue: Rebuild codebase index`.
### Agent mode is unavailable or tools aren't working
If Agent mode is grayed out or tools aren't functioning properly, this is likely due to model capability configuration issues.
<Info>
Continue uses system message tools as a fallback for models without native tool support, so most models should work with Agent mode automatically.
</Info>
#### Check if your model has tool support
1. Not all models support native tool/function calling, but Continue will automatically use system message tools as a fallback
2. Try adding `capabilities: ["tool_use"]` to your model config to force tool support
3. Verify your provider supports function calling or that system message tools are working correctly
#### Tools Not Working
If tools aren't being called:
1. Ensure `tool_use` is in your capabilities
2. Check that your API endpoint actually supports function calling
3. Some providers may use different function calling formats
#### Images Not Uploading
If you can't upload images:
1. Add `image_input` to capabilities
2. Ensure your model actually supports vision (e.g., gpt-4-vision, claude-3)
3. Check that your provider passes through image data
#### Add capabilities
If Continue's autodetection isn't working correctly, you can manually add capabilities in your `config.yaml`:
```yaml
models:
- name: my-model
provider: openai
model: gpt-4
capabilities:
- tool_use
- image_input
```
#### Verify with provider
Some proxy services (like OpenRouter) or custom deployments may not preserve tool calling capabilities. Check your provider's documentation.
#### Verifying Current Capabilities
To see what capabilities Continue detected for your model:
1. Check the mode selector tooltips - they indicate if tools are available
2. Try uploading an image - if disabled, the model lacks `image_input`
3. Check if Agent mode is available - requires `tool_use`
See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for complete configuration details.
### Android Studio - "Nothing to show" in Chat
This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details.

View file

@ -1,30 +0,0 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.vfs.AsyncFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
class AsyncFileSaveListener(private val continuePluginService: ContinuePluginService) : AsyncFileListener {
private val configFilePatterns = listOf(
".continue/config.json",
".continue/config.ts",
".continue/config.yaml",
".continuerc.json"
)
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier? {
val isConfigFile = events.any { event ->
configFilePatterns.any { pattern ->
event.path.endsWith(pattern) || event.path.endsWith(pattern.replace("/", "\\"))
}
}
return if (isConfigFile) {
object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
continuePluginService.coreMessenger?.request("config/reload", null, null) { _ -> }
}
}
} else null
}
}

View file

@ -48,12 +48,7 @@ class IdeProtocolClient(
@OptIn(ExperimentalCoroutinesApi::class)
private val limitedDispatcher = Dispatchers.IO.limitedParallelism(4)
init {
// Setup config.json / config.ts save listeners
VirtualFileManager.getInstance().addAsyncFileListener(
AsyncFileSaveListener(continuePluginService), project.service<ContinuePluginDisposable>()
)
}
init {}
fun handleMessage(msg: String, respond: (Any?) -> Unit) {
coroutineScope.launch(limitedDispatcher) {

View file

@ -287,6 +287,7 @@ describe("GUI Test", () => {
}).timeout(DEFAULT_TIMEOUT.MD);
it("should render tool call", async () => {
await GUIActions.toggleToolPolicy(view, "view_diff", 0);
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");
await messageInput.sendKeys(Key.ENTER);

View file

@ -42,11 +42,25 @@ describe("Prompt file", () => {
"terminal",
"tree",
];
for (const provider of providers) {
await editor.typeText("@" + provider.slice(0, 2));
await editor.typeText(Key.ENTER);
// Type the @ symbol to trigger completion
await editor.typeText("@");
// Wait a moment for the completion to appear
await new Promise((resolve) => setTimeout(resolve, 500));
// Type the first few characters
await editor.typeText(provider.slice(0, 2));
// Wait for completion popup to update
await new Promise((resolve) => setTimeout(resolve, 300));
// Use Tab to accept completion instead of Enter
await editor.typeText(Key.TAB);
const text = await editor.getText();
expect(text).equals("@" + provider);
expect(text).to.include("@" + provider);
await editor.clearText();
}

View file

@ -55,8 +55,6 @@ console.log("[info] Using target: ", target);
const exe = os === "win32" ? ".exe" : "";
const isInGitHubAction = !!process.env.GITHUB_ACTIONS;
const isArmTarget =
target === "darwin-arm64" ||
target === "linux-arm64" ||
@ -86,15 +84,6 @@ void (async () => {
process.chdir(path.join(continueDir, "gui"));
if (isInGitHubAction) {
const guiBuildStart = Date.now();
console.log(`[timer] Starting GUI build at ${new Date().toISOString()}`);
execCmdSync("npm run build");
console.log(
`[timer] GUI build completed in ${Date.now() - guiBuildStart}ms`,
);
}
// Copy over the dist folder to the JetBrains extension //
const intellijExtensionWebviewPath = path.join(
"..",
@ -140,6 +129,7 @@ void (async () => {
// Then copy over the dist folder to the VSCode extension //
const vscodeGuiPath = path.join("../extensions/vscode/gui");
rimrafSync(vscodeGuiPath);
fs.mkdirSync(vscodeGuiPath, { recursive: true });
const vscodeCopyStart = Date.now();
console.log(`[timer] Starting VSCode copy at ${new Date().toISOString()}`);

View file

@ -251,6 +251,7 @@ export class VsCodeExtension {
let orgId = queryParams.get("org_id");
this.core.invoke("config/refreshProfiles", {
reason: "VS Code deep link",
selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined),
selectProfileId:
profileId === "null" ? undefined : (profileId ?? undefined),

View file

@ -0,0 +1,24 @@
import styled, { keyframes } from "styled-components";
const ellipsisAnimation = keyframes`
0% { width: 0; }
33% { width: 0.33em; }
66% { width: 0.66em; }
100% { width: 1em; }
`;
export const AnimatedEllipsis = styled.span`
display: inline-block;
width: 1em; /* Fixed width to match the maximum animation width */
&::after {
content: "...";
display: inline-block;
overflow: hidden;
vertical-align: bottom;
animation: ${ellipsisAnimation} 2s infinite;
width: 0;
}
`;
export default AnimatedEllipsis;

View file

@ -152,7 +152,9 @@ export function AssistantAndOrgListbox() {
value="reload-assistant"
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={() => refreshProfiles()}
onClick={() =>
refreshProfiles("Manual refresh from assistant list")
}
>
<span
className="text-description flex flex-row items-center"

View file

@ -15,7 +15,6 @@ import { saveCurrentSession } from "../redux/thunks/session";
import { fontSize, isMetaEquivalentKeyPressed } from "../util";
import { incrementFreeTrialCount } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
import { FatalErrorIndicator } from "./config/FatalErrorNotice";
import TextDialog from "./dialogs";
import { GenerateRuleDialog } from "./GenerateRuleDialog";
import { LumpProvider } from "./mainInput/Lump/LumpContext";
@ -280,7 +279,6 @@ const Layout = () => {
<GridDiv>
<PostHogPageView />
<Outlet />
<FatalErrorIndicator />
</GridDiv>
</div>
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />

View file

@ -16,14 +16,16 @@ export function OnboardingModelsAddOnTab() {
const isJetbrains = getLocalStorage("ide") === "jetbrains";
// Polling effect for JetBrains
// This is because jetbrains doesn't support deeplinking the same way as VS Code
useEffect(() => {
if (!isPolling || !isJetbrains) return;
const interval = setInterval(() => {
ideMessenger.post("config/refreshProfiles", {
reason: "Jetbrains onboarding polling",
selectProfileId: "local",
});
}, 5000);
}, 7000);
return () => clearInterval(interval);
}, [isPolling, isJetbrains, ideMessenger]);

View file

@ -2,7 +2,7 @@ import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { TrashIcon } from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { useState } from "react";
import { AnimatedEllipsis } from "../";
import { AnimatedEllipsis } from "../AnimatedEllipsis";
import { useAppSelector } from "../../redux/hooks";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useDeleteCompaction } from "../../util/compactConversation";

View file

@ -1,11 +1,16 @@
import { useMemo } from "react";
import { useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { ROUTES } from "../../util/navigation";
import Alert from "../gui/Alert";
import { useLump } from "../mainInput/Lump/LumpContext";
export const FatalErrorIndicator = () => {
const { refreshProfiles } = useAuth();
const configError = useAppSelector((store) => store.config.configError);
const ideMessenger = useContext(IdeMessengerContext);
const navigate = useNavigate();
@ -13,25 +18,62 @@ export const FatalErrorIndicator = () => {
return configError?.some((error) => error.fatal);
}, [configError]);
const { setSelectedSection } = useLump();
const { setSelectedSection, selectedSection } = useLump();
const configLoading = useAppSelector((state) => state.config.loading);
const showLumpErrorSection = () => {
navigate(ROUTES.HOME);
setSelectedSection("error");
};
const { selectedProfile } = useAuth();
if (!hasFatalErrors) {
return null;
}
const displayName =
selectedProfile?.title ??
`${selectedProfile?.fullSlug?.ownerSlug}/${selectedProfile?.fullSlug?.packageSlug}` ??
"assistant";
return (
<div
className="z-50 cursor-pointer bg-red-600 p-4 text-center text-white"
role="alert"
onClick={showLumpErrorSection}
>
<strong className="font-bold">Error!</strong>{" "}
<span className="block sm:inline">Could not load config</span>
<div className="mt-2 underline">Learn More</div>
</div>
<Alert type="error" className="mx-2 my-1 px-2">
<span>{`Error loading`}</span>{" "}
<span className="italic">{displayName}</span>
{". "}
<span>{`Chat is disabled until a model is available.`}</span>
<div className="mt-2 flex flex-row flex-wrap items-center gap-x-3 gap-y-1.5">
<div
onClick={() => {
ideMessenger.post(
"openUrl",
"https://docs.continue.dev/troubleshooting",
);
}}
className="cursor-pointer underline"
>
Help
</div>
{configLoading ? (
<div>Reloading...</div>
) : (
<div
className={`cursor-pointer underline`}
onClick={() => {
refreshProfiles("Clicked reload in fatal indicator");
}}
>
Reload
</div>
)}
<div
onClick={showLumpErrorSection}
className={`cursor-pointer underline transition-all ${selectedSection === "error" ? "opacity-0" : ""}`}
>
View
</div>
</div>
</Alert>
);
};

View file

@ -4,14 +4,12 @@ import {
ExclamationTriangleIcon,
InformationCircleIcon,
} from "@heroicons/react/16/solid";
import { ReactNode } from "react";
import { vscBackground } from "..";
import { cn } from "../../util/cn";
type AlertTypes = "info" | "success" | "warning" | "error";
type AlertSize = "sm" | "lg";
export interface AlertProps {
children?: ReactNode;
export interface AlertProps extends React.HTMLAttributes<HTMLDivElement> {
type?: AlertTypes;
size?: AlertSize;
}
@ -19,55 +17,72 @@ export interface AlertProps {
type AlertConfig = {
[key in AlertTypes]: {
Icon: any;
iconColor: string;
background: string;
border: string;
text: string;
};
};
const ALERT_CONFIGS: AlertConfig = {
info: {
Icon: InformationCircleIcon,
background: "bg-background",
border: "border-foreground",
iconColor: "text-foreground",
text: "text-foreground",
},
success: {
Icon: CheckCircleIcon,
background: "bg-green-600/20",
border: "border-success",
iconColor: "text-success",
text: "text-foreground",
},
warning: {
Icon: ExclamationTriangleIcon,
background: "bg-yellow-600/20",
border: "border-warning",
iconColor: "text-warning",
text: "text-foreground",
},
error: {
Icon: ExclamationCircleIcon,
background: "bg-red-600/20",
border: "border-error",
iconColor: "text-error",
text: "text-foreground",
},
};
const alertSizes = {
sm: "px-2 py-1.5 rounded border-l-2",
lg: "px-4 py-3 rounded-lg border-l-4",
sm: "px-3 py-1.5 rounded-md border",
lg: "px-4 py-3 rounded-md border",
};
const iconSizes = {
sm: "h-3 w-3",
lg: "h-5 w-5",
sm: "h-4 w-4 mt-1",
lg: "h-5 w-5 mt-0.5",
};
const spacingSizes = {
sm: "ml-1.5",
sm: "ml-2",
lg: "ml-3",
};
function Alert({ children, type = "info", size = "lg" }: AlertProps) {
const { Icon } = ALERT_CONFIGS[type];
function Alert({ type = "info", size = "lg", ...props }: AlertProps) {
const { Icon, background, border, text, iconColor } = ALERT_CONFIGS[type];
return (
<div
className={`bg-editor-foreground opacity-70 shadow-none ${alertSizes[size]}`}
className={cn(
`flex flex-row items-start ${background} border-[0.5px] border-solid ${border} shadow-sm ${alertSizes[size]}`,
props.className,
)}
>
<div className="flex items-center">
<Icon
className={`flex-shrink-0 ${iconSizes[size]}`}
style={{ color: vscBackground }}
/>
<div className={spacingSizes[size]} style={{ color: vscBackground }}>
{children}
</div>
<Icon className={`flex-shrink-0 ${iconColor} ${iconSizes[size]}`} />
<div className="flex flex-1 flex-col">
<div className={`${spacingSizes[size]} ${text}`}>{props.children}</div>
</div>
</div>
);

View file

@ -1,4 +1,4 @@
import styled, { keyframes } from "styled-components";
import styled from "styled-components";
import { varWithFallback } from "../styles/theme";
export const defaultBorderRadius = "0.5rem";
@ -199,21 +199,3 @@ export const CloseButton = styled.button`
justify-content: center;
cursor: pointer;
`;
const ellipsisAnimation = keyframes`
0% { width: 0; }
33% { width: 0.33em; }
66% { width: 0.66em; }
100% { width: 1em; }
`;
export const AnimatedEllipsis = styled.span`
&::after {
content: "...";
display: inline-block;
overflow: hidden;
vertical-align: bottom;
animation: ${ellipsisAnimation} 2s infinite;
width: 0;
}
`;

View file

@ -1,4 +1,4 @@
import { AnimatedEllipsis } from "../../..";
import { AnimatedEllipsis } from "../../../AnimatedEllipsis";
export function GeneratingIndicator({
text = "Generating",

View file

@ -2,17 +2,45 @@ import {
ExclamationCircleIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { useAuth } from "../../../../../context/Auth";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../../redux/hooks";
export function ErrorSection() {
const configError = useAppSelector((state) => state.config.configError);
const configLoading = useAppSelector((state) => state.config.loading);
const ideMessenger = useContext(IdeMessengerContext);
const { refreshProfiles } = useAuth();
const sortedErrors = configError
? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0))
: [];
return (
<div className="flex flex-col gap-5 p-2">
<div className="flex flex-col gap-2 p-2">
<div className="flex flex-row items-center justify-end gap-1.5">
<div
className={`text-description cursor-pointer text-xs underline transition-all ${configLoading ? "opacity-0" : ""}`}
onClick={() => {
refreshProfiles("Clicked reload in Error section");
}}
>
Reload
</div>
<div
onClick={() => {
ideMessenger.post(
"openUrl",
"https://docs.continue.dev/troubleshooting",
);
}}
className="text-description cursor-pointer text-xs underline"
>
Help
</div>
</div>
<ul className="m-0 list-none space-y-4 p-0">
{sortedErrors.map((error, index) => (
<li

View file

@ -189,7 +189,7 @@ describe("processEditorContent", () => {
expect(result.parts).toEqual([
{
type: "text",
text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n",
text: "Check this code:\n\n```js example.js (1-1)\nfunction test() {\n return 'hello';\n}\n```\n",
},
]);
expect(result.selectedCode).toHaveLength(1);
@ -347,7 +347,7 @@ describe("processEditorContent", () => {
expect(result.parts).toEqual([
{
type: "text",
text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?",
text: "Please explain this code and also check @related\n\n```ts script.ts (1-1)\nconst x = 42;\n```\n\nWhat does this constant do?",
},
{
type: "imageUrl",

View file

@ -96,7 +96,7 @@ export function processEditorContent(editorState: JSONContent) {
rif.filepath,
window.workspacePaths ?? [],
);
const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
const codeText = `\n\`\`\`${extension} ${relativePathOrBasename} (${rif.range.start.line + 1}-${rif.range.end.line + 1})\n${contextItem.content}\n\`\`\`\n`;
if (parts[parts.length - 1]?.type === "text") {
(parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText;

View file

@ -3,13 +3,13 @@ import { ContextItemWithId } from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { getUriPathBasename } from "core/util/uri";
import { ComponentType, useContext, useMemo } from "react";
import { AnimatedEllipsis } from "../..";
import {
IdeMessengerContext,
IIdeMessenger,
} from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import { selectIsGatheringContext } from "../../../redux/slices/sessionSlice";
import { AnimatedEllipsis } from "../../AnimatedEllipsis";
import FileIcon from "../../FileIcon";
import SafeImg from "../../SafeImg";
import ToggleDiv from "../../ToggleDiv";

View file

@ -4,8 +4,10 @@ import { ChevronUpIcon } from "@heroicons/react/24/solid";
import { ChatHistoryItem } from "core";
import { useEffect, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscBackground } from "../..";
import { getFontSize } from "../../../util";
import { AnimatedEllipsis } from "../../AnimatedEllipsis";
import StyledMarkdownPreview from "../../StyledMarkdownPreview";
const SpoilerButton = styled.div`
@ -36,34 +38,11 @@ const ButtonContent = styled.div`
gap: 6px;
`;
export const ThinkingText = styled.span`
position: relative;
padding-right: 12px;
const ThinkingTextContainer = styled.span`
display: inline-block;
min-width: fit-content;
&:after {
content: "...";
position: absolute;
animation: ellipsis 1s steps(4, end) infinite;
width: 0px;
display: inline-block;
overflow: hidden;
}
@keyframes ellipsis {
0%,
100% {
width: 0px;
}
33% {
width: 8px;
}
66% {
width: 16px;
}
90% {
width: 24px;
}
}
padding-right: 1em; /* Reserve space for the ellipsis animation */
`;
const MarkdownWrapper = styled.div`
@ -120,12 +99,13 @@ function ThinkingBlockPeek({
className="flex items-center justify-start pl-2 text-xs text-gray-300"
data-testid="thinking-block-peek"
>
<SpoilerButton onClick={() => setOpen((prev) => !prev)}>
<SpoilerButton onClick={() => setOpen(!open)}>
<ButtonContent>
{inProgress ? (
<ThinkingText>
<span>
{redactedThinking ? "Redacted Thinking" : "Thinking"}
</ThinkingText>
<AnimatedEllipsis />
</span>
) : redactedThinking ? (
"Redacted Thinking"
) : (
@ -141,7 +121,6 @@ function ThinkingBlockPeek({
</ButtonContent>
</SpoilerButton>
</div>
<div
className={`ml-2 mt-2 overflow-y-auto transition-none duration-300 ease-in-out ${
open ? "mb-2 mt-5 opacity-100" : "max-h-0 border-0 opacity-0"

View file

@ -135,7 +135,7 @@ function ModelSelect() {
};
}),
);
}, [config]);
}, [allModels]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {

View file

@ -11,7 +11,7 @@ type ButtonProps = React.ComponentProps<"button"> & {
const buttonVariants = {
primary:
"border-none text-foreground bg-primary hover:enabled:brightness-125",
"border-none text-primary-foreground bg-primary hover:enabled:brightness-125",
secondary:
"border-none text-foreground bg-border hover:enabled:brightness-125",
outline:

View file

@ -27,7 +27,7 @@ interface AuthContextType {
login: (useOnboarding: boolean) => Promise<boolean>;
selectedProfile: ProfileDescription | null;
profiles: ProfileDescription[] | null;
refreshProfiles: () => Promise<void>;
refreshProfiles: (reason?: string) => Promise<void>;
organizations: SerializedOrgWithProfiles[];
}
@ -99,18 +99,23 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
[],
);
const refreshProfiles = useCallback(async () => {
try {
dispatch(setConfigLoading(true));
await ideMessenger.request("config/refreshProfiles", undefined);
ideMessenger.post("showToast", ["info", "Config refreshed"]);
} catch (e) {
console.error("Failed to refresh profiles", e);
ideMessenger.post("showToast", ["error", "Failed to refresh config"]);
} finally {
dispatch(setConfigLoading(false));
}
}, [ideMessenger]);
const refreshProfiles = useCallback(
async (reason?: string) => {
try {
dispatch(setConfigLoading(true));
await ideMessenger.request("config/refreshProfiles", {
reason,
});
ideMessenger.post("showToast", ["info", "Config refreshed"]);
} catch (e) {
console.error("Failed to refresh profiles", e);
ideMessenger.post("showToast", ["error", "Failed to refresh config"]);
} finally {
dispatch(setConfigLoading(false));
}
},
[ideMessenger],
);
return (
<AuthContext.Provider

View file

@ -30,7 +30,6 @@ import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfter
import { store } from "../redux/store";
import { cancelStream } from "../redux/thunks/cancelStream";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
import { findToolCallById, logToolUsage } from "../redux/util";
import {
@ -220,16 +219,6 @@ function ParallelListeners() {
dispatch(setTTSActive(status));
});
// TODO - remove?
useWebviewListener("submitMessage", async (data) => {
void dispatch(
streamResponseThunk({
editorState: data.message,
modifiers: { useCodebase: false, noContext: true },
}),
);
});
useWebviewListener("addContextItem", async (data) => {
dispatch(
addContextItemsAtIndex({

View file

@ -1,5 +1,5 @@
import { IndexingProgressUpdate } from "core";
import { AnimatedEllipsis } from "../../../components";
import { AnimatedEllipsis } from "../../../components/AnimatedEllipsis";
export interface IndexingProgressTitleTextProps {
update: IndexingProgressUpdate;

View file

@ -43,6 +43,7 @@ import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import { ToolCallDiv } from "./ToolCallDiv";
import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice";
import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { EmptyChatBody } from "./EmptyChatBody";
@ -447,6 +448,7 @@ export function Chat() {
)}
</div>
</div>
<FatalErrorIndicator />
{!hasDismissedExploreDialog && <ExploreDialogWatcher />}
{history.length === 0 && (
<EmptyChatBody showOnboardingCard={onboardingCard.show} />

View file

@ -45,7 +45,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
} = useMemo(() => analyzeError(error, selectedModel), [error, selectedModel]);
const handleRefreshProfiles = () => {
void refreshProfiles();
void refreshProfiles("Clicked reload config from stream error dialog");
dispatch(setShowDialog(false));
dispatch(setDialogMessage(undefined));
};

View file

@ -10,7 +10,10 @@ import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump
import { waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { ChatMessage } from "core";
import { toggleToolSetting } from "../../../redux/slices/uiSlice";
import {
setToolPolicy,
toggleToolSetting,
} from "../../../redux/slices/uiSlice";
import {
getElementByTestId,
getElementByText,
@ -173,7 +176,12 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
addAndSelectMockLlm(store, ideMessenger);
// Enable automatic edit and yolo mode
store.dispatch(toggleToolSetting(BuiltInToolNames.EditExistingFile));
store.dispatch(
setToolPolicy({
toolName: BuiltInToolNames.EditExistingFile,
policy: "allowedWithoutPermission",
}),
);
triggerConfigUpdate({
store,
ideMessenger,

View file

@ -10,11 +10,18 @@ export const selectSlashCommandComboBoxInputs = createSelector(
(slashCommands) => {
return (
slashCommands?.map((cmd) => {
let content = cmd.prompt;
// For MCP prompts without content, show that it failed to load
if (cmd.source === "mcp-prompt" && !content) {
content = "[MCP Prompt - failed to load content during startup]";
}
return {
title: cmd.name,
description: cmd.description,
type: "slashCommand" as ComboBoxItemType,
content: cmd.prompt,
content: content,
} as ComboBoxItem;
}) || []
);

View file

@ -1,6 +1,7 @@
import { createSelector } from "@reduxjs/toolkit";
import { Tool } from "core";
import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import { RootState } from "../store";
export const selectActiveTools = createSelector(
@ -14,11 +15,15 @@ export const selectActiveTools = createSelector(
if (mode === "chat") {
return [];
} else {
const enabledTools = tools.filter(
(tool) =>
policies[tool.function.name] !== "disabled" &&
groupPolicies[tool.group] !== "exclude",
);
const enabledTools = tools.filter((tool) => {
const toolPolicy =
policies[tool.function.name] ??
tool.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
return (
toolPolicy !== "disabled" && groupPolicies[tool.group] !== "exclude"
);
});
if (mode === "plan") {
return enabledTools.filter(
(t) => t.group !== BUILT_IN_GROUP_NAME || t.readonly,

View file

@ -1,5 +1,5 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RuleWithSource, Tool } from "core";
import { RuleWithSource, Tool, ToolPolicy } from "core";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn";
import {
defaultOnboardingCardState,
@ -7,11 +7,6 @@ import {
} from "../../components/OnboardingCard";
import { getLocalStorage, LocalStorageKey } from "../../util/localStorage";
export type ToolPolicy =
| "allowedWithPermission"
| "allowedWithoutPermission"
| "disabled";
export type RulePolicy = "on" | "off";
export type ToolGroupPolicy = "include" | "exclude";
@ -50,21 +45,7 @@ export const uiSlice = createSlice({
),
shouldAddFileForEditing: false,
ttsActive: false,
toolSettings: {
[BuiltInToolNames.ReadFile]: "allowedWithoutPermission",
[BuiltInToolNames.EditExistingFile]: "allowedWithPermission",
[BuiltInToolNames.CreateNewFile]: "allowedWithPermission",
[BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission",
[BuiltInToolNames.GrepSearch]: "allowedWithoutPermission",
[BuiltInToolNames.FileGlobSearch]: "allowedWithoutPermission",
[BuiltInToolNames.SearchWeb]: "allowedWithoutPermission",
[BuiltInToolNames.FetchUrlContent]: "allowedWithPermission",
[BuiltInToolNames.ViewDiff]: "allowedWithoutPermission",
[BuiltInToolNames.LSTool]: "allowedWithoutPermission",
[BuiltInToolNames.CreateRuleBlock]: "allowedWithPermission",
[BuiltInToolNames.RequestRule]: "disabled",
[BuiltInToolNames.SearchAndReplaceInFile]: "allowedWithPermission",
},
toolSettings: {},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
@ -95,7 +76,7 @@ export const uiSlice = createSlice({
// Tools
addTool: (state, action: PayloadAction<Tool>) => {
state.toolSettings[action.payload.function.name] =
"allowedWithPermission";
action.payload.defaultToolPolicy ?? DEFAULT_TOOL_SETTING;
},
setToolPolicy: (
state,

View file

@ -1,9 +1,6 @@
import { ToolPolicy } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import {
clearToolPolicy,
setToolPolicy,
ToolPolicy,
} from "../redux/slices/uiSlice";
import { clearToolPolicy, setToolPolicy } from "../redux/slices/uiSlice";
import { AppDispatch } from "../redux/store";
const validPolicyValues: ToolPolicy[] = [

View file

@ -5,8 +5,8 @@
"tsc:watch:vscode": "tsc --project extensions/vscode/tsconfig.json --watch --noEmit --pretty",
"tsc:watch:core": "tsc --project core/tsconfig.json --watch --noEmit --pretty",
"tsc:watch:binary": "tsc --project binary/tsconfig.json --watch --noEmit --pretty",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore"
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore"
},
"devDependencies": {
"@typescript-eslint/parser": "^7.8.0",

Some files were not shown because too many files have changed in this diff Show more