Merge branch 'main' into pe/remove-tools

This commit is contained in:
Nate 2025-03-12 09:47:35 -07:00
commit 745d239619
117 changed files with 2685 additions and 761 deletions

View file

@ -5,4 +5,5 @@ docs/docs/languages
.vscode/
.archive/
**/*.scm
**/*.diff
**/*.diff
.continue/

View file

@ -275,7 +275,7 @@ jobs:
cd core
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }}
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@ -303,7 +303,13 @@ jobs:
cd extensions/vscode
npm ci
npm run e2e:compile
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then
# Exclude SSH tests for forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .)
else
# Include all tests for non-forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
fi
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
@ -409,6 +415,14 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
# We don't want to cache the Continue extension, so it is deleted at the end of the job
- uses: actions/cache@v4
id: test-extensions-cache
with:
path: extensions/vscode/e2e/.test-extensions
# package.json used as the key because that's where the download script is defined
key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }}
- name: Download build artifact
uses: actions/download-artifact@v4
with:
@ -436,7 +450,7 @@ jobs:
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts
echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
if: ${{ github.event.pull_request.head.repo.fork == false }}
if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}
- name: Set up Xvfb
run: |
@ -446,10 +460,15 @@ jobs:
- name: Run e2e tests
run: |
cd extensions/vscode
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
env:
DISPLAY: :99
- name: Delete continue from test extensions
run: |
cd extensions/vscode
rm -rf e2e/.test-extensions/continue*
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4

View file

@ -0,0 +1,25 @@
name: "Label / close stale issues"
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!"
stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue."
days-before-stale: 90
days-before-close: 10
days-before-pr-stale: -1
days-before-pr-close: -1
operations-per-run: 1000
stale-issue-label: "stale"
stale-pr-label: "stale"
exempt-issue-labels: "needs-triage,no-stale,high,highest"
exempt-pr-labels: "no-stale"

3
.gitignore vendored
View file

@ -168,4 +168,5 @@ extensions/.continue-debug/
*.vsix
.continuerules
.continuerules
.continue/assistants/

View file

@ -2,8 +2,7 @@ import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = {
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const ig = ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(getGlobalContinueIgArray());
const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
const entries = await ide.listDir(dir);
const ignoreUri = joinPathsToUri(dir, ".gitignore");

View file

@ -1,5 +1,3 @@
import * as fs from "node:fs";
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
import {
@ -17,9 +15,8 @@ import {
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
import { localPathToUri } from "../util/pathToUri.js";
import { getAllAssistantFiles } from "./getSystemPromptDotFile.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
LOCAL_ONBOARDING_PROVIDER_TITLE,
@ -86,6 +83,25 @@ export class ConfigHandler {
});
}
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
private async getLocalAssistantProfiles() {
const assistantFiles = await getAllAssistantFiles(this.ide);
const profiles = assistantFiles.map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
assistant,
);
});
return profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
);
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".
*
@ -98,13 +114,20 @@ export class ConfigHandler {
}
private async init() {
try {
await this.loadLocalProfilesOnly();
} catch (e) {
console.error("Failed to load local assistants: ", e);
}
try {
await this.fetchControlPlaneProfiles();
} catch (e) {
// If this fails, make sure at least local profile is loaded
console.error("Failed to fetch control plane profiles in init: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
await this.loadLocalProfilesOnly();
}
try {
const configResult = await this.loadConfig();
this.notifyConfigListeners(configResult);
@ -135,14 +158,12 @@ export class ConfigHandler {
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
const profile = this.profiles?.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
const ideInfo = await this.ide.getIdeInfo();
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
if (fs.existsSync(configYamlPath)) {
await this.ide.openFile(localPathToUri(configYamlPath));
} else {
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
}
await this.ide.openFile(profile.profileDescription.uri);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
@ -161,35 +182,39 @@ export class ConfigHandler {
let profiles: ProfileLifecycleManager[] | null = null;
if (!userId) {
// Not logged in
profiles = [this.localProfileManager];
const allLocalProfiles = await this.getAllLocalProfiles();
profiles = [...allLocalProfiles];
} else {
// Logged in
const assistants =
await this.controlPlaneClient.listAssistants(selectedOrgId);
const hubProfiles = assistants.map((assistant) => {
const profileLoader = new PlatformProfileLoader(
{
...assistant.configResult,
config: assistant.configResult.config,
},
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
const profileLoader = await PlatformProfileLoader.create(
{
...assistant.configResult,
config: assistant.configResult.config,
},
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
return new ProfileLifecycleManager(profileLoader, this.ide);
});
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
if (selectedOrgId === null) {
// Personal
profiles = [...hubProfiles, this.localProfileManager];
const allLocalProfiles = await this.getAllLocalProfiles();
profiles = [...hubProfiles, ...allLocalProfiles];
} else {
// Organization
profiles = hubProfiles;
@ -199,6 +224,16 @@ export class ConfigHandler {
await this.updateAvailableProfiles(profiles);
}
private async getAllLocalProfiles() {
const localAssistantProfiles = await this.getLocalAssistantProfiles();
return [this.localProfileManager, ...localAssistantProfiles];
}
private async loadLocalProfilesOnly() {
const allLocalProfiles = await this.getAllLocalProfiles();
await this.updateAvailableProfiles(allLocalProfiles);
}
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
this.profiles = profiles;
@ -278,7 +313,7 @@ export class ConfigHandler {
} else {
try {
const workspaces = await this.controlPlaneClient.listWorkspaces();
const profiles = [this.localProfileManager];
const profiles = await this.getAllLocalProfiles();
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
@ -296,7 +331,7 @@ export class ConfigHandler {
await this.updateAvailableProfiles(profiles);
} catch (e: any) {
console.error("Failed to load profiles: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
await this.loadLocalProfilesOnly();
}
}
}
@ -355,7 +390,7 @@ export class ConfigHandler {
);
this.fetchControlPlaneProfiles().catch(async (e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
await this.loadLocalProfilesOnly();
await this.reloadConfig();
});
}

View file

@ -21,6 +21,7 @@ export interface ProfileDescription {
id: string;
iconUrl: string;
errors: ConfigValidationError[] | undefined;
uri: string;
}
export interface OrganizationDescription {

View file

@ -1,4 +1,7 @@
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
import { getGlobalAssistantsPath } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { joinPathsToUri } from "../util/uri";
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
@ -24,3 +27,56 @@ export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
return prompts.join("\n\n");
}
export const ASSISTANTS_FOLDER = ".continue/assistants";
export async function getAssistantFilesFromDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const uris = await walkDir(dir, ide);
const assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
);
const results = assistantFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
return { path: uri, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}
export async function getAllAssistantFiles(
ide: IDE,
): Promise<{ path: string; content: string }[]> {
const workspaceDirs = await ide.getWorkspaceDirs();
let assistantFiles: { path: string; content: string }[] = [];
let dirsToCheck = [ASSISTANTS_FOLDER];
const fullDirs = workspaceDirs
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
.flat();
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
assistantFiles = (
await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir)))
).flat();
return await Promise.all(
assistantFiles.map(async (file) => {
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),
);
}

View file

@ -272,7 +272,7 @@ async function intermediateToFinalConfig(
{
...desc,
model: modelName,
title: `${llm.title} - ${modelName}`,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,

View file

@ -10,6 +10,7 @@ import {
} from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { PRODUCTION_ENV } from "../../control-plane/env.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
},
title: workspaceTitle,
errors: undefined,
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
};
setInterval(async () => {
@ -68,6 +70,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
undefined,
undefined,
this.workspaceId,
undefined,
);
return {

View file

@ -1,33 +1,54 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getPrimaryConfigFilePath } from "../../util/paths.js";
import { localPathToUri } from "../../util/pathToUri.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class LocalProfileLoader implements IProfileLoader {
static ID = "local";
description: ProfileDescription = {
id: LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: "Local Config",
errors: undefined,
};
constructor(
private ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private controlPlaneClient: ControlPlaneClient,
private writeLog: (message: string) => Promise<void>,
) {}
private overrideAssistantFile?:
| { path: string; content: string }
| undefined,
) {
const description: ProfileDescription = {
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: overrideAssistantFile?.path ?? "Local Config",
errors: undefined,
uri:
overrideAssistantFile?.path ??
localPathToUri(getPrimaryConfigFilePath()),
};
this.description = description;
if (overrideAssistantFile?.content) {
try {
const parsedAssistant = parseConfigYaml(
overrideAssistantFile?.content ?? "",
);
this.description.title = parsedAssistant.name;
} catch (e) {
console.error("Failed to parse assistant file: ", e);
}
}
}
description: ProfileDescription;
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig(
@ -39,6 +60,7 @@ export default class LocalProfileLoader implements IProfileLoader {
undefined,
undefined,
this.description.id,
this.overrideAssistantFile?.path,
);
this.description.errors = result.errors;

View file

@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -21,21 +22,35 @@ export interface PlatformConfigMetadata {
export default class PlatformProfileLoader implements IProfileLoader {
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
description: ProfileDescription;
constructor(
private constructor(
private configResult: ConfigResult<AssistantUnrolled>,
private readonly ownerSlug: string,
private readonly packageSlug: string,
private readonly iconUrl: string,
versionSlug: string,
private readonly versionSlug: string,
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private writeLog: (message: string) => Promise<void>,
private readonly onReload: () => void,
) {
this.description = {
readonly description: ProfileDescription,
) {}
static async create(
configResult: ConfigResult<AssistantUnrolled>,
ownerSlug: string,
packageSlug: string,
iconUrl: string,
versionSlug: string,
controlPlaneClient: ControlPlaneClient,
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
writeLog: (message: string) => Promise<void>,
onReload: () => void,
): Promise<PlatformProfileLoader> {
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
const description: ProfileDescription = {
id: `${ownerSlug}/${packageSlug}`,
profileType: "platform",
fullSlug: {
@ -45,8 +60,23 @@ export default class PlatformProfileLoader implements IProfileLoader {
},
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: this.iconUrl,
iconUrl: iconUrl,
uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
};
return new PlatformProfileLoader(
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
writeLog,
onReload,
description,
);
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
@ -70,6 +100,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
packageSlug: this.packageSlug,
},
this.description.id,
undefined,
);
return {

View file

@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
export default async function doLoadConfig(
ide: IDE,
@ -36,6 +37,7 @@ export default async function doLoadConfig(
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
profileId: string,
overrideConfigYamlByPath: string | undefined,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
@ -50,7 +52,9 @@ export default async function doLoadConfig(
migrateJsonSharedConfig(configJsonPath, ide);
}
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
const configYamlPath = localPathOrUriToPath(
overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
);
let newConfig: ContinueConfig | undefined;
let errors: ConfigValidationError[] | undefined;
@ -68,6 +72,7 @@ export default async function doLoadConfig(
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
);
newConfig = result.config;
errors = result.errors;

View file

@ -366,10 +366,14 @@ export async function loadContinueConfigFromYaml(
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
controlPlaneClient: ControlPlaneClient,
configYamlPath: string | undefined,
): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8")
? fs.readFileSync(
configYamlPath ?? getConfigYamlPath(ideInfo.ideType),
"utf-8",
)
: "";
const configYamlResult = await loadConfigYaml(

View file

@ -49,6 +49,10 @@ async function modelConfigToBaseLLM(
title: model.name,
systemMessage,
promptTemplates: model.promptTemplates,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),
},
};
if (model.embedOptions?.maxBatchSize) {
@ -127,7 +131,7 @@ async function autodetectModels(
{
...model,
model: modelName,
name: `${llm.title} - ${modelName}`,
name: modelName,
},
uniqueId,
ideSettings,

View file

@ -5,6 +5,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
IDE,
LoadSubmenuItemsArgs,
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
@ -36,6 +37,7 @@ class DocsContextProvider extends BaseContextProvider {
chunks: Chunk[],
reranker: NonNullable<ContextProviderExtras["reranker"]>,
fullInput: ContextProviderExtras["fullInput"],
ide: IDE,
) {
let chunksCopy = [...chunks];
@ -51,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider {
this.options?.nFinal ?? DocsContextProvider.nFinal,
);
} catch (e) {
console.warn(`Failed to rerank docs results: ${e}`);
void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
chunksCopy = chunksCopy.splice(
0,
@ -116,6 +118,7 @@ class DocsContextProvider extends BaseContextProvider {
chunks,
extras.reranker,
extras.fullInput,
extras.ide,
);
}

View file

@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
});
}
private async getRemoteBranchName(
private async getRemoteBranchInfo(
extras: ContextProviderExtras,
): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = /:(?<project>.*).git/.exec(remoteUrl);
let urlMatches: RegExpExecArray | null;
if (/https?.*/.test(remoteUrl)) {
const pathname = new URL(remoteUrl).pathname;
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
} else {
// ssh
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
}
const project = urlMatches?.groups?.project ?? null;
const project = urlMatches?.groups?.projectPath ?? null;
return {
branch: remoteBranch,
@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const { branch, project } = await this.getRemoteBranchName(extras);
const { branch, project } = await this.getRemoteBranchInfo(extras);
const api = await this.getApi();

View file

@ -80,24 +80,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
args: RetrievalPipelineRunArguments,
n: number,
): Promise<Chunk[]> {
try {
if (args.query.trim() === "") {
return [];
}
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
const tokens = this.escapeFtsQueryString(tokensRaw);
return await this.ftsIndex.retrieve({
n,
text: tokens,
tags: args.tags,
directory: args.filterDirectory,
});
} catch (e) {
console.warn("Error retrieving from FTS:", e);
if (args.query.trim() === "") {
return [];
}
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
const tokens = this.escapeFtsQueryString(tokensRaw);
return await this.ftsIndex.retrieve({
n,
text: tokens,
tags: args.tags,
directory: args.filterDirectory,
});
}
protected async retrieveAndChunkRecentlyEditedFiles(

View file

@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
let ftsChunks: Chunk[] = [];
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
}
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
let embeddingsChunks: Chunk[] = [];
try {
embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
console.error("Error retrieving embeddings:", error);
}
const recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
let recentlyEditedFilesChunks: Chunk[] = [];
try {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
console.error("Error retrieving recently edited files:", error);
}
const repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
let repoMapChunks: Chunk[] = [];
try {
repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
} catch (error) {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,

View file

@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
const recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
let ftsChunks: Chunk[] = [];
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
}
const repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
let embeddingsChunks: Chunk[] = [];
try {
embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
console.error("Error retrieving embeddings chunks:", error);
}
let recentlyEditedFilesChunks: Chunk[] = [];
try {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
console.error("Error retrieving recently edited files chunks:", error);
}
let repoMapChunks: Chunk[] = [];
try {
repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
} catch (error) {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen
retrievalResults = retrievalResults.filter(
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
(chunk) =>
!!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
);
}
@ -59,29 +82,37 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
// remove empty chunks -- some APIs fail on that
chunks = chunks.filter((chunk) => chunk.content);
let scores: number[] =
await this.options.config.selectedModelByRole.rerank.rerank(
input,
chunks,
try {
let scores: number[] =
await this.options.config.selectedModelByRole.rerank.rerank(
input,
chunks,
);
// Filter out low-scoring results
let results = chunks;
// let results = chunks.filter(
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
// );
// scores = scores.filter(
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
// );
const chunkIndexMap = new Map<Chunk, number>();
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
);
// Filter out low-scoring results
let results = chunks;
// let results = chunks.filter(
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
// );
// scores = scores.filter(
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
// );
const chunkIndexMap = new Map<Chunk, number>();
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
);
results = results.slice(-this.options.nFinal);
return results;
results = results.slice(-this.options.nFinal);
return results;
} catch (e) {
void this.options.ide.showToast(
"warning",
`Failed to rerank retrieval results\n${e}`,
);
return chunks.slice(-this.options.nFinal);
}
}
private async _expandWithEmbeddings(chunks: Chunk[]): Promise<Chunk[]> {

View file

@ -1,6 +1,7 @@
import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import generateRepoMap from "../../util/generateRepoMap";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { renderChatMessage } from "../../util/messageContent";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
@ -48,14 +49,14 @@ export async function requestFilesFromRepoMap(
const repoMap = await generateRepoMap(llm, ide, {
dirUris: filterDirUri ? [filterDirUri] : undefined,
includeSignatures: false,
outputRelativeUriPaths: false,
outputRelativeUriPaths: true,
});
const prompt = `${repoMap}
Given the above repo map, your task is to decide which files are most likely to be relevant in answering a question. Before giving your answer, you should write your reasoning about which files/folders are most important. This thinking should start with a <reasoning> tag, followed by a paragraph explaining your reasoning, and then a closing </reasoning> tag on the last line.
After this, your response should begin with a <results> tag, followed by a list of each file, one per line, and then a closing </results> tag on the last line. You should select between 5 and 10 files. The names that you list should be the full path from the root of the repo, not just the basename of the file.
After this, your response should begin with a <results> tag, followed by a list of each file, one per line, and then a closing </results> tag on the last line. You should select between 5 and 10 files. The names that you list should be the exact relative path that you saw in the repo map, not just the basename of the file.
This is the question that you should select relevant files for: "${input}"`;
@ -72,16 +73,20 @@ This is the question that you should select relevant files for: "${input}"`;
return [];
}
const fileUris = content
const filepaths = content
.split("<results>")[1]
?.split("</results>")[0]
?.split("\n")
.filter(Boolean)
.map((uri) => uri.trim());
.map((filepath) => filepath.trim());
const chunks = await Promise.all(
fileUris.map(async (uri) => {
const content = await ide.readFile(uri);
filepaths.map(async (filepath) => {
const uri = await resolveRelativePathInDir(filepath, ide);
if (!uri) {
return undefined;
}
const content = await ide.readFile(filepath);
const lineCount = content.split("\n").length;
const chunk: Chunk = {
digest: uri,
@ -95,7 +100,7 @@ This is the question that you should select relevant files for: "${input}"`;
}),
);
return chunks;
return chunks.filter((c) => c !== undefined) as Chunk[];
} catch (e) {
console.debug("Error requesting files from repo map", e);
return [];

View file

@ -1,6 +1,9 @@
import * as fs from "node:fs";
import { IdeSettings } from "..";
import { getStagingEnvironmentDotFilePath } from "../util/paths";
import {
getLocalEnvironmentDotFilePath,
getStagingEnvironmentDotFilePath,
} from "../util/paths";
export interface ControlPlaneEnv {
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
@ -18,7 +21,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
const WORKOS_ENV_ID_PRODUCTION = "continue";
const WORKOS_ENV_ID_STAGING = "continue-staging";
const PRODUCTION_ENV: ControlPlaneEnv = {
export const PRODUCTION_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL:
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
CONTROL_PLANE_URL:
@ -78,6 +81,11 @@ export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
): ControlPlaneEnv {
// Note .local overrides .staging
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
return LOCAL_ENV;
}
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
return STAGING_ENV;
}

View file

@ -1,7 +1,4 @@
import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import ignore from "ignore";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
@ -26,7 +23,6 @@ import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { getAllSuggestedDocs } from "./indexing/docs/suggestions";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -34,12 +30,7 @@ import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import {
editConfigJson,
getConfigJsonPath,
migrateV1DevDataFiles,
} from "./util/paths";
import { localPathToUri } from "./util/pathToUri";
import { editConfigJson, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -53,6 +44,7 @@ import {
type IndexingProgressUpdate,
} from ".";
import { shouldIgnore } from "./indexing/shouldIgnore";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -829,6 +821,10 @@ export class Core {
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
return; // TODO silent in case of commands?
}
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
@ -859,7 +855,10 @@ export class Core {
for (const uri of data.uris) {
// Listen for file changes in the workspace
// URI TODO is this equality statement valid?
if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) {
const currentProfileUri =
this.configHandler.currentProfile?.profileDescription.uri ?? "";
if (URI.equal(uri, currentProfileUri)) {
// Trigger a toast notification to provide UI feedback that config has been updated
const showToast =
this.globalContext.get("showConfigUpdateToast") ?? true;
@ -873,6 +872,8 @@ export class Core {
this.globalContext.update("showConfigUpdateToast", false);
}
}
await this.configHandler.reloadConfig();
continue;
}
if (
@ -886,32 +887,62 @@ export class Core {
uri.endsWith(".gitignore")
) {
// Reindex the workspaces
this.invoke("index/forceReIndex", undefined);
this.invoke("index/forceReIndex", {
shouldClearIndexes: true,
});
} else {
// Reindex the file
await this.refreshCodebaseIndexFiles([uri]);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
// Reindex the file
const ignore = await shouldIgnore(uri, this.ide);
if (!ignore) {
await this.refreshCodebaseIndexFiles([uri]);
}
}
}
}
}
});
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
const refreshIfNotIgnored = async (uris: string[]) => {
const toRefresh: string[] = [];
for (const uri of uris) {
const ignore = await shouldIgnore(uri, ide);
if (!ignore) {
toRefresh.push(uri);
}
}
if (toRefresh.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
await this.refreshCodebaseIndexFiles(toRefresh);
}
}
};
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
void refreshIfNotIgnored(data.uris);
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
void refreshIfNotIgnored(data.uris);
}
});
on("files/closed", async ({ data }) => {
if (data.uris) {
this.messenger.send("didCloseFiles", {
uris: data.uris,
});
}
});
on("files/opened", async ({ data }) => {
if (data?.uris?.length) {
// Do something on files opened
@ -950,15 +981,21 @@ export class Core {
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
on("didChangeSelectedProfile", async (msg) => {
await this.configHandler.setSelectedProfile(msg.data.id);
await this.configHandler.reloadConfig();
});
on("didChangeSelectedOrg", (msg) => {
void this.configHandler.setSelectedOrgId(msg.data.id);
void this.configHandler.reloadConfig();
void this.configHandler.loadAssistantsForSelectedOrg();
on("didChangeSelectedOrg", async (msg) => {
await this.configHandler.setSelectedOrgId(msg.data.id);
await this.configHandler.loadAssistantsForSelectedOrg();
if (msg.data.profileId) {
this.invoke("didChangeSelectedProfile", {
id: msg.data.profileId,
});
} else {
await this.configHandler.reloadConfig();
}
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
@ -975,19 +1012,15 @@ export class Core {
});
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
const ignoreInstance = ignore().add(defaultIgnoreFile);
let rootDirectory = await this.ide.getWorkspaceDirs();
const relativeFilePath = path.relative(rootDirectory[0], filepath);
try {
if (!ignoreInstance.ignores(relativeFilePath)) {
const ignore = shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
} catch (e) {
if (e instanceof RangeError) {
// do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json`
} else {
console.debug("unhandled ignores error", relativeFilePath, e);
}
console.error(
`didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
);
}
});

View file

@ -47,7 +47,7 @@ export class DataLogger {
newBody.eventName = eventName;
}
if ("timestamp" in zodSchema.shape) {
newBody.timestamp = new Date().toISOString();
newBody.timestamp = Date.now();
}
if ("schema" in zodSchema.shape) {
newBody.schema = schema;

View file

@ -5,6 +5,7 @@ import { getUriFileExtension } from "../../util/uri";
import { deterministicApplyLazyEdit } from "./deterministic";
import { streamLazyApply } from "./streamLazyApply";
import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply";
function canUseInstantApply(filename: string) {
const fileExtension = getUriFileExtension(filename);
@ -33,5 +34,16 @@ export async function applyCodeBlock(
}
}
// If the code block is a diff
if (isUnifiedDiffFormat(newFile)) {
try {
const diffLines = applyUnifiedDiff(oldFile, newFile);
const diffGenerator = generateLines(diffLines!);
return [true, diffGenerator];
} catch (e) {
console.error("Failed to apply unified diff", e);
}
}
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
}

View file

@ -0,0 +1,415 @@
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
describe("isUnifiedDiffFormat", () => {
it("should return true for valid unified diff format", () => {
const validDiff = `--- original.txt
+++ modified.txt
@@ -1,3 +1,4 @@
line1
-line2
+newline2
+newline3
line3`;
expect(isUnifiedDiffFormat(validDiff)).toBe(true);
});
it("should return false for empty diff", () => {
expect(isUnifiedDiffFormat("")).toBe(false);
});
it("should return false for diff without hunk header", () => {
const invalidDiff = `--- original.txt
+++ modified.txt
+line1
-line2
+line3`;
expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
});
it("should return false for diff without valid content", () => {
const invalidDiff = `--- original.txt
+++ modified.txt
@@ -1,3 +1,4 @@`;
expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
});
it("should return true even without file headers if hunk headers exist", () => {
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
line1
-line2
+newline2
+newline3
line3`;
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
});
it("should return true in case of empty lines", () => {
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
line1
-line2
+newline2
line3`;
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
});
});
describe("applyUnifiedDiff", () => {
it("should correctly apply a add line of unified diff", () => {
const sourceCode = `func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Calculator started! Available operations:")
fmt.Println(" + : Addition")
fmt.Println(" - : Subtraction")
fmt.Println(" * : Multiplication")
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
}
// End of file`;
const diffText = `--- original.go
+++ updated.go
@@ -30,6 +30,7 @@
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
+ fmt.Println(" log: Logarithm (use 'log base number')")
}`;
const result = applyUnifiedDiff(sourceCode, diffText);
const expected = [
{ type: "same", line: "func main() {" },
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
{ type: "same", line: " fmt.Println(\" / : Division\")" },
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
{ type: "same", line: "}" },
{ type: "same", line: "// End of file" }
];
expect(result).toEqual(expected);
});
it("should correctly apply multiple insertions and deletions", () => {
const sourceCode = `package main
import "fmt"
func main() {
fmt.Println("Hello")
fmt.Println("World")
}`;
const diffText = `--- original.go
+++ updated.go
@@ -1,8 +1,11 @@
package main
-import "fmt"
+import (
+ "fmt"
+ "time"
+)
func main() {
- fmt.Println("Hello")
+ fmt.Printf("The time is: %v\\n", time.Now())
- fmt.Println("World")
+ fmt.Println("Goodbye!")
}`;
const result = applyUnifiedDiff(sourceCode, diffText);
const expected = [
{ type: "same", line: "package main" },
{ type: "same", line: "" },
{ type: "old", line: "import \"fmt\"" },
{ type: "new", line: "import (" },
{ type: "new", line: " \"fmt\"" },
{ type: "new", line: " \"time\"" },
{ type: "new", line: ")" },
{ type: "same", line: "" },
{ type: "same", line: "func main() {" },
{ type: "old", line: " fmt.Println(\"Hello\")" },
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
{ type: "old", line: " fmt.Println(\"World\")" },
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
{ type: "same", line: "}" }
];
expect(result).toEqual(expected);
});
it("should correctly apply multiple diff blocks", () => {
const sourceCode = `package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
"testing"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Calculator started! Available operations:")
fmt.Println(" + : Addition")
fmt.Println(" - : Subtraction")
fmt.Println(" * : Multiplication")
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
for {
fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
scanner.Scan()
input := scanner.Text()
if strings.ToLower(input) == "q" {
fmt.Println("Goodbye!")
break
}
result, err := calculate(input)
if err != nil {
fmt.Printf("Error: %v\n", err)
continue
}
fmt.Printf("Result: %v\n", result)
}
}
func calculate(input string) (float64, error) {
parts := strings.Fields(input)
if len(parts) < 2 {
return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'")
}
if parts[0] == "√" {
if len(parts) != 2 {
return 0, fmt.Errorf("square root operation requires exactly one number")
}
num, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
return 0, fmt.Errorf("invalid number for square root: %v", err)
}
if num < 0 {
return 0, fmt.Errorf("cannot calculate square root of a negative number")
}
return math.Sqrt(num), nil
}
if len(parts) != 3 {
return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
}
num1, err := strconv.ParseFloat(parts[0], 64)
if err != nil {
return 0, fmt.Errorf("invalid first number: %v", err)
}
operator := parts[1]
num2, err := strconv.ParseFloat(parts[2], 64)
if err != nil {
return 0, fmt.Errorf("invalid second number: %v", err)
}
switch operator {
case "+":
return num1 + num2, nil
case "-":
return num1 - num2, nil
case "*":
return num1 * num2, nil
case "/":
if num2 == 0 {
return 0, fmt.Errorf("division by zero is not allowed")
}
return num1 / num2, nil
case "^":
return math.Pow(num1, num2), nil
default:
return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √")
}
}
func TestCalculate(t *testing.T) {
tests := []struct {
input string
expected float64
hasError bool
}{
{"2 + 3", 5, false},
{"10 - 5", 5, false},
{"4 * 3", 12, false},
{"15 / 3", 5, false},
{"2 ^ 3", 8, false},
{"√ 16", 4, false},
{"2 + a", 0, true},
{"15 / 0", 0, true},
{"√ -4", 0, true},
{"3 $ 4", 0, true},
{"", 0, true},
{"1", 0, true},
{"1 +", 0, true},
{"+ 1", 0, true},
{"√ 2 3", 0, true},
}
for _, test := range tests {
result, err := calculate(test.input)
if test.hasError && err == nil {
t.Errorf("Expected error for input '%s', but got none", test.input)
continue
}
if !test.hasError && err != nil {
t.Errorf("Unexpected error for input '%s': %v", test.input, err)
continue
}
if !test.hasError && result != test.expected {
t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result)
}
}
}
func TestSpecialCases(t *testing.T) {
result, err := calculate("2.5 + 2.5")
if err != nil {
t.Errorf("Unexpected error for floating point addition: %v", err)
}
if result != 5.0 {
t.Errorf("Floating point addition failed: expected 5.0, got %f", result)
}
result, err = calculate("2.5 ^ 2")
if err != nil {
t.Errorf("Unexpected error for power operation: %v", err)
}
expected := 6.25
if math.Abs(result-expected) > 0.0001 {
t.Errorf("Power operation failed: expected %f, got %f", expected, result)
}
result, err = calculate("√ 2")
if err != nil {
t.Errorf("Unexpected error for square root: %v", err)
}
expected = math.Sqrt(2)
if math.Abs(result-expected) > 0.0001 {
t.Errorf("Square root operation failed: expected %f, got %f", expected, result)
}
}
func TestLargeNumbers(t *testing.T) {
result, err := calculate("1000000000 + 1000000000")
if err != nil {
t.Errorf("Unexpected error for adding large numbers: %v", err)
}
if result != 2000000000 {
t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result)
}
result, err = calculate("1000000 * 1000000")
if err != nil {
t.Errorf("Unexpected error for multiplying large numbers: %v", err)
}
if result != 1000000000000 {
t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result)
}
result, err = calculate("2 ^ 30")
if err != nil {
t.Errorf("Unexpected error for large exponent operation: %v", err)
}
expected := math.Pow(2, 30)
if result != expected {
t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result)
}
result, err = calculate("1000000000000 / 1000000")
if err != nil {
t.Errorf("Unexpected error for dividing large numbers: %v", err)
}
if result != 1000000 {
t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result)
}
}`;
const diffText = `--- original.go
+++ updated.go
@@ -30,6 +30,7 @@
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
+ fmt.Println(" log: Logarithm (use 'log base number')")
+ fmt.Println(" Base must be > 0 and != 1, number must be > 0")
for {
fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
@@ -73,6 +74,8 @@
}
return math.Sqrt(num), nil
}
+
+ // Handle logarithmic operations
+ if parts[0] == "log" {
+ if len(parts) != 3 {
+ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'")
+ }
+ base, err := strconv.ParseFloat(parts[1], 64)
+ if err != nil || base <= 0 || base == 1 {
+ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1")
+ }
+ num, err := strconv.ParseFloat(parts[2], 64)
+ if err != nil || num <= 0 {
+ return 0, fmt.Errorf("invalid number for logarithm: must be > 0")
+ }
+ return math.Log(num) / math.Log(base), nil
+ }
+
if len(parts) != 3 {
return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
@@ -155,6 +158,15 @@
}
}
}
+
+func TestLogarithmicCases(t *testing.T) {
+ tests := []struct {
+ input string
+ expected float64
+ hasError bool
+ }{
+ {"log 2 8", 3, false},
+ {"log 10 100", 2, false},
+ {"log 10 -5", 0, true},
+ {"log 1 100", 0, true},
+ {"log 0.5 0.25", 2, false},
+ }`;
const result = applyUnifiedDiff(sourceCode, diffText);
expect(result[0].line).toEqual("package main");
// 1st block
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
// 2nd block
expect(result[56]).toEqual({type: "same", line: "\t}"});
expect(result[57]).toEqual({type: "new", line: "\t"});
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
expect(result[73]).toEqual({type: "new", line: ""});
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
// 3rd block
expect(result[140]).toEqual({type: "same", line: "}"});
expect(result[141]).toEqual({type: "new", line: ""});
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
expect(result[153]).toEqual({type: "new", line: "\t}"});
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
});
it("should throw error when hunk cannot be matched to source", () => {
const sourceCode = `line1
line2
line3`;
const diffText = `--- a.txt
+++ b.txt
@@ -1,3 +1,4 @@
missing1
-missing2
+newline2
missing3`;
expect(() => applyUnifiedDiff(sourceCode, diffText))
.toThrow("Hunk could not be applied cleanly to source code.");
});
});

View file

@ -0,0 +1,152 @@
import { DiffLine } from "../../index";
/**
* Checks if a string matches unified diff format by validating:
* 1. Has at least one hunk header (@@ -n,m +n,m @@)
* 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines
*/
export function isUnifiedDiffFormat(diff: string): boolean {
const lines = diff.trim().split("\n");
if (lines.length < 3) {return false;}
let hasHunkHeader = false;
let hasValidContent = false;
for (const line of lines) {
if (line.startsWith("---") || line.startsWith("+++")) {
// ignore file headers - they are not required or useful
} else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) {
hasHunkHeader = true;
} else if (line.match(/^[+ -]/) || line === "") {
hasValidContent = true;
}
}
return hasHunkHeader && hasValidContent;
}
function extractBeforeLines(hunkLines: string[]): string[] {
return hunkLines
.filter((line) => line.startsWith("-") || !line.startsWith("+"))
.map((line) => line.substring(1));
}
/**
* Applies a unified diff to source code and returns an array of DiffLine objects.
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
*
* @throws Error if the diff cannot be cleanly applied to the source
*/
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
const sourceLines = sourceCode.split(/\r?\n/);
const hunks = parseUnifiedDiff(unifiedDiffText);
const diffResult: DiffLine[] = [];
let currentPos = 0; // pointer in sourceLines
for (const hunk of hunks) {
const hunkBeforeLines = extractBeforeLines(hunk.lines);
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
if (hunkStart === -1) {
// All hunks must be found in the source code. If not, throw an error.
throw new Error("Hunk could not be applied cleanly to source code.");
}
// Emit any unchanged lines that come before this hunk.
for (let i = currentPos; i < hunkStart; i++) {
diffResult.push({ type: "same", line: sourceLines[i] });
}
let hunkSourcePos = hunkStart;
for (const dline of hunk.lines) {
const srcLine = sourceLines[hunkSourcePos];
if (dline.startsWith("+")) {
// Insertion: output new line (strip the '+' marker)
diffResult.push({ type: "new", line: dline.substring(1) });
} else if (dline.startsWith("-")) {
// Removal: output the removed (old) line and advance the pointer.
diffResult.push({ type: "old", line: srcLine });
hunkSourcePos++;
} else {
// Context line: use the source line (in case the diff’s context has a minor whitespace error)
// and advance the pointer.
diffResult.push({ type: "same", line: srcLine });
hunkSourcePos++;
}
}
currentPos = hunkSourcePos;
}
for (let i = currentPos; i < sourceLines.length; i++) {
diffResult.push({ type: "same", line: sourceLines[i] });
}
return diffResult;
}
interface Hunk {
lines: string[];
}
/**
* Parses a unified diff string into an array of hunks.
* It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"),
* then collects the remaining lines (which may start with '+' or '-' or have no prefix).
*/
function parseUnifiedDiff(diffText: string): Hunk[] {
const lines = diffText.split(/\r?\n/);
const hunks: Hunk[] = [];
let currentHunk: Hunk | null = null;
for (const line of lines) {
if (line.startsWith("---") || line.startsWith("+++")) {
// Skip file header lines.
continue;
}
if (line.startsWith("@@")) {
if (currentHunk) {
hunks.push(currentHunk);
}
currentHunk = { lines: [] };
continue;
}
currentHunk?.lines.push(line);
}
if (currentHunk) {
hunks.push(currentHunk);
}
return hunks;
}
/**
* Searches for an occurrence of the block of lines (the “before” block) in sourceLines,
* starting at startIndex. Comparison is done by checking if the lines are exactly equal,
* or if their trimmed versions are equal.
*
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
*/
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
let match = true;
for (let j = 0; j < hunkBeforeLines.length; j++) {
const sl = sourceLines[i + j];
const hl = hunkBeforeLines[j];
if (!linesMatch(sl, hl)) {
match = false;
break;
}
}
if (match) {
return i;
}
}
return -1;
}
/**
* Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs.
*/
function linesMatch(a: string, b: string): boolean {
const trimmedA = a.replace(/^\s+/, "");
const trimmedB = b.replace(/^\s+/, "");
return trimmedA === trimmedB;
}

6
core/index.d.ts vendored
View file

@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions {
): string | ChatMessage[];
}
export interface ModelInstaller {
installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
@ -543,7 +547,7 @@ export interface CustomLLMWithOptionals {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => Promise<string[]>;

View file

@ -97,7 +97,6 @@ export class CodebaseIndexer {
const lanceDbIndex = await LanceDbIndex.create(
embeddingsModel,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
);
if (lanceDbIndex) {

View file

@ -9,7 +9,6 @@ import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./test/indexing";
import { IndexResultType } from "./types";
@ -37,7 +36,6 @@ describe.skip("ChunkCodebaseIndex", () => {
index = (await LanceDbIndex.create(
mockConfig.selectedModelByRole.embed,
testIde.readFile.bind(testIde),
testContinueServerClient,
))!;
sqliteDb = await SqliteDb.get();

View file

@ -2,7 +2,6 @@ import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import { isSupportedLanceDbCpuTargetForLinux } from "../config/util";
import { IContinueServerClient } from "../continueServer/interface";
import {
BranchAndDir,
Chunk,
@ -57,7 +56,6 @@ export class LanceDbIndex implements CodebaseIndex {
static async create(
embeddingsProvider: ILLM,
readFile: (filepath: string) => Promise<string>,
continueServerClient?: IContinueServerClient,
): Promise<LanceDbIndex | null> {
if (!isSupportedLanceDbCpuTargetForLinux()) {
return null;
@ -65,11 +63,7 @@ export class LanceDbIndex implements CodebaseIndex {
try {
this.lance = await import("vectordb");
return new LanceDbIndex(
embeddingsProvider,
readFile,
continueServerClient,
);
return new LanceDbIndex(embeddingsProvider, readFile);
} catch (err) {
console.error("Failed to load LanceDB:", err);
return null;
@ -79,7 +73,6 @@ export class LanceDbIndex implements CodebaseIndex {
private constructor(
private readonly embeddingsProvider: ILLM,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: IContinueServerClient,
) {
if (!LanceDbIndex.lance) {
throw new Error("LanceDB not initialized");
@ -278,60 +271,6 @@ export class LanceDbIndex implements CodebaseIndex {
await markComplete(pathAndCacheKeys, IndexResultType.Compute);
};
if (this.continueServerClient?.connected) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
const resp = await this.continueServerClient.getFromIndexCache(
keys,
"embeddings",
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
const path = results.compute.find(
(item) => item.cacheKey === cacheKey,
)?.path;
if (!path) {
console.warn(
"Continue server sent a cacheKey that wasn't requested",
cacheKey,
);
continue;
}
const rows: LanceDbRow[] = [];
for (const chunk of chunks) {
const row = {
path,
cachekey: cacheKey,
uuid: uuidv4(),
vector: chunk.vector,
};
rows.push(row);
await sqliteDb.run(
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
row.uuid,
row.cachekey,
row.path,
this.artifactId,
JSON.stringify(row.vector),
chunk.startLine,
chunk.endLine,
chunk.contents,
);
}
await addComputedLanceDbRows([{ cacheKey, path }], rows);
}
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
} catch (e) {
console.log("Error checking remote cache: ", e);
}
}
yield {
progress: 0,
desc: `Computing embeddings for ${

View file

@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
export const defaultIgnoreFileAndDir = ignore()
.add(defaultIgnoreFile)
.add(defaultIgnoreDir);
export function gitIgArrayFromFile(file: string) {
return file
.split(/\r?\n/) // Split on new line

View file

@ -0,0 +1,167 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
TEST_DIR,
addToTestDir,
setUpTestDir,
tearDownTestDir,
} from "../test/testDir";
import { shouldIgnore } from "./shouldIgnore";
// Test for the shouldIgnore function
describe("shouldIgnore", () => {
beforeEach(() => {
setUpTestDir();
});
afterEach(() => {
tearDownTestDir();
});
test("should return true if a file is ignored by .gitignore", async () => {
addToTestDir([
["ignored-file.txt", "content"],
[".gitignore", "ignored-file.txt"],
]);
const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should return true if a folder is ignored by .continueignore", async () => {
addToTestDir([
["ignored-folder/file.txt", "content"],
[".continueignore", "ignored-folder/"],
]);
const result = await shouldIgnore(
TEST_DIR + "/ignored-folder/file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(true);
});
test("should return false if a file is not ignored", async () => {
addToTestDir([["kept-file.txt", "contents"]]);
const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(false);
});
test("should return true if a file is ignored by .gitignore with spaces in file name", async () => {
addToTestDir([
["ignored file.txt", "content"],
[".gitignore", "ignored file.txt"],
]);
const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should return true if a .continueignore override ignores file", async () => {
addToTestDir([
["override-file.txt", "content"],
[".gitignore", "override-file.txt"],
[".continueignore", "!override-file.txt"],
]);
const result = await shouldIgnore(
TEST_DIR + "/override-file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(false);
});
test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => {
addToTestDir([
["level1/level2/level3/ignored-file.txt", "content"],
["level1/.gitignore", "level2/"],
["level1/level2/.continueignore", "level3/"],
]);
const result = await shouldIgnore(
TEST_DIR + "/level1/level2/level3/ignored-file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(true);
});
test("should return false if a file with spaces is not ignored", async () => {
addToTestDir([["kept file.txt", "contents"]]);
const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(false);
});
test("should handle multiple levels of directories with some files ignored", async () => {
addToTestDir([
["nested/dir1/.gitignore", "ignored.txt"],
["nested/dir1/ignored.txt", "content"],
["nested/dir2/kept.txt", "content"],
]);
const ignoredResult = await shouldIgnore(
TEST_DIR + "/nested/dir1/ignored.txt",
testIde,
[TEST_DIR],
);
expect(ignoredResult).toBe(true);
const keptResult = await shouldIgnore(
TEST_DIR + "/nested/dir2/kept.txt",
testIde,
[TEST_DIR],
);
expect(keptResult).toBe(false);
});
test("should respect default file and folder ignores top level", async () => {
addToTestDir([
[".env", "contents"],
["go.sum", "contents"],
".idea/",
[".idea/test.xml", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should respect default file and folder ignores at nested level", async () => {
addToTestDir([
"nested/.idea/test.xml",
["nested/.env", "contents"],
["nested/go.sum", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
});

View file

@ -0,0 +1,73 @@
import ignore from "ignore";
import type { FileType, IDE } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
import { getIgnoreContext } from "./walkDir";
/*
Process:
1. Check global/default ignores
2. Walk UP tree from file, checking ignores at each level
TODO there might be issues with symlinks here
*/
export async function shouldIgnore(
fileUri: string,
ide: IDE,
rootDirCandidates?: string[],
): Promise<boolean> {
const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs());
const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris);
if (!rootDir) {
return true;
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
let currentDir = uri;
let directParent = true;
let fileType = 1 as FileType.File as FileType;
while (currentDir !== rootDir) {
// Go to parent dir of file
const splitUri = currentDir.split("/");
splitUri.pop();
currentDir = splitUri.join("/");
// Get all files in the dir
const dirEntries = await ide.listDir(currentDir);
// Check if the file is a symbolic link, ignore if so
if (directParent) {
directParent = false;
const baseName = getUriPathBasename(fileUri);
const entry = dirEntries.find(([name, _]) => name === baseName);
if (entry) {
fileType = entry[1];
if (fileType === (64 as FileType.SymbolicLink)) {
return true;
}
}
}
const ignoreContext = await getIgnoreContext(
currentDir,
dirEntries,
ide,
defaultAndGlobalIgnores,
);
let relativePath = uri.substring(currentDir.length + 1);
if (fileType === (2 as FileType.Directory)) {
relativePath += "/";
}
if (ignoreContext.ignores(relativePath)) {
return true;
}
}
return false;
}

View file

@ -1,14 +1,14 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import fs from "fs";
import path from "path";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
describe("walkDir functions", () => {
beforeEach(async () => {
@ -19,6 +19,27 @@ describe("walkDir functions", () => {
tearDownTestDir();
});
// describe.only("test speed", () => {
// it("should walk a simple directory structure", async () => {
// addToTestDir([
// "src/",
// ["src/file1.ts", "content1"],
// ["src/file2.ts", "content2"],
// "src/nested/",
// ["src/nested/file3.ts", "content3"],
// ]);
// const dir = await testIde.getWorkspaceDirs();
// const start = Date.now();
// for (let i = 0; i < 10000; i++) {
// await walkDir(dir[0], testIde);
// }
// const passed = Date.now() - start;
// console.log(`Test took ${passed} ms`);
// });
// });
describe("walkDir", () => {
it("should walk a simple directory structure", async () => {
addToTestDir([
@ -171,12 +192,7 @@ describe("walkDir functions", () => {
it("should skip symlinks", async () => {
const filePath = path.join(TEST_DIR_PATH, "real.ts");
addToTestDir([["real.ts", "content"]]);
fs.symlink(
filePath,
path.join(TEST_DIR_PATH, "symlink.ts"),
"file",
() => {},
);
fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file");
const files = await walkDirs(testIde);
@ -313,6 +329,9 @@ describe("walkDir functions", () => {
["node_modules/package/index.js", "content"],
["dist/bundle.js", "content"],
["coverage/lcov.env", "content"],
["nested/node_modules/package/index.js", "content"],
["nested/dist/bundle.js", "content"],
["nested/coverage/lcov.env", "content"],
]);
const files = await walkDir(
@ -327,6 +346,9 @@ describe("walkDir functions", () => {
expect(files).not.toContain(".git/config");
expect(files).not.toContain("node_modules/package/index.js");
expect(files).not.toContain("coverage/lcov.info");
expect(files).not.toContain("nested/node_modules/package/index.js");
expect(files).not.toContain("nested/dist/bundle.js");
expect(files).not.toContain("nested/coverage/lcov.env");
});
it("should handle directory-specific ignore patterns correctly", async () => {

View file

@ -2,27 +2,23 @@ import ignore, { Ignore } from "ignore";
import type { FileType, IDE } from "..";
import { joinPathsToUri } from "../util/uri";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
defaultIgnoreFileAndDir,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore";
import { joinPathsToUri } from "../util/uri";
export interface WalkerOptions {
ignoreFiles?: string[];
onlyDirs?: boolean;
returnRelativeUrisPaths?: boolean;
additionalIgnoreRules?: string[];
}
type Entry = [string, FileType];
// helper struct used for the DFS walk
type WalkableEntry = {
name: string;
relativeUriPath: string;
uri: string;
type: FileType;
@ -41,143 +37,110 @@ type IgnoreContext = {
};
class DFSWalker {
private readonly ignoreFileNames: Set<string>;
constructor(
private readonly uri: string,
private readonly ide: IDE,
private readonly options: WalkerOptions,
) {
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
}
) {}
// walk is a depth-first search implementation
public async *walk(): AsyncGenerator<string> {
const root = this.newRootWalkContext();
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignoreContexts = await this.getIgnoreToApplyInDir(
cur,
walkableEntries,
);
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignoreContexts)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignoreContexts: ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
} else {
// Note that shouldInclude handles skipping files if options.onlyDirs is true
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
}
}
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
private newRootWalkContext(): WalkContext {
const globalIgnoreFile = getGlobalContinueIgArray();
return {
const rootContext: WalkContext = {
walkableEntry: {
name: "",
relativeUriPath: "",
uri: this.uri,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreContexts: [
ignoreContexts: [],
};
const stack = [rootContext];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
// Only directories will be added to the stack
const entries = await this.ide.listDir(cur.walkableEntry.uri);
const newIgnore = await getIgnoreContext(
cur.walkableEntry.uri,
entries,
this.ide,
defaultAndGlobalIgnores,
);
const ignoreContexts = [
...cur.ignoreContexts,
{
ignore: ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(globalIgnoreFile),
dirname: "",
ignore: newIgnore,
dirname: cur.walkableEntry.relativeUriPath,
},
],
};
}
];
private async listDirForWalking(
walkableEntry: WalkableEntry,
): Promise<WalkableEntry[]> {
const entries = await this.ide.listDir(walkableEntry.uri);
return entries.map((e) => ({
relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`,
uri: joinPathsToUri(walkableEntry.uri, e[0]),
type: e[1],
entry: e,
}));
}
for (const entry of entries) {
if (this.entryIsSymlink(entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
continue;
}
const walkableEntry = {
name: entry[0],
relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`,
uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]),
type: entry[1],
entry: entry,
};
private async getIgnoreToApplyInDir(
curDir: WalkContext,
entriesInDir: WalkableEntry[],
): Promise<IgnoreContext[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir);
if (ignoreFilesInDir.length === 0) {
return curDir.ignoreContexts;
}
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
const newIgnoreContext = {
ignore: ignore().add(patterns),
dirname: curDir.walkableEntry.relativeUriPath,
};
return [...curDir.ignoreContexts, newIgnoreContext];
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
continue;
}
}
let shouldInclude = true;
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength =
ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
shouldInclude = false;
}
}
if (!shouldInclude) {
continue;
}
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
const ignoreEntries = entries.filter((w) =>
this.entryIsIgnoreFile(w.entry),
);
const promises = ignoreEntries.map(async (w) => {
return await this.ide.readFile(w.uri);
});
return Promise.all(promises);
}
private shouldInclude(
walkableEntry: WalkableEntry,
ignoreContexts: IgnoreContext[],
) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
return false;
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(walkableEntry.entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
return false;
if (this.entryIsDirectory(entry)) {
stack.push({
walkableEntry,
ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
} else {
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
}
}
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
return false;
}
}
return true;
}
private entryIsDirectory(entry: Entry) {
@ -187,21 +150,9 @@ class DFSWalker {
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
private entryIsIgnoreFile(e: Entry): boolean {
if (
e[1] === (2 as FileType.Directory) ||
e[1] === (64 as FileType.SymbolicLink)
) {
return false;
}
return this.ignoreFileNames.has(e[0]);
}
}
const defaultOptions: WalkerOptions = {
ignoreFiles: [".gitignore", ".continueignore"],
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
onlyDirs: false,
returnRelativeUrisPaths: false,
};
@ -238,3 +189,49 @@ export async function walkDirs(
);
return results.flat();
}
export async function getIgnoreContext(
currentDir: string,
currentDirEntries: Entry[],
ide: IDE,
defaultAndGlobalIgnores: Ignore,
) {
const dirFiles = currentDirEntries
.filter(([_, entryType]) => entryType === (1 as FileType.File))
.map(([name, _]) => name);
// Find ignore files and get ignore arrays from their contexts
// These are done separately so that .continueignore can override .gitignore
const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore");
const continueIgnoreFile = dirFiles.find(
(name) => name === ".continueignore",
);
const getGitIgnorePatterns = async () => {
if (gitIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.gitignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const getContinueIgnorePatterns = async () => {
if (continueIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.continueignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const ignoreArrays = await Promise.all([
getGitIgnorePatterns(),
getContinueIgnorePatterns(),
]);
// Note precedence here!
const ignoreContext = ignore()
.add(ignoreArrays[0]) // gitignore
.add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed
.add(ignoreArrays[1]); // local .continueignore
return ignoreContext;
}

View file

@ -19,6 +19,7 @@ import {
LLMFullCompletionOptions,
LLMOptions,
ModelCapability,
ModelInstaller,
PromptLog,
PromptTemplate,
RequestOptions,
@ -58,6 +59,17 @@ import {
toFimBody,
} from "./openaiTypeConverters.js";
export class LLMError extends Error {
constructor(message: string, public llm: ILLM) {
super(message);
}
}
export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === 'function';
}
export abstract class BaseLLM implements ILLM {
static providerName: string;
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
@ -380,9 +392,11 @@ export abstract class BaseLLM implements ILLM {
if (!resp.ok) {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
if (text.includes("try pulling it first")) {
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
const error = JSON.parse(text)?.error?.replace(/"/g, "'");
let model = error?.match(/model '(.*)' not found/)?.[1];
if (model && resp.url.match("127.0.0.1:11434")) {
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
throw new LLMError(text, this);// No need to add HTTP status details
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
@ -442,6 +456,10 @@ export abstract class BaseLLM implements ILLM {
throw new Error(message);
}
}
//if e instance of LLMError, rethrow
if (e instanceof LLMError) {
throw e;
}
throw new Error(e.message);
}
};
@ -763,6 +781,7 @@ export abstract class BaseLLM implements ILLM {
}
let completion = "";
let citations: null | string[] = null
try {
if (this.templateMessages) {
@ -790,6 +809,8 @@ export abstract class BaseLLM implements ILLM {
completion = renderChatMessage(msg);
} else {
// Stream true
console.log("Streaming");
const stream = this.openaiAdapter.chatCompletionStream(
{
...body,
@ -802,6 +823,9 @@ export abstract class BaseLLM implements ILLM {
if (result) {
yield result;
}
if (!citations && (chunk as any).citations && Array.isArray((chunk as any).citations)) {
citations = (chunk as any).citations;
}
}
}
} else {
@ -824,6 +848,10 @@ export abstract class BaseLLM implements ILLM {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
if (citations) {
await this.writeLog(`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`);
}
}
return {

View file

@ -205,10 +205,11 @@ describe("LLM", () => {
});
testLLM(
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }),
{ skip: false, timeout: 20000 },
{ skip: false, timeout: 60000 },
);
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), {
skip: false,
timeout: 60000,
});
testLLM(
new Gemini({

View file

@ -117,7 +117,7 @@ class Cohere extends BaseLLM {
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
const resp = await fetch(new URL("rerank", this.apiBase), {
const resp = await this.fetch(new URL("rerank", this.apiBase), {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,

View file

@ -1,4 +1,5 @@
import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
class CustomLLMClass extends BaseLLM {
@ -18,7 +19,7 @@ class CustomLLMClass extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
constructor(custom: CustomLLM) {
super(custom.options || { model: "custom" });
@ -38,7 +39,11 @@ class CustomLLMClass extends BaseLLM {
options,
(...args) => this.fetch(...args),
)) {
yield { role: "assistant", content };
if (typeof content === "string") {
yield { role: "assistant", content };
} else {
yield content;
}
}
} else {
for await (const update of super._streamChat(messages, signal, options)) {
@ -68,7 +73,11 @@ class CustomLLMClass extends BaseLLM {
options,
(...args) => this.fetch(...args),
)) {
yield content;
if (typeof content === "string") {
yield content;
} else {
yield renderChatMessage(content);
}
}
} else {
throw new Error(

View file

@ -1,5 +1,4 @@
import { Chunk, LLMOptions } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import { BaseLLM } from "../index.js";
class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
@ -36,17 +35,15 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
}
async doEmbedRequest(batch: string[]): Promise<number[][]> {
const resp = await withExponentialBackoff<Response>(() =>
this.fetch(new URL("embed", this.apiBase), {
method: "POST",
body: JSON.stringify({
inputs: batch,
}),
headers: {
"Content-Type": "application/json",
},
const resp = await this.fetch(new URL("embed", this.apiBase), {
method: "POST",
body: JSON.stringify({
inputs: batch,
}),
);
headers: {
"Content-Type": "application/json",
},
});
if (!resp.ok) {
const text = await resp.text();
const embedError = JSON.parse(text) as TEIEmbedErrorResponse;
@ -59,11 +56,10 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
}
async doInfoRequest(): Promise<TEIInfoResponse> {
const resp = await withExponentialBackoff<Response>(() =>
this.fetch(new URL("info", this.apiBase), {
method: "GET",
}),
);
// TODO - need to use custom fetch for this request?
const resp = await this.fetch(new URL("info", this.apiBase), {
method: "GET",
});
if (!resp.ok) {
throw new Error(await resp.text());
}
@ -79,7 +75,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
const resp = await fetch(new URL("rerank", this.apiBase), {
const resp = await this.fetch(new URL("rerank", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({

View file

@ -1,9 +1,10 @@
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { ChatMessage, CompletionOptions, ModelInstaller, LLMOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
type OllamaChatMessage = {
role: "tool" | "user" | "assistant" | "system";
@ -123,7 +124,7 @@ interface OllamaTool {
};
}
class Ollama extends BaseLLM {
class Ollama extends BaseLLM implements ModelInstaller{
static providerName = "ollama";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:11434/",
@ -358,6 +359,7 @@ class Ollama extends BaseLLM {
if ("error" in j) {
throw new Error(j.error);
}
j.response ??= ''
yield j.response;
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
@ -574,6 +576,38 @@ class Ollama extends BaseLLM {
}
return embedding;
}
public async installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any> {
const modelInfo = await getRemoteModelInfo(modelName, signal);
if (!modelInfo) {
throw new Error(`'${modelName}' not found in the Ollama registry!`);
}
const response = await fetch(this.getEndpoint("api/pull"), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ name: modelName }),
signal
});
const reader = response.body?.getReader();
//TODO: generate proper progress based on modelInfo size
while (true) {
const { done, value } = await reader?.read() || { done: true, value: undefined };
if (done) {
break;
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split('\n').filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line);
progressReporter?.(data.status, data.completed, data.total);
}
}
}
}
export default Ollama;

View file

@ -97,6 +97,10 @@ class OpenAI extends BaseLLM {
return !!model && (model.startsWith("o1") || model.startsWith("o3"));
}
private isFireworksAiModel(model?: string): boolean {
return !!model && model.startsWith("accounts/fireworks/models");
}
protected supportsPrediction(model: string): boolean {
const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"];
return SUPPORTED_MODELS.some((m) => model.includes(m));
@ -274,7 +278,13 @@ class OpenAI extends BaseLLM {
body.max_completion_tokens = undefined;
}
if (body.tools?.length && !body.model?.startsWith("o3")) {
if (body.tools?.length) {
if (this.isFireworksAiModel(body.model)) {
// fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error.
// tooling works with them as a inference provider once this is set to true.
// https://docs.fireworks.ai/guides/function-calling#openai-compatibility
body.parallel_tool_calls = true;
}
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
// In practice, setting this to true and asking for multiple tool calls
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'

View file

@ -14,7 +14,7 @@ class Voyage extends OpenAI {
return [];
}
const url = new URL("rerank", this.apiBase);
const resp = await fetch(url, {
const resp = await this.fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",

View file

@ -65,7 +65,7 @@ class ContinueProxy extends OpenAI {
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
const url = new URL("rerank", this.apiBase);
const resp = await fetch(url, {
const resp = await this.fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -75,6 +75,7 @@ class ContinueProxy extends OpenAI {
query,
documents: chunks.map((chunk) => chunk.content),
model: this.model,
...this.extraBodyProperties(),
}),
});
const data: any = await resp.json();

View file

@ -39,6 +39,19 @@ export const PROVIDER_TOOL_SUPPORT: Record<
) {
return true;
}
// firworks-ai https://docs.fireworks.ai/guides/function-calling
if (model.startsWith("accounts/fireworks/models/")) {
switch (model.substring(26)) {
case "llama-v3p1-405b-instruct":
case "llama-v3p1-70b-instruct":
case "qwen2p5-72b-instruct":
case "firefunction-v1":
case "firefunction-v2":
return true;
default:
return false;
}
}
},
gemini: (model) => {
// All gemini models support function calling
@ -57,9 +70,18 @@ export const PROVIDER_TOOL_SUPPORT: Record<
},
// https://ollama.com/search?c=tools
ollama: (model) => {
let modelName = "";
// Extract the model name after the last slash to support other registries
if(model.includes("/")) {
let parts = model.split('/');
modelName = parts[parts.length - 1];
} else {
modelName = model;
}
if (
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
(part) => model.toLowerCase().includes(part),
(part) => modelName.toLowerCase().includes(part),
)
) {
return false;
@ -79,10 +101,11 @@ export const PROVIDER_TOOL_SUPPORT: Record<
"nemotron",
"llama3-groq",
"granite3",
"granite-3",
"aya-expanse",
"firefunction-v2",
"mistral",
].some((part) => model.toLowerCase().startsWith(part))
].some((part) => modelName.toLowerCase().includes(part))
) {
return true;
}

15
core/package-lock.json generated
View file

@ -13,7 +13,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/config-yaml": "^1.0.56",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
@ -3038,9 +3038,9 @@
}
},
"node_modules/@continuedev/config-yaml": {
"version": "1.0.52",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.52.tgz",
"integrity": "sha512-x0m4bcQpjHrrv95cq5tsen4Hb6yKCVGn+NeojyzNQYnRD0If/On+ATgX78uXtQtZxsdO4ip73HHCyQlA0O3ZyQ==",
"version": "1.0.56",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.56.tgz",
"integrity": "sha512-2OBhmlSFOgZ+Z/ZQ18R/JR9zo6HIzkQ09PCuHQQ9NanN+g5AEVCdWgEtMyOq5DmQM3HLJCoLMXwqzQ9qSJEfFg==",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
@ -6163,9 +6163,10 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",

View file

@ -46,7 +46,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/config-yaml": "^1.0.56",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",

View file

@ -16,7 +16,7 @@ export async function getPromptFilesFromDir(
return [];
}
const uris = await walkDir(dir, ide, { ignoreFiles: [] });
const uris = await walkDir(dir, ide);
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
const results = promptFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch

View file

@ -184,6 +184,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"files/opened": [{ uris?: string[] }, void];
"files/created": [{ uris?: string[] }, void];
"files/deleted": [{ uris?: string[] }, void];
"files/closed": [{ uris?: string[] }, void];
// Docs etc. Indexing. TODO move codebase to this
"indexing/reindex": [{ type: string; id: string }, void];

View file

@ -5,7 +5,10 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
didChangeSelectedProfile: [{ id: string | null }, void];
didChangeSelectedOrg: [{ id: string | null }, void];
didChangeSelectedOrg: [
{ id: string | null; profileId?: string | null },
void,
];
};
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
didChangeAvailableProfiles: [

View file

@ -84,4 +84,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"getWebviewHistoryLength",
"getCurrentSessionId",
"docs/suggestions",
"didCloseFiles",
];

View file

@ -26,6 +26,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
},
void,
];
didCloseFiles: [{ uris: string[] }, void];
isContinueInputFocused: [undefined, boolean];
addContextItem: [
{

View file

@ -1,7 +1,7 @@
import fs from "fs";
import os from "os";
import path from "path";
import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri";
import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri";
// Want this outside of the git repository so we can change branches in tests
export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir");
@ -26,7 +26,7 @@ export function tearDownTestDir() {
"index/index.ts" creates an empty index/index.ts
["index/index.ts", "hello"] creates index/index.ts with contents "hello"
*/
export function addToTestDir(pathsOrUris: (string | string[])[]) {
export function addToTestDir(pathsOrUris: (string | [string, string])[]) {
// Allow tests to use URIs or local paths
const paths = pathsOrUris.map((val) => {
if (Array.isArray(val)) {

View file

@ -1,6 +1,13 @@
import crypto from "crypto";
import { exec } from "node:child_process";
import path from "node:path";
import { IDE } from "..";
import { exec } from "node:child_process";
export interface ModelInfo {
id: string;
size: number;
digest: string;
}
export async function isOllamaInstalled(): Promise<boolean> {
return new Promise((resolve, _reject) => {
@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise<any> {
});
}
}
export async function getRemoteModelInfo(
modelId: string,
signal?: AbortSignal,
): Promise<ModelInfo | undefined> {
const start = Date.now();
const [modelName, tag = "latest"] = modelId.split(":");
const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
try {
const sig = signal ? signal : AbortSignal.timeout(3000);
const response = await fetch(url, { signal: sig });
if (!response.ok) {
throw new Error(`Failed to fetch the model page: ${response.statusText}`);
}
// First, read the response body as an ArrayBuffer to compute the digest
const buffer = await response.arrayBuffer();
const digest = getDigest(buffer);
// Then, decode the ArrayBuffer into a string and parse it as JSON
const text = new TextDecoder().decode(buffer);
const manifest = JSON.parse(text) as {
config: { size: number };
layers: { size: number }[];
};
const modelSize =
manifest.config.size +
manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
const data: ModelInfo = {
id: modelId,
size: modelSize,
digest,
};
// Cache the successful result
return data;
} catch (error) {
console.error(`Error fetching or parsing model info: ${error}`);
} finally {
const elapsed = Date.now() - start;
console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
}
return undefined;
}
function getDigest(buffer: ArrayBuffer): string {
const hash = crypto.createHash("sha256");
hash.update(new Uint8Array(buffer));
return hash.digest("hex");
}

View file

@ -6,6 +6,11 @@ import * as URI from "uri-js";
// Converts a local path to a file:/// URI
export function localPathToUri(path: string) {
// This may incidentally solve bugs, but it is primarily here to warn us if we accidentally try to double-convert. It doesn't handle other URI schemes.
if (path.startsWith("file://")) {
console.warn("localPathToUri: path already starts with file://");
return path;
}
const url = pathToFileURL(path);
return URI.normalize(url.toString());
}

View file

@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
return p;
}
export function getConfigYamlPath(ideType: IdeType): string {
export function getConfigYamlPath(ideType?: IdeType): string {
const p = path.join(getContinueGlobalPath(), "config.yaml");
// if (!fs.existsSync(p)) {
// if (ideType === "jetbrains") {
@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string {
return p;
}
export function getPrimaryConfigFilePath(): string {
const configYamlPath = getConfigYamlPath();
if (fs.existsSync(configYamlPath)) {
return configYamlPath;
}
return getConfigJsonPath();
}
export function getConfigTsPath(): string {
const p = path.join(getContinueGlobalPath(), "config.ts");
if (!fs.existsSync(p)) {
@ -353,6 +361,10 @@ export function getGlobalPromptsPath(): string {
return path.join(getContinueGlobalPath(), "prompts");
}
export function getGlobalAssistantsPath(): string {
return path.join(getContinueGlobalPath(), "assistants");
}
export function readAllGlobalPromptFiles(
folderPath: string = getGlobalPromptsPath(),
): { path: string; content: string }[] {
@ -368,7 +380,7 @@ export function readAllGlobalPromptFiles(
if (stats.isDirectory()) {
const nestedPromptFiles = readAllGlobalPromptFiles(filepath);
promptFiles.push(...nestedPromptFiles);
} else {
} else if (file.endsWith(".prompt")) {
const content = fs.readFileSync(filepath, "utf8");
promptFiles.push({ path: filepath, content });
}
@ -406,6 +418,10 @@ export function migrateV1DevDataFiles() {
moveToV1FolderIfExists("autocomplete", "autocomplete");
}
export function getLocalEnvironmentDotFilePath(): string {
return path.join(getContinueGlobalPath(), ".local");
}
export function getStagingEnvironmentDotFilePath(): string {
return path.join(getContinueGlobalPath(), ".staging");
}

6
core/util/text.ts Normal file
View file

@ -0,0 +1,6 @@
export const capitalizeFirstLetter = (val: string) => {
if (val.length === 0) {
return "";
}
return val[0].toUpperCase() + val.slice(1);
};

View file

@ -116,19 +116,23 @@ export function getLastNUriRelativePathParts(
}
export function joinPathsToUri(uri: string, ...pathSegments: string[]) {
const components = URI.parse(uri);
let baseUri = uri;
if (baseUri.at(-1) !== "/") {
baseUri += "/";
}
const segments = pathSegments.map((segment) => pathToUriPathSegment(segment));
components.path = `${components.path}/${segments.join("/")}`;
return URI.serialize(components);
return URI.resolve(baseUri, segments.join("/"));
}
export function joinEncodedUriPathSegmentToUri(
uri: string,
pathSegment: string,
) {
const components = URI.parse(uri);
components.path = `${components.path}/${pathSegment}`;
return URI.serialize(components);
let baseUri = uri;
if (baseUri.at(-1) !== "/") {
baseUri += "/";
}
return URI.resolve(baseUri, pathSegment);
}
export function getShortestUniqueRelativeUriPaths(

View file

@ -0,0 +1,16 @@
---
description: Learn how to use the Apply feature
keywords: [apply, speculative]
toc_max_heading_level: 5
---
<!-- This is a work in progress and excluded by prefixing the file name with an underscore -->
# Apply
## Instant Diff Apply
If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff".
The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change.
Explainer Video: https://youtu.be/b7Xxsot4gyw

View file

@ -49,8 +49,8 @@ There are a few options that let you configure the behavior of the `@codebase` c
context:
- provider: codebase
params:
nRetrieve: 25,
nFinal: 5,
nRetrieve: 25
nFinal: 5
useReranking: true
```
</TabItem>

View file

@ -18,7 +18,7 @@ To open your configuration file, you can click the "gear" icon in the bottom rig
When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist.
See the full reference for `config.yaml` [here](../../reference.md).
See the full reference for `config.yaml` [here](../../yaml-reference.md).
## Deprecated configuration methods

View file

@ -14,7 +14,7 @@ You can read more about how development data is generated as a byproduct of LLM-
You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories.
For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&block=data).
For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data).
See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data)

View file

@ -64,7 +64,7 @@ Pre-indexed docs are only available in VS Code because the VS Code extension shi
### Hub `docs` Blocks
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&block=docs).
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
### Through the `@Docs` Context Provider
@ -137,7 +137,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
context:
- provider: docs
params:
nRetrieve: 25 # The number of docs to retreive from the embeddings query
nRetrieve: 25 # The number of docs to retrieve from the embeddings query
nFinal: 5 # The number of docs chunks to return IF reranking
useReranking: true # use reranking if a reranker is configured (defaults to true)
```
@ -149,7 +149,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
{
"name": "docs",
"params": {
"nRetrieve": 25, // The number of docs to retreive from the embeddings query
"nRetrieve": 25, // The number of docs to retrieve from the embeddings query
"nFinal": 5, // The number of docs chunks to return IF reranking
"useReranking": true // use reranking if a reranker is configured (defaults to true)
}

View file

@ -4,7 +4,7 @@ title: Prompt files
Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts.
On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&block=rules).
On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules).
Prompt files can also be stored within your project's root directory as `.prompt` files. See below.

View file

@ -9,7 +9,7 @@ Rules are used to provide instructions to **chat** models. They are inserted int
## Hub `rules` blocks
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&block=rules) in the Hub.
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
## `.continuerules`

View file

@ -51,7 +51,7 @@ We recommend configuring **GPT-4o** as your chat model.
## Autocomplete model
We recommend configuring **Codestral** as your autocomplete model.
We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral:
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
@ -60,6 +60,8 @@ We recommend configuring **Codestral** as your autocomplete model.
- name: Codestral
provider: mistral
model: codestral-latest
apiBase: https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1
apiKey: <YOUR_AZURE_API_KEY>
roles:
- autocomplete
```
@ -70,7 +72,9 @@ We recommend configuring **Codestral** as your autocomplete model.
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest"
"model": "codestral-latest",
"apiBase": "https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1",
"apiKey": "<YOUR_AZURE_API_KEY>"
}
}
```

View file

@ -30,7 +30,7 @@ Currently custom tools can be configured using the [Model Context Protocol](http
MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp).
To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&block=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md):
To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md):
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">

View file

@ -41,7 +41,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c
1. Open the "Output" panel (right next to the terminal)
2. In the dropdown, select "Continue - LLM Prompts/Completions"
3. View the exact prompts that were sent to the LLM and the completions recieved
3. View the exact prompts that were sent to the LLM and the completions received
### JetBrains

View file

@ -12,7 +12,7 @@ See also
- [Intro to YAML](https://yaml.org/)
- [JSON Continue Config Reference](/json-reference)
- [YAML Continue Config Reference](/reference)
- [YAML Continue Config Reference](/yaml-reference)
## Create YAML file
@ -37,9 +37,9 @@ Add all model configurations in `config.json`, including models in `models`, `ta
- `inlineEdit` -> e.g. `roles: [chat, edit]`
- `applyCodeBlock` -> e.g. `roles: [chat, apply]`
Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/reference#requestoptions)
Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions)
Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions)
Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions)
<!-- TODO - ollama autodetect supported? -->

View file

@ -19,7 +19,7 @@ const config = {
favicon: "img/favicon.ico",
// Set the production url of your site here
url: "https://continue.dev",
url: "https://docs.continue.dev",
// Set the /<baseUrl>/ pathname under which your site is served
// For GitHub pages deployment, it is often '/<projectName>/'
baseUrl: "/",

View file

@ -1,5 +1,5 @@
package com.github.continuedev.continueintellijextension.activities
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.github.continuedev.continueintellijextension.auth.AuthListener
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.auth.ControlPlaneSessionInfo
@ -37,6 +37,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.vfs.VirtualFile
fun showTutorial(project: Project) {
val tutorialFileName = getTutorialFileName()
@ -199,6 +200,24 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
}
})
connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
file.toUriOrNull()?.let { uri ->
val data = mapOf("uris" to listOf(uri))
continuePluginService.coreMessenger?.request("files/closed", data, null) { _ -> }
}
}
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
file.toUriOrNull()?.let { uri ->
val data = mapOf("uris" to listOf(uri))
continuePluginService.coreMessenger?.request("files/opened", data, null) { _ -> }
}
}
})
// Listen for theme changes
connection.subscribe(LafManagerListener.TOPIC, LafManagerListener {
val colors = GetTheme().getTheme();

View file

@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.auth
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.Desktop
import com.google.gson.Gson
import com.intellij.credentialStore.Credentials
import com.intellij.ide.passwordSafe.PasswordSafe
@ -12,7 +13,6 @@ import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes
import kotlinx.coroutines.CoroutineScope
import java.awt.Desktop
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@ -153,8 +153,7 @@ class ContinueAuthService {
) { response ->
val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
if (authUrl != null) {
// Open the auth URL in the browser
Desktop.getDesktop().browse(java.net.URI(authUrl))
Desktop.browse(java.net.URI(authUrl))
}
}
}

View file

@ -71,6 +71,7 @@ class MessageTypes {
"getWebviewHistoryLength",
"getCurrentSessionId",
"docs/suggestions",
"didCloseFiles",
)
// Note: If updating these values, make a corresponding update in

View file

@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.github.continuedev.continueintellijextension.utils.getOS
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.github.continuedev.continueintellijextension.utils.Desktop
import com.google.gson.Gson
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
@ -36,7 +37,6 @@ import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.awt.Desktop
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.io.BufferedReader
@ -239,7 +239,7 @@ class IntelliJIDE(
override suspend fun openUrl(url: String) {
withContext(Dispatchers.IO) {
Desktop.getDesktop().browse(URI(url))
Desktop.browse(java.net.URI(url))
}
}

View file

@ -13,6 +13,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import kotlin.math.max
import kotlin.math.min
@ -179,7 +180,7 @@ class DiffStreamHandler(
// Update the highlighter to show the current line
curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
curLine.highlighter = editor.markupModel.addLineHighlighter(
curLineKey, min(curLine.index, editor.document.lineCount - 1), HighlighterLayer.LAST
curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST
)
// Remove the unfinished lines highlighter

View file

@ -111,7 +111,10 @@ class OpenedConnection(private val connection: URLConnection?) :
) {
try {
if (connection != null) {
val url = connection.url.toString()
val fullUrl = connection.url.toString()
// Extract only the resource path after the JAR prefix to prevent incorrect mime type matching
// (e.g., if a user's home folder contains "js" in the path)
val url = fullUrl.substringAfterLast("jar!/", fullUrl)
when {
url.contains("css") -> cefResponse.mimeType = "text/css"
url.contains("js") -> cefResponse.mimeType = "text/javascript"

View file

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

View file

@ -946,7 +946,10 @@
"gemini-1.5-flash",
"gemini-1.5-flash-8b",
"gemini-2.0-flash-exp",
"gemini-2.0-flash"
"gemini-2.0-flash",
"gemini-2.0-flash-thinking-exp-01-21",
"gemini-2.0-pro-exp-02-05",
"gemini-2.0-flash-lite-preview-02-05"
]
}
}
@ -1319,7 +1322,17 @@
"nvidia/Llama-3.1-Nemotron-70B-Instruct",
"Qwen/Qwen2-VL-72B-Instruct",
"TeleAI/TeleMM",
"deepseek-ai/DeepSeek-V2.5"
"deepseek-ai/DeepSeek-V2.5",
"deepseek-ai/deepseek-vl2",
"deepseek-ai/Janus-Pro-7B",
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-R1",
"deepseek-ai/DeepSeek-R1-Distill-Qwen-14B",
"deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
"deepseek-ai/DeepSeek-R1-Distill-Llama-70B",
"deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
"deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
]
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.3",
"version": "1.1.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.3",
"version": "1.1.7",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/fetch": "^1.0.3",
@ -106,7 +106,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/config-yaml": "^1.0.56",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.4",
"version": "1.1.8",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -52,6 +52,7 @@
"llama"
],
"activationEvents": [
"onUri",
"onStartupFinished",
"onView:continueGUIView"
],
@ -319,7 +320,7 @@
"group": "Continue"
},
{
"command": "continue.focusContinueSessionId",
"command": "continue.focusContinueInput",
"category": "Continue",
"title": "Focus Continue Chat",
"group": "Continue"
@ -594,7 +595,7 @@
"e2e:compile": "tsc -p ./tsconfig.e2e.json",
"e2e:build": "npm --prefix ../../gui run build && npm run package",
"e2e:create-storage": "mkdir -p ./e2e/storage",
"e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage",
"e2e:get-chromedriver": "CODE_VERSION=\"1.95.0\" extest get-chromedriver --storage ./e2e/storage",
"e2e:get-vscode": "CODE_VERSION=\"1.95.0\" extest get-vscode --storage ./e2e/storage",
"e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'",
"e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh",

View file

@ -21,8 +21,8 @@ import {
stopStatusBarLoading,
} from "./statusBar";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { IDE } from "core";
import { handleLLMError } from "../util/errorHandling";
const Diff = require("diff");
@ -43,16 +43,13 @@ export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider
{
private onError(e: any) {
let options = ["Documentation"];
if (e.message.includes("Ollama may not be installed")) {
options.push("Download Ollama");
} else if (e.message.includes("Ollama may not be running")) {
options = ["Start Ollama"]; // We want "Start" to be the only choice
if (handleLLMError(e)) {
return;
}
if (e.message.includes("Please sign in with GitHub")) {
let message = e.message;
if (message.includes("Please sign in with GitHub")) {
showFreeTrialLoginMessage(
e.message,
message,
this.configHandler.reloadConfig.bind(this.configHandler),
() => {
void this.webviewProtocol.request("openOnboardingCard", undefined);
@ -60,17 +57,13 @@ export class ContinueCompletionProvider
);
return;
}
vscode.window.showErrorMessage(e.message, ...options).then((val) => {
vscode.window.showErrorMessage(message, "Documentation").then((val) => {
if (val === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/features/tab-autocomplete",
),
);
} else if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
} else if (val === "Start Ollama") {
startLocalOllama(this.ide);
}
});
}

View file

@ -47,7 +47,7 @@ export class RecentlyEditedTracker {
editedRange: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
): Promise<void> {
if (editedRange.uri.scheme === "output") {
if (editedRange.uri.scheme !== "file") {
return;
}
@ -83,7 +83,6 @@ export class RecentlyEditedTracker {
RecentlyEditedTracker.maxRecentlyEditedRanges,
);
}
}
private insertDocument(uri: vscode.Uri): void {

View file

@ -1,7 +1,12 @@
/* eslint-disable @typescript-eslint/naming-convention */
import * as os from "node:os";
import { ContextMenuConfig, RangeInFileWithContents } from "core";
import {
ContextMenuConfig,
ILLM,
ModelInstaller,
RangeInFileWithContents,
} from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
import { ContinueServerClient } from "core/continueServer/stubs/client";
@ -14,13 +19,13 @@ import readLastLines from "read-last-lines";
import * as vscode from "vscode";
import {
StatusBarStatus,
getAutocompleteStatusBarDescription,
getAutocompleteStatusBarTitle,
getStatusBarStatus,
getStatusBarStatusFromQuickPickItemLabel,
quickPickStatusText,
setupStatusBar,
StatusBarStatus,
} from "./autocomplete/statusBar";
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
@ -32,6 +37,7 @@ import { getMetaKeyLabel } from "./util/util";
import { VsCodeIde } from "./VsCodeIde";
import { LOCAL_DEV_DATA_VERSION } from "core/data/log";
import { isModelInstaller } from "core/llm";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
@ -954,11 +960,11 @@ const getCommandsMap: (
}
} else if (selectedOption === "$(feedback) Give feedback") {
vscode.commands.executeCommand("continue.giveAutocompleteFeedback");
} else if (selectedOption === "$(comment) Open chat (Cmd+L)") {
} else if (selectedOption === "$(comment) Open chat") {
vscode.commands.executeCommand("continue.focusContinueInput");
} else if (
selectedOption ===
"$(screen-full) Open full screen chat (Cmd+K Cmd+M)"
"$(screen-full) Open full screen chat"
) {
vscode.commands.executeCommand("continue.toggleFullScreen");
} else if (selectedOption === "$(question) Open help center") {
@ -996,6 +1002,25 @@ const getCommandsMap: (
"continue.startLocalOllama": () => {
startLocalOllama(ide);
},
"continue.installModel": async (
modelName: string,
llmProvider: ILLM | undefined,
) => {
try {
if (!isModelInstaller(llmProvider)) {
const msg = llmProvider
? `LLM provider '${llmProvider.providerName}' does not support installing models`
: "Missing LLM Provider";
throw new Error(msg);
}
await installModelWithProgress(modelName, llmProvider);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
vscode.window.showErrorMessage(
`Failed to install '${modelName}': ${message}`,
);
}
},
};
};
@ -1037,6 +1062,45 @@ const registerCopyBufferSpy = (
context.subscriptions.push(typeDisposable);
};
async function installModelWithProgress(
modelName: string,
modelInstaller: ModelInstaller,
) {
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Installing model '${modelName}'`,
cancellable: true,
},
async (windowProgress, token) => {
let currentProgress: number = 0;
const progressWrapper = (
details: string,
worked?: number,
total?: number,
) => {
let increment = 0;
if (worked && total) {
const progressValue = Math.round((worked / total) * 100);
increment = progressValue - currentProgress;
currentProgress = progressValue;
}
windowProgress.report({ message: details, increment });
};
const abortController = new AbortController();
token.onCancellationRequested(() => {
console.log(`Pulling ${modelName} model was cancelled`);
abortController.abort();
});
await modelInstaller.installModel(
modelName,
abortController.signal,
progressWrapper,
);
},
);
}
export function registerAllCommands(
context: vscode.ExtensionContext,
ide: VsCodeIde,

View file

@ -9,6 +9,7 @@ import * as vscode from "vscode";
import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { handleLLMError } from "../../util/errorHandling";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
export interface VerticalDiffCodeLens {
@ -230,7 +231,7 @@ export class VerticalDiffManager {
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
console.warn("Issue occurred while creating new vertical diff handler");
return;
}
@ -255,7 +256,9 @@ export class VerticalDiffManager {
this.enableDocumentChangeListener();
} catch (e) {
this.disableDocumentChangeListener();
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
if (!handleLLMError(e)) {
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
}
} finally {
vscode.commands.executeCommand(
"setContext",
@ -353,7 +356,7 @@ export class VerticalDiffManager {
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
console.warn("Issue occurred while creating new vertical diff handler");
return undefined;
}
@ -446,7 +449,9 @@ export class VerticalDiffManager {
return `${prefix}${streamedLines.join("\n")}${suffix}`;
} catch (e) {
this.disableDocumentChangeListener();
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
if (!handleLLMError(e)) {
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
}
return undefined;
} finally {
vscode.commands.executeCommand(

View file

@ -28,6 +28,7 @@ import { registerAllPromptFilesCompletionProviders } from "../lang-server/prompt
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
import { UriEventHandler } from "../stubs/uriHandler";
import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
@ -55,10 +56,11 @@ export class VsCodeExtension {
private battery: Battery;
private workOsAuthProvider: WorkOsAuthProvider;
private fileSearch: FileSearch;
private uriHandler = new UriEventHandler();
constructor(context: vscode.ExtensionContext) {
// Register auth provider
this.workOsAuthProvider = new WorkOsAuthProvider(context);
this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
this.workOsAuthProvider.refreshSessions();
context.subscriptions.push(this.workOsAuthProvider);
@ -193,6 +195,41 @@ export class VsCodeExtension {
),
);
// Handle uri events
this.uriHandler.event((uri) => {
const queryParams = new URLSearchParams(uri.query);
let profileId = queryParams.get("profile_id");
let orgId = queryParams.get("org_id");
if (orgId) {
if (orgId === "null") {
orgId = null;
}
// In case org id is passed with profile id
// Make sure org is updated before profile is set
if (profileId) {
if (profileId === "null") {
profileId = null;
}
this.core.invoke("didChangeSelectedOrg", {
id: orgId,
profileId,
});
} else {
this.core.invoke("didChangeSelectedOrg", {
id: orgId,
});
}
} else if (profileId) {
if (profileId === "null") {
profileId = null;
}
this.core.invoke("didChangeSelectedProfile", {
id: profileId,
});
}
});
// Battery
this.battery = new Battery();
context.subscriptions.push(this.battery);
@ -273,6 +310,12 @@ export class VsCodeExtension {
});
});
vscode.workspace.onDidCloseTextDocument(async (event) => {
this.core.invoke("files/closed", {
uris: [event.uri.toString()],
});
});
vscode.workspace.onDidCreateFiles(async (event) => {
this.core.invoke("files/created", {
uris: event.files.map((uri) => uri.toString()),

View file

@ -15,13 +15,13 @@ import {
ExtensionContext,
ProgressLocation,
Uri,
UriHandler,
window,
workspace,
} from "vscode";
import { PromiseAdapter, promiseFromEvent } from "./promiseUtils";
import { SecretStorage } from "./SecretStorage";
import { UriEventHandler } from "./uriHandler";
const AUTH_NAME = "Continue";
@ -35,11 +35,6 @@ const controlPlaneEnv = getControlPlaneEnvSync(
const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`;
class UriEventHandler extends EventEmitter<Uri> implements UriHandler {
public handleUri(uri: Uri) {
this.fire(uri);
}
}
// Function to generate a random string of specified length
function generateRandomString(length: number): string {
const possibleCharacters =
@ -83,13 +78,15 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
string,
{ promise: Promise<string>; cancel: EventEmitter<void> }
>();
private _uriHandler = new UriEventHandler();
private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes
private secretStorage: SecretStorage;
constructor(private readonly context: ExtensionContext) {
constructor(
private readonly context: ExtensionContext,
private readonly _uriHandler: UriEventHandler,
) {
this._disposable = Disposable.from(
authentication.registerAuthenticationProvider(
controlPlaneEnv.AUTH_TYPE,

View file

@ -0,0 +1,10 @@
import * as vscode from "vscode";
export class UriEventHandler
extends vscode.EventEmitter<vscode.Uri>
implements vscode.UriHandler
{
public handleUri(uri: vscode.Uri) {
this.fire(uri);
}
}

View file

@ -0,0 +1,49 @@
import * as vscode from "vscode";
function supportSpecialHandling(error: any): boolean {
let message: string | undefined = error.message;
return message !== undefined && message.toLowerCase().includes("ollama");
}
/**
* @param error Handles common LLM errors. Currently only handles Ollama-related errors.
* @returns true if error is handled, false otherwise
*/
export function handleLLMError(error: any): boolean {
if (!supportSpecialHandling(error)) {
return false;
}
let message: string = error.message;
let options: string[] | undefined;
let modelName = undefined;
if (message.includes("Ollama may not be installed")) {
options = ["Download Ollama"];
} else if (message.includes("Ollama may not be running")) {
options = ["Start Ollama"]; // We want "Start" to be the only choice
} else if (message.includes("ollama run") && error.llm) {
//extract model name from error message matching the pattern "ollama run <model-name>"
modelName = message.match(/`ollama run (.*)`/)?.[1];
message = `Model "${modelName}" is not found in Ollama. You need to install it.`;
options = [`Install Model`];
}
if (options === undefined) {
console.log("Found an unhandled Ollama error: ", message);
return false;
}
vscode.window.showErrorMessage(message, ...options).then((val) => {
if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
} else if (val === "Start Ollama") {
vscode.commands.executeCommand("continue.startLocalOllama");
} else if (val === "Install Model" && error.llm) {
//Eventually, we might be able to support installing models for other LLM providers than Ollama
vscode.commands.executeCommand(
"continue.installModel",
modelName,
error.llm,
);
}
});
return true;
}

View file

@ -7,6 +7,7 @@ import * as vscode from "vscode";
import { IMessenger } from "../../../core/protocol/messenger";
import { handleLLMError } from "./util/errorHandling";
import { showFreeTrialLoginMessage } from "./util/messages";
export class VsCodeWebviewProtocol
@ -86,31 +87,12 @@ export class VsCodeWebviewProtocol
respond({ done: true, content: response, status: "success" });
}
} catch (e: any) {
let message = e.message;
//Intercept Ollama errors for special handling
if (message.includes("Ollama may not")) {
const options = [];
if (message.includes("be installed")) {
options.push("Download Ollama");
} else if (message.includes("be running")) {
options.push("Start Ollama");
}
if (options.length > 0) {
// Respond without an error, so the UI doesn't show the error component
respond({ done: true, status: "error" });
// Show native vscode error message instead, with options to download/start Ollama
vscode.window.showErrorMessage(e.message, ...options).then(async (val) => {
if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
} else if (val === "Start Ollama") {
vscode.commands.executeCommand("continue.startLocalOllama");
}
});
return;
}
if (handleLLMError(e)) {
// Respond without an error, so the UI doesn't show the error component
respond({ done: true, status: "error" });
}
respond({ done: true, error: e.message, status: "error" });
let message = e.message;
respond({ done: true, error: message, status: "error" });
const stringified = JSON.stringify({ msg }, null, 2);
console.error(

2
gui/package-lock.json generated
View file

@ -107,7 +107,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/config-yaml": "^1.0.56",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",

View file

@ -12,7 +12,7 @@ function AddModelButtonSubtext() {
className="cursor-pointer underline"
onClick={() =>
ideMessenger.post("config/openProfile", {
profileId: "local",
profileId: undefined,
})
}
>

View file

@ -0,0 +1,61 @@
import { ChevronRightIcon } from "@heroicons/react/24/outline";
import { useContext } from "react";
import { Button, ButtonSubtext } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice";
import { LocalStorageKey, setLocalStorage } from "../../util/localStorage";
import { ReusableCard } from "../ReusableCard";
export function ExploreHubCard() {
const dispatch = useAppDispatch();
const isOpen = useAppSelector((state) => state.ui.isExploreDialogOpen);
const ideMessenger = useContext(IdeMessengerContext);
if (!isOpen) return null;
return (
<ReusableCard
showCloseButton={true}
onClose={() => {
setLocalStorage(LocalStorageKey.IsExploreDialogOpen, false);
setLocalStorage(LocalStorageKey.HasDismissedExploreDialog, true);
return dispatch(setIsExploreDialogOpen(false));
}}
>
<div className="flex flex-col items-center gap-1 p-4 text-center">
<h2 className="text-2xl font-semibold">Create Your Own Assistant</h2>
<p className="max-w-lg text-base leading-relaxed">
Discover and remix popular assistants, or create your own from scratch
</p>
<Button
className="w-full"
onClick={() => {
ideMessenger.request("controlPlane/openUrl", {
path: "/explore/assistants",
orgSlug: undefined,
});
}}
>
Explore Assistants
</Button>
<ButtonSubtext
onClick={() => {
ideMessenger.request("controlPlane/openUrl", {
path: "/new?type=assistant",
orgSlug: undefined,
});
}}
>
<div className="mt-4 flex cursor-pointer items-center justify-center gap-1">
<span>Or, create your own assistant from scratch</span>
<ChevronRightIcon className="h-3 w-3" />
</div>
</ButtonSubtext>
</div>
</ReusableCard>
);
}

View file

@ -1,20 +1,9 @@
import * as Tabs from "./tabs";
import { TabTitle, OnboardingCardTabs } from "./components/OnboardingCardTabs";
import { XMarkIcon } from "@heroicons/react/24/outline";
import styled from "styled-components";
import { CloseButton, defaultBorderRadius, vscInputBackground } from "../";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import { useOnboardingCard } from "./hooks/useOnboardingCard";
import { useAppSelector } from "../../redux/hooks";
const StyledCard = styled.div`
margin: auto;
border-radius: ${defaultBorderRadius};
background-color: ${vscInputBackground};
box-shadow:
0 20px 25px -5px rgb(0 0 0 / 0.1),
0 8px 10px -6px rgb(0 0 0 / 0.1);
`;
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import { ReusableCard } from "../ReusableCard";
import { OnboardingCardTabs, TabTitle } from "./components/OnboardingCardTabs";
import { useOnboardingCard } from "./hooks/useOnboardingCard";
import * as Tabs from "./tabs";
export interface OnboardingCardState {
show?: boolean;
@ -47,20 +36,16 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) {
}
return (
<StyledCard
className="xs:py-4 xs:px-4 relative px-2 py-3"
data-testid="onboarding-card"
<ReusableCard
showCloseButton={!isDialog && !!config.models.length}
onClose={() => onboardingCard.close()}
testId="onboarding-card"
>
<OnboardingCardTabs
activeTab={onboardingCard.activeTab || "Best"}
onTabClick={onboardingCard.setActiveTab}
/>
{!isDialog && !!config.models.length && (
<CloseButton onClick={() => onboardingCard.close()}>
<XMarkIcon className="mt-1.5 hidden h-5 w-5 hover:brightness-125 sm:flex" />
</CloseButton>
)}
<div className="content py-4">{renderTabContent()}</div>
</StyledCard>
{renderTabContent()}
</ReusableCard>
);
}

View file

@ -1,23 +1,12 @@
import { XMarkIcon } from "@heroicons/react/24/outline";
import { useState } from "react";
import styled from "styled-components";
import { CloseButton, defaultBorderRadius, vscInputBackground } from "../..";
import { useAppSelector } from "../../../redux/hooks";
import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
import Alert from "../../gui/Alert";
import { ReusableCard } from "../../ReusableCard";
import { TabTitle } from "../components/OnboardingCardTabs";
import { useOnboardingCard } from "../hooks";
import OnboardingLocalTab from "../tabs/OnboardingLocalTab";
import MainTab from "./tabs/main";
import { useAppSelector } from "../../../redux/hooks";
const StyledCard = styled.div`
margin: auto;
border-radius: ${defaultBorderRadius};
background-color: ${vscInputBackground};
box-shadow:
0 20px 25px -5px rgb(0 0 0 / 0.1),
0 8px 10px -6px rgb(0 0 0 / 0.1);
`;
export interface OnboardingCardState {
show?: boolean;
@ -31,44 +20,38 @@ interface OnboardingCardProps {
export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) {
const onboardingCard = useOnboardingCard();
const config = useAppSelector((store) => store.config.config);
const [currentTab, setCurrentTab] = useState<"main" | "local">("main");
if (getLocalStorage("onboardingStatus") === undefined) {
setLocalStorage("onboardingStatus", "Started");
}
const [currentTab, setCurrentTab] = useState<"main" | "local">("main");
return (
<StyledCard className="xs:py-4 xs:px-4 relative px-2 py-3">
{!isDialog && !!config.models.length && (
<CloseButton onClick={() => onboardingCard.close()}>
<XMarkIcon className="mt-1.5 hidden h-5 w-5 hover:brightness-125 sm:flex" />
</CloseButton>
)}
<div className="content py-4">
<div className="flex h-full w-full items-center justify-center">
{currentTab === "main" ? (
<MainTab
onRemainLocal={() => setCurrentTab("local")}
isDialog={isDialog}
/>
) : (
<div className="mt-4 flex flex-col">
<Alert type="info">
By choosing this option, Continue will be configured by a local{" "}
<code>config.yaml</code> file. If you're just looking to use
Ollama and still want to manage your configuration through
Continue, click{" "}
<a href="#" onClick={() => setCurrentTab("main")}>
here
</a>
</Alert>
<OnboardingLocalTab isDialog={isDialog} />
</div>
)}
</div>
<ReusableCard
showCloseButton={!isDialog && !!config.models.length}
onClose={() => onboardingCard.close()}
>
<div className="flex h-full w-full items-center justify-center">
{currentTab === "main" ? (
<MainTab
onRemainLocal={() => setCurrentTab("local")}
isDialog={isDialog}
/>
) : (
<div className="mt-4 flex flex-col">
<Alert type="info">
By choosing this option, Continue will be configured by a local{" "}
<code>config.yaml</code> file. If you're just looking to use
Ollama and still want to manage your configuration through
Continue, click{" "}
<a href="#" onClick={() => setCurrentTab("main")}>
here
</a>
</Alert>
<OnboardingLocalTab isDialog={isDialog} />
</div>
)}
</div>
</StyledCard>
</ReusableCard>
);
}

View file

@ -0,0 +1,42 @@
import { XMarkIcon } from "@heroicons/react/24/outline";
import styled from "styled-components";
import { CloseButton, defaultBorderRadius, vscInputBackground } from ".";
const StyledCard = styled.div`
margin: auto;
border-radius: ${defaultBorderRadius};
background-color: ${vscInputBackground};
box-shadow:
0 20px 25px -5px rgb(0 0 0 / 0.1),
0 8px 10px -6px rgb(0 0 0 / 0.1);
`;
interface ReusableCardProps {
children: React.ReactNode;
showCloseButton?: boolean;
onClose?: () => void;
className?: string;
testId?: string;
}
export function ReusableCard({
children,
showCloseButton,
onClose,
className = "",
testId,
}: ReusableCardProps) {
return (
<StyledCard
className={`xs:py-4 xs:px-4 relative px-2 py-3 ${className}`}
data-testid={testId}
>
{showCloseButton && (
<CloseButton onClick={onClose}>
<XMarkIcon className="mt-1.5 hidden h-5 w-5 hover:brightness-125 sm:flex" />
</CloseButton>
)}
<div className="content py-4">{children}</div>
</StyledCard>
);
}

View file

@ -155,10 +155,6 @@ export function TabBar() {
);
const tabs = useSelector((state: RootState) => state.tabs.tabs);
useEffect(() => {
console.log("session", currentSession);
}, [currentSession.id]);
// Simple UUID generator for our needs
const generateId = useCallback(() => {
return Date.now().toString(36) + Math.random().toString(36).substring(2);

View file

@ -8,9 +8,8 @@
// TODO support github-specific markdown as well, edge case
*/
export const patchNestedMarkdown = (source: string): string => {
if (!source.match(/```(md|markdown)/)) return source; // For performance
if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
// const start = Date.now();
let nestCount = 0;
const lines = source.split("\n");
@ -28,9 +27,17 @@ export const patchNestedMarkdown = (source: string): string => {
}
} else {
// Enter the markdown block, start tracking nesting
if (line.startsWith("```md") || line.startsWith("```markdown")) {
nestCount = 1;
lines[i] = lines[i].replace(/```(md|markdown)/, "~~~"); // Replace backticks with tildes
if (line.startsWith("```")) {
const header = line.replaceAll("`", "");
const file = header.split(" ")[0];
if (file) {
const ext = file.split(".").at(-1);
if (ext === "md" || ext === "markdown") {
nestCount = 1;
lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
}
}
}
}
}
@ -38,53 +45,3 @@ export const patchNestedMarkdown = (source: string): string => {
// console.log(`patched in ${Date.now() - start}ms`);
return out;
};
// This version tries to detect if a codeblock without a language specified is a starter codeblock
// It tries again if didn't come back to root nesting, without checking for that ^
// I didn't use for performance and also because the root nest check doesn't make sense mid-generation
// export const patchNestedMarkdown = (source: string): string => {
// const start = Date.now();
// let attempts = 0;
// while (attempts <= 2) {
// let nestCount = 0;
// const lines = source.split("\n");
// const trimmedLines = lines.map((l) => l.trim());
// for (let i = 0; i < trimmedLines.length; i++) {
// const line = trimmedLines[i];
// if (nestCount) {
// if (line.match(/^`+$/)) {
// if (attempts === 0 && i !== lines.length && lines[i + 1] !== "") {
// nestCount++;
// continue;
// }
// if (nestCount === 1) lines[i] = "~~~";
// nestCount--;
// } else if (line.startsWith("```")) {
// // Going into a nested codeblock
// nestCount++;
// }
// } else {
// // Enter the markdown block, start tracking nesting
// if (line.startsWith("```md") || line.startsWith("```markdown")) {
// nestCount = 1;
// lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes
// }
// }
// }
// if (nestCount === 0) {
// console.log(
// `patch successful in ${Date.now() - start} ms with ${attempts} attempts`,
// );
// return lines.join("\n");
// }
// attempts++;
// }
// console.log(
// `patch failed in ${Date.now() - start} ms with ${attempts} attempts`,
// );
// return source;
// };

View file

@ -19,14 +19,10 @@ import {
setDefaultModel,
} from "../../redux/slices/configSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import {
getFontSize,
getMetaKeyLabel,
isMetaEquivalentKeyPressed,
} from "../../util";
import { getFontSize, isMetaEquivalentKeyPressed } from "../../util";
import ConfirmationDialog from "../dialogs/ConfirmationDialog";
import Shortcut from "../gui/Shortcut";
import { Divider } from "./platform/shared";
import Shortcut from '../gui/Shortcut';
interface ModelOptionProps {
option: Option;
@ -166,9 +162,7 @@ function ModelOption({
e.stopPropagation();
e.preventDefault();
ideMessenger.post("config/openProfile", {
profileId: "local",
});
ideMessenger.post("config/openProfile", { profileId: undefined });
}
function handleOptionClick(e: any) {
@ -351,7 +345,7 @@ function ModelSelect() {
<div className="mt-auto">
<Divider className="!my-0" />
{selectedProfile?.id === "local" && (
{selectedProfile?.profileType === "local" && (
<>
<StyledListboxOption
key={options.length}

View file

@ -1,11 +1,10 @@
import { Transition } from "@headlessui/react";
import { Listbox, Transition } from "@headlessui/react";
import {
CheckIcon,
ChevronUpDownIcon,
CubeIcon,
} from "@heroicons/react/24/outline";
import { Fragment } from "react";
import { Listbox } from "@headlessui/react";
import styled from "styled-components";
import {
defaultBorderRadius,

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