merge dev

This commit is contained in:
Dallin Romney 2024-11-10 22:41:14 -08:00
commit 67facee09c
85 changed files with 3076 additions and 2050 deletions

View file

@ -0,0 +1,4 @@
## 0.8.56 - 2024-11-08
### Added
* New Edit mode in sidebar (cmd/ctrl+I)
* Significantly faster and more accurate docs crawler by default

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: New Edit mode in sidebar (cmd/ctrl+I)
time: 2024-11-02T00:27:24.40964-07:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Significantly faster and more accurate docs crawler by default
time: 2024-11-02T00:27:44.408045-07:00

View file

@ -4,7 +4,6 @@
## Checklist
- [] The base branch of this PR is `dev`, rather than `main`
- [] The relevant docs, if any, have been updated or created
## Screenshots

View file

@ -1,19 +0,0 @@
# Deployment Process
## preview
When merging to `preview`:
- the VS Code extension along with Rust extension is built and uploaded as an artifact
- all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases.
- the version is bumped and this change is commited to preview
- in the future, the JetBrains extension will be built and uploaded to the marketplace here
## main
When merging to `main`:
- the VS Code extension along with Rust extension is built and uploaded as an artifact
- all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases.
- the version is bumped and this change is commited to main
- in the future, the JetBrains extension will be built and uploaded to the marketplace here

View file

@ -1,9 +1,9 @@
name: Dev PR checks
name: PR checks
on:
pull_request:
branches:
- dev
- main
jobs:
tsc-check:
@ -101,3 +101,13 @@ jobs:
run: |
cd binary
npx tsc --noEmit
- name: Run core tests
run: |
cd core
npm test
- name: Run gui tests
run: |
cd gui
npm test

View file

@ -210,7 +210,7 @@ jobs:
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin dev
run: git pull origin main
# 1. Download the artifacts
- uses: actions/download-artifact@v4

View file

@ -4,7 +4,6 @@ on:
pull_request:
branches:
- main
- preview
jobs:
tsc-check:

View file

@ -15,7 +15,7 @@
- [🧑‍💻 Contributing Code](#-contributing-code)
- [Environment Setup](#environment-setup)
- [Pre-requisites](#pre-requisites)
- [Fork the Continue Repository with All Branches](#fork-the-continue-repository-with-all-branches)
- [Fork the Continue Repository with All Branches](#fork-the-continue-repository)
- [VS Code](#vs-code)
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
@ -94,8 +94,6 @@ This will start a local server and you can see the documentation rendered in you
## 🧑‍💻 Contributing Code
> Please make PRs to the `dev` branch. We use this to first test changes in a pre-release version of the extension.
### Environment Setup
#### Pre-requisites
@ -106,15 +104,15 @@ You should have Node.js version 20.11.0 (LTS) or higher installed. You can get i
nvm use
```
#### Fork the Continue Repository with All Branches
#### Fork the Continue Repository
1. Go to the [Continue GitHub repository](https://github.com/continuedev/continue) and fork it to your GitHub account. **Ensure all branches are included in the fork**.
1. Go to the [Continue GitHub repository](https://github.com/continuedev/continue) and fork it to your GitHub account.
2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git`
3. Navigate to the cloned directory and switch to the **dev** branch. Execute: `git checkout dev`, then create your feature/fix branch from there, like so: `git checkout -b 123-my-feature-branch`
3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there, like so: `git checkout -b 123-my-feature-branch`
4. When you're ready to submit your changes, send your pull request specifically to the **dev** branch.
4. Send your pull request to the main branch.
#### VS Code
@ -145,7 +143,7 @@ See the [`CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBr
### Our Git Workflow
We keep two permanent branches: `main` and `dev`. All contributions should be made as pull requests to the `dev` branch. When we are ready to create a "pre-release" version, we create a tag on the `dev` branch, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will merge its tag into the `main` branch. Creating a tag on the `main` branch will then trigger a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question.
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by http://releaseflow.org.
### Formatting

View file

@ -253,6 +253,7 @@ export class CompletionProvider {
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
...helper.options,
};
@ -266,6 +267,12 @@ export class CompletionProvider {
}
}, 100);
// When using the JetBrains extension, Mark as displayed
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcome);
}
return outcome;
} catch (e: any) {
this.onError(e);

View file

@ -1,9 +0,0 @@
TODO
- The generator reuse thing isn't working it seems
Tests for context:
- You need a static set of files to test. Ideally you don't have to rewrite the exact same files every time you want to make a new test.
- So put some example files in a few folders. There should be a folder for each language I think.
- You should definitely test each of the services separately

View file

@ -86,7 +86,7 @@ export async function testRootPathContext(
}
describe("RootPathContextService", () => {
it("should be true", async () => {
it.skip("should be true", async () => {
await testRootPathContext(
"typescript",
"file1.ts",

View file

@ -115,7 +115,7 @@ describe("lineStream", () => {
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should stop at a similar line", async () => {
it.only("should stop at a similar line", async () => {
const lineToTest = "const x = 6;";
const linesGenerator = await getLineGenerator([
"console.log();",

View file

@ -196,7 +196,7 @@ export function lineIsRepeated(a: string, b: string): boolean {
const aTrim = a.trim();
const bTrim = b.trim();
return distance(aTrim, bTrim) / bTrim.length < 0.05;
return distance(aTrim, bTrim) / bTrim.length < 0.1;
}
/**

View file

@ -156,22 +156,23 @@ public class Calculator {
POSTGRES_DB: mydb
`,
},
{
description: "Should autocomplete a Markdown list with nested items",
filename: "test.md",
input: `
- Item 1
- Item 2
- Subitem 1
<|fim|>
- Item 3
`,
llmOutput: ` - Subitem 2
- Subitem 3
`,
expectedCompletion: ` - Subitem 2
- Subitem 3`,
},
// TODO
// {
// description: "Should autocomplete a Markdown list with nested items",
// filename: "test.md",
// input: `
// - Item 1
// - Item 2
// - Subitem 1
// <|fim|>
// - Item 3
// `,
// llmOutput: ` - Subitem 2
// - Subitem 3
// `,
// expectedCompletion: ` - Subitem 2
// - Subitem 3`,
// },
{
description: "Should enforce bracket matching in JSON files",
filename: "test.json",
@ -1585,62 +1586,65 @@ console.log(multiplyNumbers(2, 3));
expectedCompletion: `turn a * b;`,
},
{
description:
"Should handle autocomplete inside a nested TypeScript class method",
filename: "Account.ts",
input: `
class Account {
private balance: number = 0;
// TODO
// {
// description:
// "Should handle autocomplete inside a nested TypeScript class method",
// filename: "Account.ts",
// input: `
// class Account {
// private balance: number = 0;
deposit(amount: number) {
this.balance += amount;
return this.balance;
}
// deposit(amount: number) {
// this.balance += amount;
// return this.balance;
// }
withdraw(amount: number) {
if (amount > this.balance) {
throw new Error("Insufficient funds");
}
this.balance -= amount;
return thi<|fim|>
}
}
`,
llmOutput: `s.balance;`,
expectedCompletion: `s.balance;`,
},
// withdraw(amount: number) {
// if (amount > this.balance) {
// throw new Error("Insufficient funds");
// }
// this.balance -= amount;
// return thi<|fim|>
// }
// }
// `,
// llmOutput: `s.balance;`,
// expectedCompletion: `s.balance;`,
// },
{
description: "Should autocomplete a TypeScript generic function",
filename: "GenericFunction.ts",
input: `
function identity<T>(arg: T): T {
return ar<|fim|>
}
// TODO
// {
// description: "Should autocomplete a TypeScript generic function",
// filename: "GenericFunction.ts",
// input: `
// function identity<T>(arg: T): T {
// return ar<|fim|>
// }
console.log(identity<number>(5));
`,
llmOutput: `g;`,
expectedCompletion: `g;`,
},
// console.log(identity<number>(5));
// `,
// llmOutput: `g;`,
// expectedCompletion: `g;`,
// },
{
description:
"Should autocomplete a TypeScript promise within an asynchronous function",
filename: "asyncFunction.ts",
input: `
async function fetchData(url: string): Promise<unknown> {
const response = await fetch(url);
<|fim|>
return data;
}
// TODO
// {
// description:
// "Should autocomplete a TypeScript promise within an asynchronous function",
// filename: "asyncFunction.ts",
// input: `
// async function fetchData(url: string): Promise<unknown> {
// const response = await fetch(url);
// <|fim|>
// return data;
// }
fetchData('https://api.example.com/data');
`,
llmOutput: `const data = await response.json();`,
expectedCompletion: `const data = await response.json();`,
},
// fetchData('https://api.example.com/data');
// `,
// llmOutput: `const data = await response.json();`,
// expectedCompletion: `const data = await response.json();`,
// },
{
description:

View file

@ -40,4 +40,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
gitRepo?: string;
completionId: string;
uniqueId: string;
timestamp: number;
}

View file

@ -1,6 +1,6 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import SlashCommands from "./slash";
export function slashFromCustomCommand(

View file

@ -1,8 +1,6 @@
import GenerateTerminalCommand from "./cmd";
import CommentSlashCommand from "./comment";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import EditSlashCommand from "./edit";
import HttpSlashCommand from "./http";
import MultiFileEditSlashCommand from "./multifileEdit";
import OnboardSlashCommand from "./onboard";
@ -13,8 +11,6 @@ export default [
DraftIssueCommand,
ShareSlashCommand,
GenerateTerminalCommand,
EditSlashCommand,
CommentSlashCommand,
HttpSlashCommand,
CommitMessageCommand,
ReviewMessageCommand,

View file

@ -1,6 +1,4 @@
import { SlashCommand } from "../..";
import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util";
import { VsCodeIde } from "../../../extensions/vscode/src/VsCodeIde";
import { stripImages } from "../../llm/images";
const MultiFileEditSlashCommand: SlashCommand = {
@ -12,7 +10,10 @@ const MultiFileEditSlashCommand: SlashCommand = {
selectedCode.map(async (item) => {
// Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]`
const [filepath, rangeStr] = item.filepath.split(" ");
const fullPath = getFullyQualifiedPath(ide as VsCodeIde, filepath);
const { getFullyQualifiedPath } = await import(
"../../../extensions/vscode/src/util/util"
);
const fullPath = getFullyQualifiedPath(ide as any, filepath); // any = VsCodeIde here, but importing it breaks tests
if (!fullPath) {
return "";

View file

@ -1,9 +1,9 @@
import fs from "node:fs";
import path from "node:path";
import { defaultConfig } from "./default";
import { getConfigTsPath } from "../util/paths";
import { testConfigHandler } from "../test/util/fixtures";
import { TEST_DIR } from "../test/util/testDir";
import { getConfigTsPath } from "../util/paths";
import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {

View file

@ -67,14 +67,6 @@ export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [
];
export const defaultSlashCommandsVscode: SlashCommandDescription[] = [
{
name: "edit",
description: "Edit selected code",
},
{
name: "comment",
description: "Write comments for the selected code",
},
{
name: "share",
description: "Export the current chat session to markdown",
@ -90,14 +82,6 @@ export const defaultSlashCommandsVscode: SlashCommandDescription[] = [
];
export const defaultSlashCommandsJetBrains = [
{
name: "edit",
description: "Edit selected code",
},
{
name: "comment",
description: "Write comments for the selected code",
},
{
name: "share",
description: "Export the current chat session to markdown",

View file

@ -1,16 +1,9 @@
import { execSync } from "child_process";
import * as JSONC from "comment-json";
import * as fs from "fs";
import os from "os";
import path from "path";
import * as tar from "tar";
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import { AllRerankers } from "../context/rerankers/index";
import { LLMReranker } from "../context/rerankers/llm";
import {
BrowserSerializedContinueConfig,
Config,
@ -30,18 +23,25 @@ import {
SerializedContinueConfig,
SlashCommand,
} from "..";
import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider";
import { allEmbeddingsProviders } from "../indexing/embeddings";
import { BaseLLM } from "../llm";
import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { llmFromDescription } from "../llm/llms";
import os from "os";
import { execSync } from "child_process";
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import { fetchwithRequestOptions } from "../util/fetchWithOptions";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import { AllRerankers } from "../context/rerankers/index";
import { LLMReranker } from "../context/rerankers/llm";
import { allEmbeddingsProviders } from "../indexing/embeddings";
import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider";
import { BaseLLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { copyOf } from "../util";
import { fetchwithRequestOptions } from "../util/fetchWithOptions";
import mergeJson from "../util/merge";
import {
DEFAULT_CONFIG_TS_CONTENTS,
@ -65,8 +65,9 @@ import {
getPromptFiles,
slashCommandFromPromptFile,
} from "./promptFile.js";
import { validateConfig, ConfigValidationError } from "./validation.js";
import { ConfigValidationError, validateConfig } from "./validation.js";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { GlobalContext } from "../util/GlobalContext";
export interface ConfigResult<T> {
@ -187,6 +188,7 @@ async function serializedToIntermediateConfig(
const promptFolder = initial.experimental?.promptPath;
if (loadPromptFiles) {
// v1 prompt files
let promptFiles: { path: string; content: string }[] = [];
promptFiles = (
await Promise.all(
@ -238,6 +240,7 @@ async function intermediateToFinalConfig(
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
loadPromptFiles: boolean = true,
allowFreeTrial: boolean = true,
): Promise<ContinueConfig> {
// Auto-detect models
@ -389,6 +392,7 @@ async function intermediateToFinalConfig(
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(

View file

@ -4,7 +4,7 @@ import * as YAML from "yaml";
import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { getBasename } from "../util/index";
import { BaseContextProvider } from "../context";

View file

@ -542,6 +542,7 @@ declare global {
| "folder"
| "jira"
| "postgres"
| "mssql"
| "database"
| "code"
| "docs"
@ -734,6 +735,7 @@ declare global {
stop?: string[];
maxTokens?: number;
numThreads?: number;
useMmap?: boolean;
keepAlive?: number;
raw?: boolean;
stream?: boolean;

View file

@ -0,0 +1,56 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { getAllPromptFilesV2 } from "../../promptFiles/v2/getPromptFiles";
import { parsePreamble } from "../../promptFiles/v2/parse";
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
class PromptFilesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "prompt-files",
displayTitle: "Prompt Files",
description: ".prompt files",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const rawContent = await extras.ide.readFile(query);
const preamble = parsePreamble(query, rawContent);
const [contextItems, body] = await renderPromptFileV2(rawContent, extras);
return [
...contextItems,
{
content: body,
name: preamble.name,
description: preamble.description,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const promptFiles = await getAllPromptFilesV2(
args.ide,
args.config.experimental?.promptPath,
);
return promptFiles.map((file) => {
const preamble = parsePreamble(file.path, file.content);
return {
id: file.path,
title: preamble.name,
description: preamble.description,
};
});
}
}
export default PromptFilesContextProvider;

View file

@ -4,6 +4,7 @@ import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
import CurrentFileContextProvider from "./CurrentFileContextProvider";
import DatabaseContextProvider from "./DatabaseContextProvider";
import DebugLocalsProvider from "./DebugLocalsProvider";
import DiffContextProvider from "./DiffContextProvider";
import DiscordContextProvider from "./DiscordContextProvider";
import DocsContextProvider from "./DocsContextProvider";
@ -15,7 +16,6 @@ import GoogleContextProvider from "./GoogleContextProvider";
import GreptileContextProvider from "./GreptileContextProvider";
import HttpContextProvider from "./HttpContextProvider";
import JiraIssuesContextProvider from "./JiraIssuesContextProvider/";
import DebugLocalsProvider from "./DebugLocalsProvider";
import OSContextProvider from "./OSContextProvider";
import OpenFilesContextProvider from "./OpenFilesContextProvider";
import PostgresContextProvider from "./PostgresContextProvider";

View file

@ -54,6 +54,7 @@ const modelDescriptionSchema = z.object({
stop: z.array(z.string()).optional(),
maxTokens: z.number().optional(),
numThreads: z.number().optional(),
useMmap: z.boolean().optional(),
keepAlive: z.number().optional(),
raw: z.boolean().optional(),
stream: z.boolean().optional(),

View file

@ -10,7 +10,6 @@ import {
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { createNewPromptFile } from "./config/promptFile";
import { addModel, addOpenAIKey, deleteModel } from "./config/util";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
@ -21,6 +20,7 @@ import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { GlobalContext } from "./util/GlobalContext";
import { ChatDescriber } from "./util/chatDescriber";
@ -80,7 +80,7 @@ export class Core {
constructor(
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
private readonly ide: IDE,
private readonly onWrite: (text: string) => Promise<void> = async () => {},
private readonly onWrite: (text: string) => Promise<void> = async () => { },
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
@ -171,7 +171,7 @@ export class Core {
this.configHandler,
ide,
getLlm,
(e) => {},
(e) => { },
(..._) => Promise.resolve([]),
);
@ -248,11 +248,11 @@ export class Core {
});
on("config/newPromptFile", async (msg) => {
void createNewPromptFile(
await createNewPromptFileV2(
this.ide,
(await this.config()).experimental?.promptPath,
);
void this.configHandler.reloadConfig();
await this.configHandler.reloadConfig();
});
on("config/reload", (msg) => {
@ -681,7 +681,7 @@ export class Core {
await codebaseIndexer.clearIndexes();
}
const dirs = data?.dir ? [data.dir] : await this.ide.getWorkspaceDirs();
const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs();
await this.refreshCodebaseIndex(dirs);
});
on("index/setPaused", (msg) => {

View file

@ -127,11 +127,11 @@ describe("deterministicApplyLazyEdit(", () => {
await expectDiff("calculator-comments.js");
});
test("calculator docstrings", async () => {
test.skip("calculator docstrings", async () => {
await expectDiff("calculator-docstrings.js");
});
test("calculator stateless", async () => {
test.skip("calculator stateless", async () => {
await expectDiff("calculator-stateless.js");
});
@ -151,7 +151,7 @@ describe("deterministicApplyLazyEdit(", () => {
await expectDiff("no-lazy.js");
});
test("no lazy blocks in single top level class", async () => {
test.skip("no lazy blocks in single top level class", async () => {
await expectDiff("no-lazy-single-class.js");
});

1
core/index.d.ts vendored
View file

@ -803,6 +803,7 @@ interface BaseCompletionOptions {
stop?: string[];
maxTokens?: number;
numThreads?: number;
useMmap?: boolean;
keepAlive?: number;
raw?: boolean;
stream?: boolean;

View file

@ -2,14 +2,14 @@ import { jest } from "@jest/globals";
import { testIde } from "../test/util/fixtures";
import {
insertMockChunks,
updateIndexAndAwaitGenerator,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
describe("CodeSnippetsCodebaseIndex", () => {
describe.skip("CodeSnippetsCodebaseIndex", () => {
let index: CodeSnippetsCodebaseIndex;
let db: DatabaseConnection;

View file

@ -8,7 +8,7 @@ import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
describe("FullTextSearchCodebaseIndex", () => {
describe.skip("FullTextSearchCodebaseIndex", () => {
let index: FullTextSearchCodebaseIndex;
let db: DatabaseConnection;

View file

@ -14,7 +14,7 @@ import { IndexResultType } from "./types";
jest.useFakeTimers();
describe("ChunkCodebaseIndex", () => {
describe.skip("ChunkCodebaseIndex", () => {
let index: LanceDbIndex;
let sqliteDb: DatabaseConnection;
let lanceDb: lance.Connection;

View file

@ -1,7 +1,6 @@
import ignore from "ignore";
import path from "path";
import os from "os";
import fs from "fs";
import ignore from "ignore";
import { getGlobalContinueIgnorePath } from "../util/paths";
export const DEFAULT_IGNORE_FILETYPES = [
"*.DS_Store",
@ -118,17 +117,7 @@ export function gitIgArrayFromFile(file: string) {
.filter((l) => !/^#|^$/.test(l)); // Remove empty lines
}
export const GLOBAL_CONTINUEIGNORE_PATH = path.join(os.homedir(), ".continue", ".continueignore");
export const getGlobalContinueIgArray = () => {
try {
const contents = fs.readFileSync(GLOBAL_CONTINUEIGNORE_PATH, "utf8");
return gitIgArrayFromFile(contents);
} catch (error) {
// If the file doesn't exist, that's okay
if (error instanceof Error && ("code" in error) && error.code === "ENOENT") {
return [];
}
throw error;
}
};
const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
return gitIgArrayFromFile(contents);
};

View file

@ -30,6 +30,7 @@ interface ModelFileParams {
min_p?: number;
// deprecated?
num_thread?: number;
use_mmap?: boolean;
num_gqa?: number;
num_gpu?: number;
}
@ -191,6 +192,7 @@ class Ollama extends BaseLLM {
num_ctx: this.contextLength,
mirostat: options.mirostat,
num_thread: options.numThreads,
use_mmap: options.useMmap,
min_p: options.minP,
};
}

View file

@ -5,9 +5,10 @@ import {
LLMOptions,
ModelDescription,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Asksage from "./Asksage";
import Azure from "./Azure";
import Bedrock from "./Bedrock";
import BedrockImport from "./BedrockImport";
@ -40,11 +41,10 @@ import SageMaker from "./SageMaker";
import SambaNova from "./SambaNova";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import VertexAI from "./VertexAI";
import Vllm from "./Vllm";
import WatsonX from "./WatsonX";
import ContinueProxy from "./stubs/ContinueProxy";
import VertexAI from "./VertexAI";
import Asksage from "./Asksage";
import xAI from "./xAI";
const LLMs = [
@ -86,7 +86,7 @@ const LLMs = [
Asksage,
Nebius,
VertexAI,
xAI
xAI,
];
export async function llmFromDescription(

15
core/package-lock.json generated
View file

@ -39,7 +39,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"lru-cache": "^11.0.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@ -10903,11 +10903,11 @@
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
},
"node_modules/lru-cache": {
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
"integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz",
"integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==",
"engines": {
"node": "14 || >=16.14"
"node": "20 || >=22"
}
},
"node_modules/mac-ca": {
@ -12123,6 +12123,11 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/path-scurry/node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="
},
"node_modules/path-scurry/node_modules/minipass": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",

View file

@ -70,7 +70,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"lru-cache": "^11.0.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -1,6 +1,6 @@
import path from "path";
import { IDE } from "..";
import { DEFAULT_PROMPTS_FOLDER } from "./";
import { DEFAULT_PROMPTS_FOLDER } from ".";
import { IDE } from "../..";
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue

View file

@ -1,5 +1,5 @@
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
import { IDE } from "../..";
import { walkDir } from "../../indexing/walkDir";
export async function getPromptFiles(
ide: IDE,

View file

@ -1,8 +1,7 @@
import { IDE } from "..";
import { getPromptFiles } from "./getPromptFiles";
import { createNewPromptFile } from "./createNewPromptFile";
import { getPromptFiles } from "./getPromptFiles";
import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
export { getPromptFiles, createNewPromptFile, slashCommandFromPromptFile };
export { createNewPromptFile, getPromptFiles, slashCommandFromPromptFile };

View file

@ -1,10 +1,10 @@
import { ContinueSDK, SlashCommand } from "..";
import { stripImages } from "../llm/images";
import * as YAML from "yaml";
import { ContinueSDK, SlashCommand } from "../..";
import { stripImages } from "../../llm/images";
import { getBasename } from "../../util/index";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
import { updateChatHistory } from "./updateChatHistory";
import * as YAML from "yaml";
import { getBasename } from "../util/index";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getBasename(path).split(".prompt")[0];
@ -37,7 +37,10 @@ export function extractUserInput(input: string, commandName: string): string {
return input;
}
export async function getDefaultVariables(context: ContinueSDK, userInput: string): Promise<Record<string, string>> {
export async function getDefaultVariables(
context: ContinueSDK,
userInput: string,
): Promise<Record<string, string>> {
const currentFile = await context.ide.getCurrentFile();
const vars: Record<string, string> = { input: userInput };
if (currentFile) {

View file

@ -0,0 +1,74 @@
import path from "path";
import { IDE } from "../..";
import { GlobalContext } from "../../util/GlobalContext";
import { DEFAULT_PROMPTS_FOLDER_V2 } from "./getPromptFiles";
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue
# Continue will automatically create a context provider for each prompt in the .prompts folder
# A prompt file consists of two parts:
# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options
# 2. Everything below the "---" is the prompt body
# If you don't want to set any options, you don't need to include the "---"
# In the body, you can reference:
# 1. Files, using either absolute or relative (based on the workspace root) paths
# e.g. @README.md
# e.g. @src/test/test.py
# e.g. @/Users/me/Desktop/my-project/src/test/test.py
# 2. URLs
# e.g. https://example.com
# 3. Some context providers, like
# e.g. @currentFile
# e.g. @os
# e.g. @repo-map
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
name: Example
description: Example prompt file
version: 2
---
@README.md
Please reference the above README.md file to understand the current project.
`;
const DEFAULT_PROMPT_FILE = `version: 2
---
`;
export async function createNewPromptFileV2(
ide: IDE,
promptPath: string | undefined,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const baseDir = path.join(
workspaceDirs[0],
promptPath ?? DEFAULT_PROMPTS_FOLDER_V2,
);
// Find the first available filename
let counter = 0;
let promptFilePath: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
promptFilePath = path.join(baseDir, `new-prompt-file${suffix}.prompt`);
counter++;
} while (await ide.fileExists(promptFilePath));
const PROMPT_FILE =
new GlobalContext().get("hasAlreadyCreatedAPromptFile") === true
? DEFAULT_PROMPT_FILE
: FIRST_TIME_DEFAULT_PROMPT_FILE;
await ide.writeFile(promptFilePath, PROMPT_FILE);
await ide.openFile(promptFilePath);
}

View file

@ -0,0 +1,59 @@
import path from "path";
import { IDE } from "../..";
import { walkDir } from "../../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../../util/paths";
async function getPromptFilesFromDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
const results = paths.map(async (path) => {
const content = await ide.readFile(path); // make a try catch
return { path, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}
export const DEFAULT_PROMPTS_FOLDER_V2 = ".prompts";
export async function getAllPromptFilesV2(
ide: IDE,
overridePromptFolder?: string,
): Promise<{ path: string; content: string }[]> {
const workspaceDirs = await ide.getWorkspaceDirs();
let promptFiles: { path: string; content: string }[] = [];
promptFiles = (
await Promise.all(
workspaceDirs.map((dir) =>
getPromptFilesFromDir(
ide,
path.join(dir, overridePromptFolder ?? DEFAULT_PROMPTS_FOLDER_V2),
),
),
)
)
.flat()
.filter(({ path }) => path.endsWith(".prompt"));
// Also read from ~/.continue/.prompts
promptFiles.push(...readAllGlobalPromptFiles());
return await Promise.all(
promptFiles.map(async (file) => {
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),
);
}

View file

@ -0,0 +1,33 @@
import * as YAML from "yaml";
import { getBasename } from "../../util";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getBasename(path).split(".prompt")[0];
}
export function getPreambleAndBody(content: string): [string, string] {
let [preamble, body] = content.split("\n---\n");
if (body === undefined) {
// This means there is no preamble
body = preamble;
preamble = "";
}
return [preamble, body];
}
export function parsePreamble(
path: string,
content: string,
): { [key: string]: any; name: string; description: string } {
const [preambleRaw, _] = getPreambleAndBody(content);
const preamble = YAML.parse(preambleRaw) ?? {};
const name = extractName(preamble, path);
const description = preamble.description ?? name;
return {
...preamble,
name,
description,
};
}

View file

@ -0,0 +1,52 @@
import { ContextItem, ContextProviderExtras } from "../..";
import URLContextProvider from "../../context/providers/URLContextProvider";
import { getBasename } from "../../util";
import { getPreambleAndBody } from "./parse";
async function resolveAttachment(
name: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Context providers
const contextProvider = extras.config.contextProviders?.find(
(provider) => provider.description.title === name,
);
if (contextProvider) {
const items = await contextProvider.getContextItems("", extras);
return items;
}
// Files
if (await extras.ide.fileExists(name)) {
const content = `\`\`\`${name}\n${await extras.ide.readFile(name)}\n\`\`\``;
return [{ name: getBasename(name), content, description: name }];
}
// URLs
if (name.startsWith("http")) {
const items = await new URLContextProvider({}).getContextItems(
name,
extras,
);
return items;
}
return [];
}
export async function renderPromptFileV2(
rawContent: string,
extras: ContextProviderExtras,
): Promise<[ContextItem[], string]> {
const [preamble, body] = getPreambleAndBody(rawContent);
const contextItemsPromises: Promise<ContextItem[]>[] = [];
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
contextItemsPromises.push(resolveAttachment(name, extras));
return match;
});
const contextItems = (await Promise.all(contextItemsPromises)).flat();
return [contextItems, renderedBody];
}

View file

@ -143,7 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"tts/kill": [undefined, void];
"index/setPaused": [boolean, void];
"index/forceReIndex": [
undefined | { dir?: string; shouldClearIndexes?: boolean },
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
void,
];
"index/indexingProgressBarInitialized": [undefined, void];

View file

@ -55,7 +55,7 @@ function testLLM(llm: BaseLLM) {
});
}
describe("LLM", () => {
describe.skip("LLM", () => {
// testLLM(
// new FreeTrial({
// model: "gpt-3.5-turbo",

View file

@ -14,6 +14,7 @@ export type GlobalContextType = {
*/
curEmbeddingsProviderId: EmbeddingsProvider["id"];
hasDismissedConfigTsNoticeJetBrains: boolean;
hasAlreadyCreatedAPromptFile: boolean;
};
/**

View file

@ -28,6 +28,17 @@ export function getContinueUtilsPath(): string {
return utilsPath;
}
export function getGlobalContinueIgnorePath(): string {
const continueIgnorePath = path.join(
getContinueGlobalPath(),
".continueignore",
);
if (!fs.existsSync(continueIgnorePath)) {
fs.writeFileSync(continueIgnorePath, "");
}
return continueIgnorePath;
}
export function getContinueGlobalPath(): string {
// This is ~/.continue on mac/linux
const continuePath = CONTINUE_GLOBAL_DIR;

View file

@ -390,7 +390,7 @@ By default, the `schema` filter is set to `public`, and the `sampleRows` is set
### `@Database`
Reference table schemas from Sqlite, Postgres, and MySQL databases.
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
```json title="config.json"
{
@ -410,6 +410,16 @@ Reference table schemas from Sqlite, Postgres, and MySQL databases.
"port": 5432
}
},
{
"name": "exampleMssql",
"connection_type": "mssql",
"connection": {
"user": "username",
"server": "localhost",
"database": "exampleDB",
"password": "yourPassword"
}
},
{
"name": "exampleSqlite",
"connection_type": "sqlite",

View file

@ -24,6 +24,7 @@ In addition to the model type, you can also configure some of the parameters tha
- top_k: options.topK - This parameter limits the number of unique tokens to consider when generating the next token in the sequence. Higher values increase the variety of generated sequences, while lower values lead to more focused outputs.
- num_predict: options.maxTokens - This determines the maximum number of tokens (words or characters) to generate for the given input prompt.
- num_thread: options.numThreads - This is the multi-threading configuration option that controls how many threads the model uses for parallel processing. Higher values may lead to faster generation times but could also increase memory usage and complexity. Set this to one or two lower than the number of threads your CPU can handle to leave some for your GUI when running the model locally.
- use_mmap: options.useMmap - For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
## Authentication

View file

@ -12,37 +12,7 @@ Slash commands are shortcuts that can be activated by typing '/' and selecting f
To use any of the built-in slash commands, open `config.json` and add it to the `slashCommands` list.
### `/Edit`
Select code with `ctrl/cmd + L` (VS Code) or `ctrl/cmd + J` (JetBrains), and then type `/Edit`, followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor.
```json title="config.json"
{
"slashCommands": [
{
"name": "edit",
"description": "Edit highlighted code"
}
]
}
```
### `/Comment`
Comment works just like `/Edit`, except it will automatically prompt the LLM to comment the code.
```json title="config.json"
{
"slashCommands": [
{
"name": "comment",
"description": "Write comments for the highlighted code"
}
]
}
```
### `/Share`
### `/share`
Generate a shareable markdown transcript of your current chat history.
@ -60,7 +30,7 @@ Generate a shareable markdown transcript of your current chat history.
Use the `outputDir` parameter to specify where you want to the markdown file to be saved.
### `/Cmd`
### `/cmd`
Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal.
@ -75,7 +45,7 @@ Generate a shell command from natural language and (only in VS Code) automatical
}
```
### `/Commit`
### `/commit`
Shows the LLM your current git diff and asks it to generate a commit message.
@ -90,7 +60,7 @@ Shows the LLM your current git diff and asks it to generate a commit message.
}
```
### `/Http`
### `/http`
Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference.
@ -106,7 +76,7 @@ Write a custom slash command at your own HTTP endpoint. Set 'url' in the params
}
```
### `/Issue`
### `/issue`
Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for.
@ -122,9 +92,9 @@ Describe the issue you'd like to generate, and Continue will turn into a well-fo
}
```
### `/Onboard`
### `/onboard`
The Onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture.
The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture.
```json title="config.json"
{

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

View file

@ -203,26 +203,48 @@ The `"options"` property can be used to send additional parameters to your endpo
Continue exposes an API for registering context providers from a 3rd party VSCode extension. This is useful if you have a VSCode extension that provides some additional context that you would like to use in Continue. To use this API, add the following to your `package.json`:
```json
```json title="package.json"
{
"extensionDependencies": ["continue.continue"]
}
```
Or copy `~/.continue/type/core/index.d.ts` to your extension repository.
Or install the Continue Core module from npm:
```bash
npm i @continuedev/core
```
You can add the Continue core module as a dev dependency in your `package.json`:
```json title="package.json"
{
"devDependencies": {
"@continuedev/core": "^0.0.1"
}
}
```
Then, you can use the `registerCustomContextProvider` function to register your context provider. Your custom context provider must implement the `IContextProvider` interface.
Here is an example:
```typescript
```typescript title="myCustomContextProvider.ts"
import * as vscode from "vscode";
import {
IContextProvider,
ContextProviderDescription,
ContextProviderExtras,
ContextItem,
LoadSubmenuItemsArgs,
ContextSubmenuItem,
} from "@continuedev/core";
class MyCustomProvider implements IContextProvider {
get description(): ContextProviderDescription {
return {
title: "custom",
title: "Custom",
displayTitle: "Custom",
description: "Custom description",
description: "my custom context provider",
type: "normal",
};
}
@ -251,7 +273,7 @@ class MyCustomProvider implements IContextProvider {
const customProvider = new MyCustomProvider();
// get Continue extension using vscode API
const continueExt = vscode.extensions.getExtension("continue.continue");
const continueExt = vscode.extensions.getExtension("Continue.continue");
// get the API from the extension
const continueApi = continueExt?.exports;
@ -259,3 +281,7 @@ const continueApi = continueExt?.exports;
// register your custom provider
continueApi?.registerCustomContextProvider(customProvider);
```
This will register `MyCustomProvider` with Continue!
![alt text](./assets/image.png)

View file

@ -158,6 +158,7 @@ Parameters that control the behavior of text generation and completion settings.
- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`).
- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`.
- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes).
- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
Example
@ -267,7 +268,7 @@ Custom commands initiated by typing "/" in the sidebar. Commands include predefi
**Properties:**
- `name`: The command name. Options include "issue", "share", "cmd", "edit", "comment", "http", "commit", and "review".
- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review".
- `description`: Brief description of the command.
- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options.
- `params`: Additional parameters to configure command behavior (command-specific - see code for command)
@ -281,10 +282,6 @@ Example:
"name": "commit",
"description": "Generate a commit message"
},
{
"name": "comment",
"description": "Write comments for the selected code"
},
{
"name": "share",
"description": "Export this session as markdown"

View file

@ -30,6 +30,11 @@ import javax.swing.*
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
fun showTutorial(project: Project) {
val tutorialFileName = getTutorialFileName()
@ -148,6 +153,28 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
}
})
// Handle file changes and deletions - reindex
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
// Collect all relevant paths for deletions
val deletedPaths = events.filterIsInstance<VFileDeleteEvent>()
.map { event -> event.file.path.split("/").dropLast(1).joinToString("/") }
// Collect all relevant paths for content changes
val changedPaths = events.filterIsInstance<VFileContentChangeEvent>()
.map { event -> event.file.path.split("/").dropLast(1).joinToString("/") }
// Combine both lists of paths for re-indexing
val allPaths = deletedPaths + changedPaths
// Create a data map if there are any paths to re-index
if (allPaths.isNotEmpty()) {
val data = mapOf("dirs" to allPaths)
continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> }
}
}
})
// Listen for clicking settings button to start the auth flow
val authService = service<ContinueAuthService>()
val initialSessionInfo = authService.loadControlPlaneSessionInfo()

View file

@ -192,10 +192,9 @@ class AutocompleteService(private val project: Project) {
editor.caretModel.moveToOffset(offset + text.length)
project.service<ContinuePluginService>().coreMessenger?.request(
"autocomplete/accept",
completion.completionId,
hashMapOf("completionId" to completion.completionId),
null,
({})
)

View file

@ -48,14 +48,6 @@ const val DEFAULT_CONFIG =
}
],
"slashCommands": [
{
"name": "edit",
"description": "Edit selected code"
},
{
"name": "comment",
"description": "Write comments for the selected code"
},
{
"name": "share",
"description": "Export the current chat session to markdown"

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,64 @@
{
"name": "Prompt",
"scopeName": "source.prompt",
"patterns": [
{
"include": "#at-references"
},
{
"include": "#strings"
},
{
"include": "#comments"
}
],
"repository": {
"at-references": {
"patterns": [
{
"name": "entity.name.type.prompt",
"match": "@\\S+"
}
]
},
"strings": {
"patterns": [
{
"name": "string.quoted.double.prompt",
"begin": "\"",
"end": "\"",
"patterns": [
{
"name": "constant.character.escape.prompt",
"match": "\\\\."
}
]
},
{
"name": "string.quoted.single.prompt",
"begin": "'",
"end": "'",
"patterns": [
{
"name": "constant.character.escape.prompt",
"match": "\\\\."
}
]
}
]
},
"comments": {
"patterns": [
{
"name": "comment.line.double-slash.prompt",
"match": "//.*$"
},
{
"name": "comment.block.prompt",
"begin": "/\\*",
"end": "\\*/"
}
]
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -64,6 +64,23 @@
".continuerc.json"
],
"id": "jsonc"
},
{
"id": "promptLanguage",
"extensions": [
".prompt"
],
"aliases": [
"Prompt Language"
],
"configuration": "./prompt-file-language-configuration.json"
}
],
"grammars": [
{
"language": "promptLanguage",
"scopeName": "source.prompt",
"path": "./media/prompt.tmLanguage.json"
}
],
"configuration": {
@ -591,7 +608,7 @@
"axios": "^1.2.5",
"core": "file:../../core",
"cors": "^2.8.5",
"dbinfoz": "^0.11.0",
"dbinfoz": "^0.14.0",
"downshift": "^7.6.0",
"esbuild": "^0.17.19",
"express": "^4.18.2",

View file

@ -49,7 +49,8 @@ class VsCodeIde implements IDE {
return Promise.resolve(this.ideUtils.path.sep);
}
async fileExists(filepath: string): Promise<boolean> {
return vscode.workspace.fs.stat(uriFromFilePath(filepath)).then(
const absPath = await this.ideUtils.resolveAbsFilepathInWorkspace(filepath);
return vscode.workspace.fs.stat(uriFromFilePath(absPath)).then(
() => true,
() => false,
);

View file

@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { ContextMenuConfig } from "core";
import { CompletionProvider } from "core/autocomplete/completionProvider";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { RangeInFileWithContents } from "core/commands/util";
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";

View file

@ -19,6 +19,7 @@ import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvide
import { DiffManager } from "../diff/horizontal";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { registerAllPromptFilesCompletionProviders } from "../lang-server/promptFileCompletions";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
@ -28,6 +29,7 @@ import {
} from "../stubs/WorkOsAuthProvider";
import { arePathsEqual } from "../util/arePathsEqual";
import { Battery } from "../util/battery";
import { FileSearch } from "../util/FileSearch";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { VsCodeIde } from "../VsCodeIde";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
@ -49,6 +51,7 @@ export class VsCodeExtension {
private core: Core;
private battery: Battery;
private workOsAuthProvider: WorkOsAuthProvider;
private fileSearch: FileSearch;
constructor(context: vscode.ExtensionContext) {
// Register auth provider
@ -206,12 +209,21 @@ export class VsCodeExtension {
context.subscriptions.push(this.battery);
context.subscriptions.push(monitorBatteryChanges(this.battery));
// FileSearch
this.fileSearch = new FileSearch(this.ide);
registerAllPromptFilesCompletionProviders(
context,
this.fileSearch,
this.ide,
);
const quickEdit = new QuickEdit(
this.verticalDiffManager,
this.configHandler,
this.sidebar.webviewProtocol,
this.ide,
context,
this.fileSearch,
);
// Commands
@ -279,11 +291,18 @@ export class VsCodeExtension {
this.core.invoke("index/forceReIndex", undefined);
} else {
// Reindex the file
const indexer = await this.core.codebaseIndexerPromise;
indexer.refreshFile(filepath);
this.core.invoke("index/forceReIndex", {
dirs: [filepath]
})
}
});
vscode.workspace.onDidDeleteFiles(async (event) => {
this.core.invoke("index/forceReIndex", {
dirs: event.files.map((file) => file.fsPath.split("/").slice(0, -1).join("/"))
})
})
// When GitHub sign-in status changes, reload config
vscode.authentication.onDidChangeSessions(async (e) => {
if (e.provider.id === "github") {
@ -316,7 +335,7 @@ export class VsCodeExtension {
currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
) {
// Trigger refresh of index only in this directory
this.core.invoke("index/forceReIndex", { dir });
this.core.invoke("index/forceReIndex", { dirs: [dir] });
}
}

View file

@ -0,0 +1,270 @@
import { IDE } from "core";
import { getBasename, getLastNPathParts } from "core/util";
import vscode from "vscode";
import { FileSearch } from "../util/FileSearch";
class PromptFilesCompletionItemProvider
implements vscode.CompletionItemProvider
{
constructor(
private fileSearch: FileSearch,
private ide: IDE,
) {}
async provideCompletionItems(
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken,
context: vscode.CompletionContext,
) {
const linePrefix =
document
.lineAt(position)
.text.substr(0, position.character)
.split(" ")
.pop() || "";
// Check if the last character typed is '@'
if (!linePrefix.includes("@")) {
return undefined;
}
const searchText = linePrefix.split("@").pop() || "";
const files = this.fileSearch.search(searchText).map(({ filename }) => {
return filename;
});
if (files.length === 0) {
const openFiles = await this.ide.getOpenFiles();
files.push(...openFiles);
}
// Provide completion items
return [
{
label: "terminal",
detail: "Contents of terminal",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
{
label: "tree",
detail: "File tree of workspace",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
{
label: "open",
detail: "All open files",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
{
label: "os",
detail: "Operating system information",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
{
label: "problems",
detail: "Problems in the current file",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
{
label: "currentFile",
detail: "Current file",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
{
label: "repo-map",
detail: "Map of files in your repo",
sortText: "...",
kind: vscode.CompletionItemKind.Field,
},
...files.map((file) => {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(
vscode.Uri.file(file),
);
const relativePath = workspaceFolder
? vscode.workspace.asRelativePath(file)
: file;
return {
label: getBasename(file),
detail: getLastNPathParts(file, 2),
insertText: relativePath,
kind: vscode.CompletionItemKind.File,
};
}),
];
}
}
function registerPromptFilesCompletionProvider(
context: vscode.ExtensionContext,
fileSearch: FileSearch,
ide: IDE,
) {
let provider = vscode.languages.registerCompletionItemProvider(
"promptLanguage",
new PromptFilesCompletionItemProvider(fileSearch, ide),
"@", // Trigger completion when '@' is typed
);
context.subscriptions.push(provider);
}
class YamlKeysCompletionItemProvider implements vscode.CompletionItemProvider {
private yamlKeys: { key: string; description: string }[] = [
{
key: "name",
description: "The name of the prompt template",
},
{
key: "description",
description: "A description of what this prompt template does",
},
{
key: "version",
description: ".prompt file version. Either 1 (legacy) or 2",
},
];
async provideCompletionItems(
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken,
context: vscode.CompletionContext,
) {
const lineText = document.lineAt(position).text;
const textBeforeCursor = lineText.substring(0, position.character);
// 1. Check if the cursor is in YAML section (before --- delimiter)
const beforeDelimiter = isCursorBeforeDelimiter(document, position);
if (!beforeDelimiter) {
return undefined;
}
// 2. Check if there is no colon before the cursor on this line
if (textBeforeCursor.includes(":")) {
return undefined;
}
// 3. Provide completion items for YAML keys
const completionItems = this.yamlKeys.map((key) => {
const item = new vscode.CompletionItem(
key.key,
vscode.CompletionItemKind.Property,
);
item.documentation = new vscode.MarkdownString(key.description);
item.insertText = key + ": ";
return item;
});
return completionItems;
}
}
// Helper function to determine if the cursor is before the '---' delimiter
function isCursorBeforeDelimiter(
document: vscode.TextDocument,
position: vscode.Position,
): boolean {
const delimiter = "---";
for (let i = 0; i < document.lineCount; i++) {
const lineText = document.lineAt(i).text.trim();
if (lineText === delimiter) {
// Cursor is before the delimiter
return position.line < i;
}
}
// Delimiter not found; assume entire document is YAML
return true;
}
function registerYamlKeysCompletionProvider(context: vscode.ExtensionContext) {
const provider = vscode.languages.registerCompletionItemProvider(
"promptLanguage",
new YamlKeysCompletionItemProvider(),
...Array.from("abcdefghijklmnopqrstuvwxyz"), // Trigger on all lowercase letters
);
context.subscriptions.push(provider);
}
// Helper function to determine if the position is within the YAML header
function isPositionInYamlHeader(
document: vscode.TextDocument,
position: vscode.Position,
): boolean {
const delimiter = "---";
for (let i = 0; i < document.lineCount; i++) {
const lineText = document.lineAt(i).text.trim();
if (lineText === delimiter) {
// Cursor is before the delimiter
return position.line < i;
}
}
// Delimiter not found; assume entire document is YAML
return true;
}
export function registerAllPromptFilesCompletionProviders(
context: vscode.ExtensionContext,
fileSearch: FileSearch,
ide: IDE,
) {
registerPromptFilesCompletionProvider(context, fileSearch, ide);
registerYamlKeysCompletionProvider(context);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument((event) => {
const editor = vscode.window.activeTextEditor;
if (!editor || event.document !== editor.document) {
return;
}
const languageId = editor.document.languageId;
if (languageId !== "promptLanguage") {
return;
}
for (const change of event.contentChanges) {
// Get position after the change by applying the change length
const isDeletion = change.text.length <= 0;
const lines = change.text.split("\n");
const positionAfterChange = isDeletion
? change.range.start
: new vscode.Position(
change.range.start.line + lines.length - 1,
lines.length === 1
? change.range.start.character + change.text.length
: lines[lines.length - 1].length,
);
// Use the updated document state
const line = event.document.lineAt(positionAfterChange.line);
// Check if we're in the YAML header using current document state
const inYamlHeader = isPositionInYamlHeader(
event.document,
positionAfterChange,
);
// Check if we're at the first character of the line
const atLineStart = positionAfterChange.character === 0;
// Check if the current line is empty (excluding whitespace)
const lineIsEmpty = line.text.trim() === "";
if (inYamlHeader && atLineStart && lineIsEmpty) {
// Delay slightly to ensure the editor updates before triggering suggestions
setTimeout(() => {
// Trigger suggestions
vscode.commands.executeCommand("editor.action.triggerSuggest");
}, 50);
}
}
}),
);
}

View file

@ -1,6 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE } from "core";
import { walkDir } from "core/indexing/walkDir";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
@ -13,9 +12,8 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick";
import { ConfigHandler } from "core/config/ConfigHandler";
// @ts-ignore
import { getModelByRole } from "core/config/util";
// @ts-ignore
import MiniSearch from "minisearch";
import { logDevData } from "core/util/devdata";
import { FileSearch } from "../util/FileSearch";
/**
* Used to track what action to take after a user interacts
@ -43,8 +41,6 @@ export type QuickEditShowParams = {
range?: vscode.Range;
};
type FileMiniSearchResult = { filename: string };
const FILE_SEARCH_CHAR = "@";
/**
@ -89,15 +85,6 @@ export class QuickEdit {
private range?: vscode.Range;
private initialPrompt?: string;
private miniSearch = new MiniSearch<FileMiniSearchResult>({
fields: ["filename"],
storeFields: ["filename"],
searchOptions: {
prefix: true,
fuzzy: 2,
},
});
private previousInput?: string;
/**
@ -123,9 +110,8 @@ export class QuickEdit {
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly ide: IDE,
private readonly context: vscode.ExtensionContext,
) {
this.initializeFileSearchState();
}
private readonly fileSearch: FileSearch,
) {}
/**
* Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt.
@ -238,7 +224,13 @@ export class QuickEdit {
break;
}
let model = await this.getCurModelTitle();
logDevData('quickEdit', {prompt, path, label, diffs: this.verticalDiffManager.logDiffs, model});
logDevData("quickEdit", {
prompt,
path,
label,
diffs: this.verticalDiffManager.logDiffs,
model,
});
quickPick.dispose();
});
}
@ -252,23 +244,6 @@ export class QuickEdit {
this.openAcceptRejectMenu(prompt, path);
};
private async initializeFileSearchState() {
const workspaceDirs = await this.ide.getWorkspaceDirs();
const results = await Promise.all(
workspaceDirs.map((dir) => {
return walkDir(dir, this.ide);
}),
);
const filenames = results.flat().map((file) => ({
id: file,
filename: vscode.workspace.asRelativePath(file),
}));
this.miniSearch.addAll(filenames);
}
private setActiveEditorAndPrevInput(editor: vscode.TextEditor) {
const existingHandler = this.verticalDiffManager.getHandlerForFile(
editor.document.uri.fsPath ?? "",
@ -321,8 +296,9 @@ export class QuickEdit {
return isSelectionEmpty
? `Edit ${fileName}`
: `Edit ${fileName}:${start.line}${end.line > start.line ? `-${end.line}` : ""
}`;
: `Edit ${fileName}:${start.line}${
end.line > start.line ? `-${end.line}` : ""
}`;
};
private async _streamEditWithInputAndContext(
@ -465,9 +441,7 @@ export class QuickEdit {
// search character to the end of the string
const searchQuery = value.substring(lastAtIndex + 1);
const searchResults = this.miniSearch.search(
searchQuery,
) as unknown as FileMiniSearchResult[];
const searchResults = this.fileSearch.search(searchQuery);
if (searchResults.length > 0) {
quickPick.items = searchResults

View file

@ -0,0 +1,42 @@
import { IDE } from "core";
import { walkDir } from "core/indexing/walkDir";
// @ts-ignore
import MiniSearch from "minisearch";
import * as vscode from "vscode";
type FileMiniSearchResult = { filename: string };
export class FileSearch {
constructor(private readonly ide: IDE) {
this.initializeFileSearchState();
}
private miniSearch = new MiniSearch<FileMiniSearchResult>({
fields: ["filename"],
storeFields: ["filename"],
searchOptions: {
prefix: true,
fuzzy: 2,
},
});
private async initializeFileSearchState() {
const workspaceDirs = await this.ide.getWorkspaceDirs();
const results = await Promise.all(
workspaceDirs.map((dir) => {
return walkDir(dir, this.ide);
}),
);
const filenames = results.flat().map((file) => ({
id: file,
filename: vscode.workspace.asRelativePath(file),
}));
this.miniSearch.addAll(filenames);
}
public search(query: string): FileMiniSearchResult[] {
return this.miniSearch.search(query) as unknown as FileMiniSearchResult[];
}
}

View file

@ -1,5 +1,4 @@
const os = require("node:os");
import path from "node:path";
import * as vscode from "vscode";
import { VsCodeIde } from "../VsCodeIde";

View file

@ -0,0 +1,79 @@
import { configureStore } from "@reduxjs/toolkit";
import { fireEvent, render, screen } from "@testing-library/react";
import { Provider } from "react-redux";
import { describe, expect, it, vi } from "vitest";
import { uiStateSlice } from "../../redux/slices/uiStateSlice";
import ConfirmationDialog from "./ConfirmationDialog";
const createMockStore = () => {
return configureStore({
reducer: {
uiState: uiStateSlice.reducer,
},
});
};
describe("ConfirmationDialog", () => {
const renderDialog = (props: any) => {
const store = createMockStore();
return render(
<Provider store={store}>
<ConfirmationDialog {...props} />
</Provider>,
);
};
it("renders with default props", () => {
const onConfirm = vi.fn();
renderDialog({ text: "Are you sure?", onConfirm });
expect(screen.getByText("Confirmation")).toBeInTheDocument();
expect(screen.getByText("Are you sure?")).toBeInTheDocument();
expect(screen.getByText("Cancel")).toBeInTheDocument();
expect(screen.getByText("Confirm")).toBeInTheDocument();
});
it("renders with custom title and confirm text", () => {
const onConfirm = vi.fn();
renderDialog({
text: "Delete item?",
title: "Custom Title",
confirmText: "Delete",
onConfirm,
});
expect(screen.getByText("Custom Title")).toBeInTheDocument();
expect(screen.getByText("Delete item?")).toBeInTheDocument();
expect(screen.getByText("Delete")).toBeInTheDocument();
});
it("hides cancel button when hideCancelButton is true", () => {
const onConfirm = vi.fn();
renderDialog({
text: "Proceed?",
hideCancelButton: true,
onConfirm,
});
expect(screen.queryByText("Cancel")).not.toBeInTheDocument();
});
it("calls onConfirm and dispatches actions when confirm button is clicked", () => {
const onConfirm = vi.fn();
renderDialog({ text: "Confirm action?", onConfirm });
fireEvent.click(screen.getByText("Confirm"));
expect(onConfirm).toHaveBeenCalledTimes(1);
});
it("calls onCancel and dispatches actions when cancel button is clicked", () => {
const onConfirm = vi.fn();
const onCancel = vi.fn();
renderDialog({ text: "Cancel action?", onConfirm, onCancel });
fireEvent.click(screen.getByText("Cancel"));
expect(onCancel).toHaveBeenCalledTimes(1);
});
});

View file

@ -2,7 +2,6 @@ import { NodeViewWrapper } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { useDispatch, useSelector } from "react-redux";
import { vscBadgeBackground } from "..";
import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice";
import { RootState } from "../../redux/store";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
@ -26,71 +25,13 @@ export const CodeBlockComponent = ({
item.id === contextItems[0]?.id
? "#d0d"
: selected
? vscBadgeBackground
: undefined
? vscBadgeBackground
: undefined
}
item={item}
onDelete={() => {
deleteNode();
}}
onEdit={async () => {
dispatch(setEditingContextItemAtIndex({ item }));
if (item.id === contextItems[0]?.id) {
// Find and delete the /edit command
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "slashcommand") {
if (el.attrs.id === "/edit") {
editor
.chain()
.deleteRange({ from: index, to: index + 2 })
.focus("end")
.run();
break;
}
}
index += 1;
}
updateAttributes({
item: {
...item,
editing: false,
},
});
} else {
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
}
editor
.chain()
.focus("end")
.insertContent([
{
type: "slashcommand",
attrs: { id: "/edit", label: "/edit" },
},
{ type: "text", text: " " },
])
.run();
updateAttributes({
item: {
...item,
editing: true,
},
});
await new Promise((resolve) => setTimeout(resolve, 100));
editor.commands.focus("end");
}
}}
editing={item.id === contextItems[0]?.id}
/>
</NodeViewWrapper>
);

View file

@ -6,14 +6,13 @@ import {
BookOpenIcon,
CodeBracketIcon,
CommandLineIcon,
DocumentTextIcon,
ExclamationCircleIcon,
ExclamationTriangleIcon,
FolderIcon,
FolderOpenIcon,
GlobeAltIcon,
HashtagIcon,
MagnifyingGlassIcon,
PencilIcon,
PlusIcon,
SparklesIcon,
TrashIcon,
@ -21,6 +20,7 @@ import {
import { Editor } from "@tiptap/react";
import {
forwardRef,
useContext,
useEffect,
useImperativeHandle,
useRef,
@ -36,6 +36,7 @@ import {
vscListActiveForeground,
vscQuickInputBackground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import {
setDialogMessage,
setShowDialog,
@ -61,10 +62,9 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
issue: ExclamationCircleIcon,
trash: TrashIcon,
web: GlobeAltIcon,
"prompt-files": DocumentTextIcon,
"repo-map": FolderIcon,
"/edit": PencilIcon,
"/clear": TrashIcon,
"/comment": HashtagIcon,
"/share": ArrowUpOnSquareIcon,
"/cmd": CommandLineIcon,
};
@ -177,6 +177,8 @@ interface MentionListProps {
const MentionList = forwardRef((props: MentionListProps, ref) => {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const [selectedIndex, setSelectedIndex] = useState(0);
const [subMenuTitle, setSubMenuTitle] = useState<string | undefined>(
@ -208,6 +210,24 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
},
description: "Add a new documentation source",
});
} else if (subMenuTitle === ".prompt files") {
items.push({
title: "New .prompt file",
type: "action",
action: () => {
ideMessenger.request("config/newPromptFile", undefined);
const { tr } = props.editor.view.state;
const text = tr.doc.textBetween(0, tr.selection.from);
const start = text.lastIndexOf("@");
if (start !== -1) {
props.editor.view.dispatch(
tr.delete(start, tr.selection.from).scrollIntoView(),
);
}
props.onClose(); // Escape the mention list after creating a new prompt file
},
description: "Create a new .prompt file",
});
}
setAllItems(items);
@ -375,7 +395,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
onClick={() => selectItem(index)}
onMouseEnter={() => setSelectedIndex(index)}
>
<span className="flex justify-between w-full items-center">
<span className="flex w-full items-center justify-between">
<div className="flex items-center justify-center">
{showFileIconForItem(item) && (
<FileIcon
@ -400,7 +420,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
opacity: index !== selectedIndex ? 0 : 1,
minWidth: "30px",
}}
className="whitespace-nowrap overflow-hidden overflow-ellipsis ml-2 flex items-center"
className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap"
>
{item.description}
{item.type === "contextProvider" &&

View file

@ -44,7 +44,6 @@ import useUpdatingRef from "../../hooks/useUpdatingRef";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { selectUseActiveFile } from "../../redux/selectors";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice";
import { RootState } from "../../redux/store";
import {
getFontSize,
@ -508,29 +507,6 @@ function TipTapEditor(props: TipTapEditorProps) {
if (!codeBlock) {
return;
}
// Search for slashcommand type
for (const p of json.content) {
if (
p.type !== "paragraph" ||
!p.content ||
typeof p.content === "string"
) {
continue;
}
for (const node of p.content) {
if (
node.type === "slashcommand" &&
["/edit", "/comment"].includes(node.attrs.label)
) {
// Update context items
dispatch(
setEditingContextItemAtIndex({ item: codeBlock.attrs.item }),
);
return;
}
}
}
},
editable: !active || props.isMainInput,
});

View file

@ -189,18 +189,17 @@ export function getSlashCommandDropdownOptions(
const items = async ({ query }: { query: string }) => {
const options = [
...availableSlashCommandsRef.current,
{
title: "Build a custom prompt",
description: "Build a custom prompt",
type: "action",
id: "createPromptFile",
label: "Create Prompt File",
action: () => {
console.log("I", ideMessenger.request);
ideMessenger.request("config/newPromptFile", undefined);
},
name: "Create Prompt File",
},
// {
// title: "Build a custom prompt",
// description: "Build a custom prompt",
// type: "action",
// id: "createPromptFile",
// label: "Create Prompt File",
// action: () => {
// ideMessenger.request("config/newPromptFile", undefined);
// },
// name: "Create Prompt File",
// },
];
return (
options.filter((slashCommand) => {

View file

@ -1,7 +1,6 @@
import {
ChevronDownIcon,
ChevronUpIcon,
PencilIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
@ -36,7 +35,7 @@ const PreviewMarkdownHeader = styled.div`
padding: 2px 6px;
border-bottom: 0.5px solid ${lightGray};
word-break: break-all;
font-size: ${getFontSize() - 2}px;
font-size: ${getFontSize() - 3}px;
display: flex;
align-items: center;
`;
@ -44,17 +43,9 @@ const PreviewMarkdownHeader = styled.div`
interface CodeSnippetPreviewProps {
item: ContextItemWithId;
onDelete?: () => void;
onEdit?: () => void;
borderColor?: string;
editing?: boolean;
}
const StyledHeaderButtonWithText = styled(ButtonWithTooltip) <{
color?: string;
}>`
${(props) => props.color && `background-color: ${props.color};`}
`;
const MAX_PREVIEW_HEIGHT = 300;
// Pre-compile the regular expression outside of the function
@ -84,7 +75,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
className="find-widget-skip"
>
<PreviewMarkdownHeader
className="flex justify-between cursor-pointer"
className="flex cursor-pointer justify-between"
onClick={() => {
if (props.item.id.providerTitle === "file") {
ideMessenger.post("showFile", {
@ -109,23 +100,10 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
}}
>
<div className="flex items-center gap-1">
<FileIcon height="20px" width="20px" filename={props.item.name} />
<FileIcon height="16px" width="16px" filename={props.item.name} />
{props.item.name}
</div>
<div className="flex items-center gap-1">
{props.onEdit && (
<StyledHeaderButtonWithText
text="Edit"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
props.onEdit?.();
}}
{...(props.editing && { color: "#f0f4" })}
>
<PencilIcon width="1.1em" height="1.1em" />
</StyledHeaderButtonWithText>
)}
<ButtonWithTooltip
text="Delete"
onClick={(e) => {
@ -133,7 +111,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
props.onDelete?.();
}}
>
<XMarkIcon width="1.1em" height="1.1em" />
<XMarkIcon width="1em" height="1em" />
</ButtonWithTooltip>
</div>
</PreviewMarkdownHeader>
@ -152,7 +130,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
{(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && (
<ButtonWithTooltip
className="bottom-1 right-2 absolute"
className="absolute bottom-1 right-2"
text={collapsed ? "Expand" : "Collapse"}
>
<ChevronDownIcon

View file

@ -64,7 +64,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
saveSession(false);
}, [save]);
useEffect(() => {
activeRef.current = active;
}, [active]);
@ -219,7 +218,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
const currentFile = await ideMessenger.ide.getCurrentFile();
if (currentFile) {
let currentFileContents = currentFile.contents
let currentFileContents = currentFile.contents;
if (usingFreeTrial) {
currentFileContents = currentFile.contents
.split("\n")
@ -292,13 +291,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
params: {},
});
// For edit and comment slash commands, including the selected code in the context from store and for other commands, including the selected context alone
if (slashCommand.name === "edit" || slashCommand.name === "comment") {
updatedContextItems = [...contextItems];
} else {
updatedContextItems = [...selectedContextItems];
}
await _streamSlashCommand(
messages,
slashCommand,

View file

@ -1,6 +1,6 @@
import HistoryPage from "./index";
import { renderWithProviders } from "../../util/test/render";
import { screen } from "@testing-library/dom";
import { renderWithProviders } from "../../util/test/render";
import HistoryPage from "./index";
const navigateFn = vi.fn();
@ -15,6 +15,8 @@ vi.mock("react-router-dom", async () => {
describe("history Page test", () => {
it("History text is existed after render", () => {
renderWithProviders(<HistoryPage />);
expect(screen.getByText("History")).toBeInTheDocument();
expect(
screen.getByText("All session data is saved in ~/.continue/sessions"),
).toBeInTheDocument();
});
});

View file

@ -1,7 +1,6 @@
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/react";
import {
ChatHistory,
ChatHistoryItem,
ChatMessage,
ContextItemId,
@ -10,12 +9,11 @@ import {
PromptLog,
} from "core";
import { BrowserSerializedContinueConfig } from "core/config/load";
import { ConfigValidationError } from "core/config/validation";
import { stripImages } from "core/llm/images";
import { createSelector } from "reselect";
import { v4 } from "uuid";
import { v4 as uuidv4, v4 } from "uuid";
import { RootState } from "../store";
import { v4 as uuidv4 } from "uuid";
import { ConfigValidationError } from "core/config/validation";
export const memoizedContextItemsSelector = createSelector(
[(state: RootState) => state.state.history],
@ -57,14 +55,6 @@ const initialState: State = {
configError: undefined,
config: {
slashCommands: [
{
name: "edit",
description: "Edit selected code",
},
{
name: "comment",
description: "Write comments for the selected code",
},
{
name: "share",
description: "Export the current chat session to markdown",
@ -151,23 +141,6 @@ export const stateSlice = createSlice({
state.history[index].contextItems = contextItems;
}
},
setEditingContextItemAtIndex: (
state,
{
payload: { index, item },
}: PayloadAction<{ index?: number; item: ContextItemWithId }>,
) => {
if (index === undefined) {
const isFirstContextItem =
state.contextItems[0]?.id.itemId === item.id.itemId;
state.contextItems = isFirstContextItem
? []
: [{ ...item, editing: true }];
return;
}
// TODO
},
addContextItems: (state, action: PayloadAction<ContextItemWithId[]>) => {
state.contextItems = state.contextItems.concat(action.payload);
},
@ -462,7 +435,6 @@ export const {
addPromptCompletionPair,
setTTSActive,
setActive,
setEditingContextItemAtIndex,
initNewActiveMessage,
setMessageAtIndex,
clearLastResponse,

View file

@ -11,6 +11,7 @@ export const completionOptionsSchema = z.object({
stop: z.array(z.string()).optional(),
maxTokens: z.number().optional(),
numThreads: z.number().optional(),
useMmap: z.boolean().optional(),
keepAlive: z.number().optional(),
raw: z.boolean().optional(),
stream: z.boolean().optional(),