merge dev

This commit is contained in:
Dallin Romney 2024-11-07 01:19:09 -08:00
commit ba4d740473
118 changed files with 3013 additions and 1992 deletions

View file

@ -0,0 +1,4 @@
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

@ -0,0 +1,4 @@
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

@ -16,3 +16,9 @@ jobs:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen
numOfAssignee: 1
- name: "Add default labels"
uses: actions-ecosystem/action-add-labels@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
labels: |
"needs-triage"

View file

@ -2,5 +2,8 @@
"tabWidth": 2,
"useTabs": false,
"trailingComma": "all",
"semi": true,
"singleQuote": false,
"bracketSpacing": true,
"plugins": ["prettier-plugin-tailwindcss"]
}

View file

@ -1,19 +0,0 @@
temperature: 0.5
maxTokens: 4096
name: jest
description: Write Jest unit tests
---
<system>
You are an expert programmer
</system>
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:
- Use `jest`
- Properly set up and tear down
- Include important edge cases
- The tests should be complete and sophisticated
- Give the tests just as chat output, don't edit any file
- Don't explain how to set up `jest`
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")

25
.vscode/settings.json vendored
View file

@ -14,11 +14,26 @@
}
},
"search.exclude": {
"**/core/vendor/**": true,
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,
"**/extensions/vscode/out/**": true,
"**/extensions/intellij/build/**": true
"**/package-lock.json": true,
"binary/bin/**": true,
"binary/build/**": true,
"binary/out/**": true,
"binary/tmp/**": true,
"core/llm/llamaTokenizer.js": true,
"core/llm/llamaTokenizer.mjs": true,
"core/vendor/**": true,
"docs/.docusaurus/**": true,
"extensions/intellij/build/**": true,
"extensions/vscode/bin/**": true,
"extensions/vscode/build/**": true,
"extensions/vscode/gui/**": true,
"extensions/vscode/models/all-MiniLM-L6-v2/**": true,
"extensions/vscode/out/**": true,
"extensions/vscode/tag-qry/**": true,
"extensions/vscode/textmate-syntaxes/**": true,
"extensions/vscode/tree-sitter/**": true,
"gui/dist/**": true
// "sync/**": true
},
"eslint.workingDirectories": ["./core"]
}

11
.vscode/tasks.json vendored
View file

@ -5,11 +5,11 @@
{
"label": "vscode-extension:build",
"dependsOn": [
// To detect compile errors and output extensions.js
// To detect compile errors
"vscode-extension:tsc",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
// To bundle the code the same way we do for publishing
// // To bundle the code the same way we do for publishing
"vscode-extension:esbuild",
// Start the React app that is used in the extension
"gui:dev"
@ -21,10 +21,7 @@
},
{
"label": "vscode-extension:esbuild",
"dependsOn": [
"vscode-extension:continue-ui:build",
"vscode-extension:tsc"
],
"dependsOn": ["vscode-extension:continue-ui:build"],
"type": "npm",
"script": "esbuild-watch",
"path": "extensions/vscode",
@ -44,7 +41,7 @@
"background": {
"activeOnStart": true,
"beginsPattern": ">",
"endsPattern": ">"
"endsPattern": "VS Code Extension esbuild complete"
}
}
]

View file

@ -10,13 +10,11 @@ export async function fullTextRetrieve(
const searchStrings = prefix.split("\n").slice(-3);
const results: Chunk[] = [];
searchStrings.forEach(async (searchString) => {
const chunks = await index.retrieve(
[indexTag],
searchString,
3,
undefined,
undefined,
);
const chunks = await index.retrieve({
tags: [indexTag],
text: searchString,
n: 3,
});
results.push(...chunks);
});
return results;

View file

@ -4,9 +4,10 @@ import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import EditSlashCommand from "./edit";
import HttpSlashCommand from "./http";
import MultiFileEditSlashCommand from "./multifileEdit";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
import OnboardSlashCommand from "./onboard";
export default [
DraftIssueCommand,
@ -18,4 +19,5 @@ export default [
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
MultiFileEditSlashCommand,
];

View file

@ -0,0 +1,108 @@
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 = {
name: "multifile-edit",
description: "Edit multiple files in the codebase at once",
run: async function* ({ llm, contextItems, selectedCode, input, ide }) {
const selectedCodeStr = (
await Promise.all(
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);
if (!fullPath) {
return "";
}
const codeStr = await ide.readRangeInFile(fullPath, item.range);
// Include the filepath so the model can map it correctly with codeblock outputs
return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``;
}),
)
).join("\n");
const fileContextItemsStr = contextItems
.filter((item) => item.uri?.type === "file")
.map((item) => item.content)
.join("\n");
const filesToEditStr = fileContextItemsStr + "\n" + selectedCodeStr;
const additionalContextStr = contextItems
.filter((item) => item.uri?.type !== "file")
.map((item) => `${item.description}: ${item.content}`)
.join("\n");
const content = createPrompt(filesToEditStr, additionalContextStr, input);
for await (const chunk of llm.streamChat([{ role: "user", content }])) {
yield stripImages(chunk.content);
}
},
};
function createPrompt(
filesToEditStr: string,
additionalContextStr: string,
input: string,
): string {
return `
You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines:
1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!"
2. When providing instructions, if a user needs to interact with a CLI, walk them through each step
2. Perform file edits in a logical, sequential ordering
3. For each file edit, provide a brief explanation of the changes
4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
a. When creating new files, also inlcude the filname in the language specifier of the code block.
6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits
Remember to be concise and focus on the code changes and their impact.
Here's an example of how your response should be structured:
<example>
I'll make the following changes to implement feature X:
1. First, I'll modify file1.js to add a new function:
\`\`\`javascript /path/to/file1.js
// Entire content of file1.js or changes to be made
\`\`\`
2. Next, let's create a new test file:
\`\`\`javascript /path/to/file1.test.js
# Entire content of file2.py or changes to be made
\`\`\`
Summary:
- [Sequential overview of the most important 3-5 edits]
</example>
Now, let's make the changes based on the engineer's request:
<input>
${input}
</input>
Here are the files to base your edits on:
<files>
${filesToEditStr}
</files>
And here is any additional context the engineer has provided:
<context>
${additionalContextStr}
</context>
Please provide the multi-file edit details based on the engineer's request.
`;
}
export default MultiFileEditSlashCommand;

View file

@ -6,7 +6,7 @@ import {
} from "../";
export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = {
model: "claude-3-5-sonnet-20240620",
model: "claude-3-5-sonnet-latest",
provider: "anthropic",
apiKey: "",
title: "Claude 3.5 Sonnet",
@ -23,7 +23,7 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3.5 Sonnet (Free Trial)",
provider: "free-trial",
model: "claude-3-5-sonnet-20240620",
model: "claude-3-5-sonnet-latest",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},

View file

@ -648,6 +648,7 @@ declare global {
| "gemma-7b-it"
| "gemma2-9b-it"
// Anthropic
| "claude-3-5-sonnet-latest"
| "claude-3-5-sonnet-20240620"
| "claude-3-opus-20240229"
| "claude-3-sonnet-20240229"

View file

@ -17,7 +17,7 @@ class DiffContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const diff = await extras.ide.getDiff(false);
const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true);
return [
{
description: "The current git diff",

View file

@ -156,12 +156,17 @@ export class JiraClient {
},
);
if (response.status !== 200) {
if (response.status === 500) {
const text = await response.text();
console.warn(
"Unable to get jira tickets. Response code from API is",
response.status,
"Unable to get Jira tickets. You may need to set 'apiVersion': 2 in your config.json. See full documentation here: https://docs.continue.dev/customize/context-providers#jira-datacenter-support\n\n",
text,
);
return Promise.resolve([]);
} else if (response.status !== 200) {
const text = await response.text();
console.warn("Unable to get Jira tickets: ", text);
return Promise.resolve([]);
}
const data = (await response.json()) as any;

View file

@ -15,6 +15,7 @@ export class HuggingFaceTEIReranker implements Reranker {
apiBase?: string;
truncate?: boolean;
truncation_direction?: string;
apiKey?: string;
},
) {}
@ -24,9 +25,17 @@ export class HuggingFaceTEIReranker implements Reranker {
apiBase += "/";
}
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.params.apiKey) {
headers["Authorization"] = `Bearer ${this.params.apiKey}`;
}
const resp = await fetch(new URL("rerank", apiBase), {
method: "POST",
headers: { "Content-Type": "application/json" },
headers,
body: JSON.stringify({
query: query,
return_text: false,

View file

@ -1,32 +0,0 @@
import { BranchAndDir, Chunk } from "../../index.js";
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js";
export async function retrieveFts(
query: string,
n: number,
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const ftsIndex = new FullTextSearchCodebaseIndex();
let ftsResults: Chunk[] = [];
try {
if (query.trim() !== "") {
ftsResults = await ftsIndex.retrieve(
tags,
query
.trim()
.split(" ")
.map((element) => `"${element}"`)
.join(" OR "),
n,
filterDirectory,
undefined,
);
}
return ftsResults;
} catch (e) {
console.warn("Error retrieving from FTS:", e);
return [];
}
}

View file

@ -1,14 +1,11 @@
import {
BranchAndDir,
Chunk,
ContinueConfig,
IDE,
ILLM,
} from "../../../index.js";
import { chunkDocument } from "../../../indexing/chunk/chunk.js";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js";
import { retrieveFts } from "../fullTextSearch.js";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
// @ts-ignore
import nlp from "wink-nlp-utils";
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
import { chunkDocument } from "../../../indexing/chunk/chunk";
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
export interface RetrievalPipelineOptions {
llm: ILLM;
@ -23,11 +20,18 @@ export interface RetrievalPipelineOptions {
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface RetrievalPipelineRunArguments {
query: string;
tags: BranchAndDir[];
filterDirectory?: string;
}
export interface IRetrievalPipeline {
run(options: RetrievalPipelineOptions): Promise<Chunk[]>;
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]>;
}
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex;
constructor(protected readonly options: RetrievalPipelineOptions) {
@ -38,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
private getCleanedTrigrams(
query: RetrievalPipelineRunArguments["query"],
): string[] {
let text = nlp.string.removeExtraSpaces(query);
text = nlp.string.stem(text);
let tokens = nlp.string
.tokenize(text, true)
.filter((token: any) => token.tag === "word")
.map((token: any) => token.value);
tokens = nlp.tokens.removeWords(tokens);
tokens = nlp.tokens.setOfWords(tokens);
const cleanedTokens = [...tokens].join(" ");
const trigrams = nlp.string.ngram(cleanedTokens, 3);
return trigrams;
}
protected async retrieveFts(
args: RetrievalPipelineRunArguments,
n: number,
): Promise<Chunk[]> {
try {
if (args.query.trim() === "") {
return [];
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
return await this.ftsIndex.retrieve({
n,
text: tokens,
tags: args.tags,
directory: args.filterDirectory,
});
} catch (e) {
console.warn("Error retrieving from FTS:", e);
return [];
}
}
protected async retrieveAndChunkRecentlyEditedFiles(
n: number,
): Promise<Chunk[]> {
@ -75,15 +122,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return chunks.slice(0, n);
}
protected async retrieveFts(input: string, n: number): Promise<Chunk[]> {
return retrieveFts(
input,
n,
this.options.tags,
this.options.filterDirectory,
);
}
protected async retrieveEmbeddings(
input: string,
n: number,
@ -96,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
run(): Promise<Chunk[]> {
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
throw new Error("Not implemented");
}
}

View file

@ -1,10 +1,13 @@
import { Chunk } from "../../../index.js";
import { requestFilesFromRepoMap } from "../repoMapRequest.js";
import { deduplicateChunks } from "../util.js";
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
import { Chunk } from "../../../";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
import BaseRetrievalPipeline, {
RetrievalPipelineRunArguments,
} from "./BaseRetrievalPipeline";
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(): Promise<Chunk[]> {
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
@ -15,7 +18,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(input, ftsNFinal);
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, embeddingsNFinal)

View file

@ -1,17 +1,22 @@
import { Chunk } from "../../../index.js";
import { RETRIEVAL_PARAMS } from "../../../util/parameters.js";
import { requestFilesFromRepoMap } from "../repoMapRequest.js";
import { deduplicateChunks } from "../util.js";
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
import BaseRetrievalPipeline, {
RetrievalPipelineRunArguments,
} from "./BaseRetrievalPipeline";
export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(): Promise<Chunk[]> {
private async _retrieveInitial(
args: RetrievalPipelineRunArguments,
): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(input, nRetrieve);
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
@ -104,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
return results;
}
async run(): Promise<Chunk[]> {
const intialResults = await this._retrieveInitial();
const rankedResults = await this._rerank(this.options.input, intialResults);
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
let results = await this._retrieveInitial(args);
results = await this._rerank(args.query, results);
// // // Expand top reranked results
// const expanded = await this._expandRankedResults(results);
@ -120,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
// TODO: stitch together results
return rankedResults;
return results;
}
}

View file

@ -93,7 +93,11 @@ export async function retrieveContextItemsFromEmbeddings(
};
const pipeline = new pipelineType(pipelineOptions);
const results = await pipeline.run();
const results = await pipeline.run({
tags,
filterDirectory,
query: extras.fullInput,
});
if (results.length === 0) {
throw new Error(

View file

@ -29,6 +29,9 @@ import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import ignore from "ignore";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import path from "path";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -704,8 +707,13 @@ export class Core {
return { url };
});
on("didChangeActiveTextEditor", ({ data: { filepath } }) => {
recentlyEditedFilesCache.set(filepath, filepath);
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
const ignoreInstance = ignore().add(defaultIgnoreFile);
let rootDirectory = await this.ide.getWorkspaceDirs();
const relativeFilePath = path.relative(rootDirectory[0], filepath);
if (!ignoreInstance.ignores(relativeFilePath)) {
recentlyEditedFilesCache.set(filepath, filepath);
}
});
}

18
core/index.d.ts vendored
View file

@ -48,9 +48,9 @@ export interface IndexingProgressUpdate {
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
export interface ILLM extends LLMOptions {
get providerName(): ModelProvider;
@ -646,7 +646,8 @@ type ModelProvider =
| "cerebras"
| "askSage"
| "vertexai"
| "nebius";
| "nebius"
| "xAI";
export type ModelName =
| "AUTODETECT"
@ -696,6 +697,8 @@ export type ModelName =
| "llama3.2-3b"
| "llama3.2-11b"
| "llama3.2-90b"
// xAI
| "grok-beta"
// Other Open-source
| "phi2"
| "phind-codellama-34b"
@ -710,6 +713,7 @@ export type ModelName =
| "gemma-7b-it"
| "gemma2-9b-it"
// Anthropic
| "claude-3-5-sonnet-latest"
| "claude-3-5-sonnet-20240620"
| "claude-3-opus-20240229"
| "claude-3-sonnet-20240229"
@ -1053,9 +1057,9 @@ export interface Config {
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */

View file

@ -1,6 +1,7 @@
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
import { getBasename } from "../util/index";
import { RETRIEVAL_PARAMS } from "../util/parameters";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
@ -10,10 +11,20 @@ import {
type CodebaseIndex,
} from "./types";
export interface RetrieveConfig {
tags: BranchAndDir[];
text: string;
n: number;
directory?: string;
filterPaths?: string[];
bm25Threshold?: number;
}
export class FullTextSearchCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 0.2;
static artifactId = "sqliteFts";
artifactId: string = FullTextSearchCodebaseIndex.artifactId;
pathWeightMultiplier = 10.0;
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
desc: `Indexing ${getBasename(item.path)}`,
status: "indexing",
};
markComplete([item], IndexResultType.Compute);
await markComplete([item], IndexResultType.Compute);
}
// Add tag
for (const item of results.addTag) {
markComplete([item], IndexResultType.AddTag);
await markComplete([item], IndexResultType.AddTag);
}
// Remove tag
for (const item of results.removeTag) {
markComplete([item], IndexResultType.RemoveTag);
await markComplete([item], IndexResultType.RemoveTag);
}
// Delete
@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
markComplete([item], IndexResultType.Delete);
await markComplete([item], IndexResultType.Delete);
}
}
async retrieve(
tags: BranchAndDir[],
text: string,
n: number,
directory: string | undefined,
filterPaths: string[] | undefined,
bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold,
): Promise<Chunk[]> {
async retrieve(config: RetrieveConfig): Promise<Chunk[]> {
const db = await SqliteDb.get();
// Notice that the "chunks" artifactId is used because of linking between tables
const tagStrings = tags.map((tag) => {
return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId });
});
const query = this.buildRetrieveQuery(config);
const parameters = this.getRetrieveQueryParameters(config);
const query = `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank
FROM fts
JOIN fts_metadata ON fts.rowid = fts_metadata.id
JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId
WHERE fts MATCH '${text.replace(
/\?/g,
"",
)}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})
${
filterPaths
? `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`
: ""
}
ORDER BY rank
LIMIT ?`;
let results = await db.all(query, parameters);
let results = await db.all(query, [
...tagStrings,
...(filterPaths || []),
Math.ceil(n),
]);
results = results.filter((result) => result.rank <= bm25Threshold);
results = results.filter(
(result) =>
result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold),
);
const chunks = await db.all(
`SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`,
results.map((result) => result.chunkId),
);
return chunks.map((chunk) => {
return {
filepath: chunk.path,
index: chunk.index,
startLine: chunk.startLine,
endLine: chunk.endLine,
content: chunk.content,
digest: chunk.cacheKey,
};
});
return chunks.map((chunk) => ({
filepath: chunk.path,
index: chunk.index,
startLine: chunk.startLine,
endLine: chunk.endLine,
content: chunk.content,
digest: chunk.cacheKey,
}));
}
private buildTagFilter(tags: BranchAndDir[]): string {
const tagStrings = this.convertTags(tags);
return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`;
}
private buildPathFilter(filterPaths: string[] | undefined): string {
if (!filterPaths || filterPaths.length === 0) {
return "";
}
return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`;
}
private buildRetrieveQuery(config: RetrieveConfig): string {
return `
SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank
FROM fts
JOIN fts_metadata ON fts.rowid = fts_metadata.id
JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId
WHERE fts MATCH ?
${this.buildTagFilter(config.tags)}
${this.buildPathFilter(config.filterPaths)}
ORDER BY bm25(fts, ${this.pathWeightMultiplier})
LIMIT ?
`;
}
private getRetrieveQueryParameters(config: RetrieveConfig) {
const { text, tags, filterPaths, n } = config;
const tagStrings = this.convertTags(tags);
return [
text.replace(/\?/g, ""),
...tagStrings,
...(filterPaths || []),
Math.ceil(n),
];
}
private convertTags(tags: BranchAndDir[]): string[] {
// Notice that the "chunks" artifactId is used because of linking between tables
return tags.map((tag) =>
tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }),
);
}
}

View file

@ -1,18 +1,11 @@
import { Octokit } from "@octokit/rest";
import * as cheerio from "cheerio";
import * as fs from "fs";
import fetch from "node-fetch";
import { URL } from "node:url";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
} from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../..";
import CheerioCrawler from "./crawlers/CheerioCrawler";
import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler";
import { DefaultCrawler } from "./crawlers/DefaultCrawler";
import GitHubCrawler from "./crawlers/GitHubCrawler";
export type PageData = {
url: string;
@ -42,10 +35,23 @@ class DocsCrawler {
async *crawl(
startUrl: URL,
maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
): AsyncGenerator<PageData> {
): AsyncGenerator<PageData, undefined, undefined> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
} else if (this.shouldUseChromium()) {
return;
}
try {
const pageData = await new DefaultCrawler(startUrl).crawl();
if (pageData.length > 0) {
yield* pageData;
return;
}
} catch (e) {
console.error("Default crawler failed, trying backup: ", e);
}
if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
let didCrawlSinglePage = false;
@ -83,471 +89,6 @@ class DocsCrawler {
}
}
class GitHubCrawler {
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
private octokit = new Octokit({ auth: undefined });
constructor(private readonly startUrl: URL) {}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${
(this.constructor as any).name
}] Crawling GitHub repo: ${this.startUrl.toString()}`,
);
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
yield { path, url: urlStr, content: content ?? "" };
}
}
private async getGithubRepoDefaultBranch(
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await this.octokit.repos.get({ owner, repo });
return repoInfo.data.default_branch;
}
private async getGitHubRepoPaths(
owner: string,
repo: string,
branch: string,
) {
const tree = await this.octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: { "X-GitHub-Api-Version": "2022-11-28" },
recursive: "true",
},
);
return tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
}
private async getGithubRepoFileContent(
path: string,
owner: string,
repo: string,
) {
try {
const response = await this.octokit.repos.getContent({
owner,
repo,
path,
headers: { Accept: "application/vnd.github.raw+json" },
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
}
class CheerioCrawler {
private readonly IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
async *crawl(): AsyncGenerator<PageData> {
yield* this.crawlPage(this.startUrl);
}
private async *crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`[${
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
];
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
try {
const promises = batch.map(({ path, depth }) =>
this.getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
);
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
yield { url: url.toString(), path, content: html };
}
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 });
}
}
}
}
} catch (e) {
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
private async getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (
error instanceof Error &&
error.message.includes("maximum redirect")
) {
console.error(
`[${
(this.constructor as any).name
}] Maximum redirect reached for: ${location.toString()}`,
);
return { html: "", links: [] };
}
console.error(error);
return { html: "", links: [] };
}
if (!response.ok) {
return { html: "", links: [] };
}
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return { html, links };
}
const $ = cheerio.load(html);
$("a").each((_: any, element: any) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, location);
if (parsedUrl.hostname === baseUrl.hostname) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return { html, links };
}
private splitUrl(url: URL) {
const baseUrl = new URL('/', url).href;
const basePath = url.pathname;
return { baseUrl, basePath };
}
}
class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
private curCrawlCount = 0;
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
);
const stats = await PCR(ChromiumInstaller.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
],
executablePath: stats.executablePath,
});
const page = await browser.newPage();
try {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
} finally {
await browser.close();
}
}
/**
* We need to handle redirects manually, otherwise there are race conditions.
*
* https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
*/
private async gotoPageAndHandleRedirects(page: Page, url: string) {
const MAX_PAGE_WAIT_MS = 5000;
await page.goto(url, {
timeout: 0,
waitUntil: "networkidle2",
});
let responseEventOccurred = false;
const responseHandler: Handler<HTTPResponse> = (event) =>
(responseEventOccurred = true);
const responseWatcher = new Promise<void>(function (resolve, reject) {
setTimeout(() => {
if (!responseEventOccurred) {
resolve();
} else {
setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
}
}, 500);
});
page.on("response", responseHandler);
await Promise.race([responseWatcher, page.waitForNavigation()]);
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
): AsyncGenerator<PageData> {
const urlStr = curUrl.toString();
if (visitedLinks.has(urlStr)) {
return;
}
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
this.curCrawlCount++;
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: urlStr,
content: htmlContent,
};
for (const linkGroup of linkGroups) {
let enqueuedLinkCount = this.curCrawlCount;
for (const link of linkGroup) {
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
}
}
}
private stripHashFromUrl(urlStr: string) {
try {
let url = new URL(urlStr);
url.hash = "";
return url;
} catch (err) {
return null;
}
}
private isValidHostAndPath(newUrl: URL, curUrl: URL) {
return (
newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host
);
}
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
(newUrl) =>
newUrl !== null &&
this.isValidHostAndPath(newUrl, curUrl) &&
newUrl !== curUrl,
)
.map((newUrl) => (newUrl as URL).href);
const dedupedLinks = Array.from(new Set(cleanedLinks));
return dedupedLinks;
}
private async getLinkGroupsFromPage(page: Page, curUrl: URL) {
const links = await this.getLinksFromPage(page, curUrl);
const groups = links.reduce((acc, link, i) => {
const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE);
if (!acc[groupIndex]) {
acc.push([]);
}
acc[groupIndex].push(link);
return acc;
}, [] as string[][]);
return groups;
}
}
class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
void this.install();
}
}
isInstalled() {
return fs.existsSync(getChromiumPath());
}
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
shouldProposeUseChromiumOnCrawlFailure() {
const { experimental } = this.config;
return (
experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling
);
}
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
async install() {
try {
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
await this.ide.showToast("error", "Failed to install Chromium");
return false;
}
}
private async proposeInstall(site: string) {
const msg =
`Unable to crawl documentation site: ${site}\n` +
"We recommend installing Chromium. " +
"Download progress can be viewed in the developer console.";
const actionMsg = "Install Chromium";
const res = await this.ide.showToast("warning", msg, actionMsg);
return res === actionMsg;
}
}
export default DocsCrawler;
export {
CheerioCrawler,

View file

@ -404,12 +404,15 @@ export default class DocsService {
async getFavicon(startUrl: string) {
const db = await this.getOrCreateSqliteDb();
const { favicon } = await db.get(
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
startUrl,
);
return favicon;
if (!result) {
return;
}
return result.favicon;
}
private async init(configHandler: ConfigHandler) {

View file

@ -0,0 +1,146 @@
import * as cheerio from "cheerio";
import { URL } from "node:url";
import { PageData } from "../DocsCrawler";
export default class CheerioCrawler {
private readonly IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
async *crawl(): AsyncGenerator<PageData> {
yield* this.crawlPage(this.startUrl);
}
private async *crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`[${
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
];
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
try {
const promises = batch.map(({ path, depth }) =>
this.getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
);
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
yield { url: url.toString(), path, content: html };
}
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 });
}
}
}
}
} catch (e) {
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
private async getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (
error instanceof Error &&
error.message.includes("maximum redirect")
) {
console.error(
`[${
(this.constructor as any).name
}] Maximum redirect reached for: ${location.toString()}`,
);
return { html: "", links: [] };
}
console.error(error);
return { html: "", links: [] };
}
if (!response.ok) {
return { html: "", links: [] };
}
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return { html, links };
}
const $ = cheerio.load(html);
$("a").each((_: any, element: any) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, location);
if (parsedUrl.hostname === baseUrl.hostname) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return { html, links };
}
private splitUrl(url: URL) {
const baseUrl = new URL("/", url).href;
const basePath = url.pathname;
return { baseUrl, basePath };
}
}

View file

@ -0,0 +1,260 @@
import * as fs from "fs";
import { URL } from "node:url";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
} from "../../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../../..";
import { PageData } from "../DocsCrawler";
export class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
private curCrawlCount = 0;
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
);
const stats = await PCR(ChromiumInstaller.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
],
executablePath: stats.executablePath,
});
const page = await browser.newPage();
try {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
} finally {
await browser.close();
}
}
/**
* We need to handle redirects manually, otherwise there are race conditions.
*
* https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
*/
private async gotoPageAndHandleRedirects(page: Page, url: string) {
const MAX_PAGE_WAIT_MS = 5000;
await page.goto(url, {
timeout: 0,
waitUntil: "networkidle2",
});
let responseEventOccurred = false;
const responseHandler: Handler<HTTPResponse> = (event) =>
(responseEventOccurred = true);
const responseWatcher = new Promise<void>(function (resolve, reject) {
setTimeout(() => {
if (!responseEventOccurred) {
resolve();
} else {
setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
}
}, 500);
});
page.on("response", responseHandler);
await Promise.race([responseWatcher, page.waitForNavigation()]);
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
): AsyncGenerator<PageData> {
const urlStr = curUrl.toString();
if (visitedLinks.has(urlStr)) {
return;
}
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
this.curCrawlCount++;
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: urlStr,
content: htmlContent,
};
for (const linkGroup of linkGroups) {
let enqueuedLinkCount = this.curCrawlCount;
for (const link of linkGroup) {
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
}
}
}
private stripHashFromUrl(urlStr: string) {
try {
let url = new URL(urlStr);
url.hash = "";
return url;
} catch (err) {
return null;
}
}
private isValidHostAndPath(newUrl: URL, curUrl: URL) {
return (
newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host
);
}
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
(newUrl) =>
newUrl !== null &&
this.isValidHostAndPath(newUrl, curUrl) &&
newUrl !== curUrl,
)
.map((newUrl) => (newUrl as URL).href);
const dedupedLinks = Array.from(new Set(cleanedLinks));
return dedupedLinks;
}
private async getLinkGroupsFromPage(page: Page, curUrl: URL) {
const links = await this.getLinksFromPage(page, curUrl);
const groups = links.reduce((acc, link, i) => {
const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE);
if (!acc[groupIndex]) {
acc.push([]);
}
acc[groupIndex].push(link);
return acc;
}, [] as string[][]);
return groups;
}
}
export class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
void this.install();
}
}
isInstalled() {
return fs.existsSync(getChromiumPath());
}
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
shouldProposeUseChromiumOnCrawlFailure() {
const { experimental } = this.config;
return (
experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling
);
}
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
async install() {
try {
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
await this.ide.showToast("error", "Failed to install Chromium");
return false;
}
}
private async proposeInstall(site: string) {
const msg =
`Unable to crawl documentation site: ${site}\n` +
"We recommend installing Chromium. " +
"Download progress can be viewed in the developer console.";
const actionMsg = "Install Chromium";
const res = await this.ide.showToast("warning", msg, actionMsg);
return res === actionMsg;
}
}

View file

@ -0,0 +1,25 @@
import { URL } from "node:url";
import { getHeaders } from "../../../continueServer/stubs/headers";
import { TRIAL_PROXY_URL } from "../../../control-plane/client";
import { PageData } from "../DocsCrawler";
export class DefaultCrawler {
constructor(private readonly startUrl: URL) {}
async crawl(): Promise<PageData[]> {
const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
...(await getHeaders()),
},
body: JSON.stringify({ startUrl: this.startUrl.toString() }),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`Failed to crawl site: ${text}`);
}
const json = (await resp.json()) as PageData[];
return json;
}
}

View file

@ -0,0 +1,80 @@
import { Octokit } from "@octokit/rest";
import { URL } from "node:url";
import { PageData } from "../DocsCrawler";
class GitHubCrawler {
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
private octokit = new Octokit({ auth: undefined });
constructor(private readonly startUrl: URL) {}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${
(this.constructor as any).name
}] Crawling GitHub repo: ${this.startUrl.toString()}`,
);
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
yield { path, url: urlStr, content: content ?? "" };
}
}
private async getGithubRepoDefaultBranch(
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await this.octokit.repos.get({ owner, repo });
return repoInfo.data.default_branch;
}
private async getGitHubRepoPaths(
owner: string,
repo: string,
branch: string,
) {
const tree = await this.octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: { "X-GitHub-Api-Version": "2022-11-28" },
recursive: "true",
},
);
return tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
}
private async getGithubRepoFileContent(
path: string,
owner: string,
repo: string,
) {
try {
const response = await this.octokit.repos.getContent({
owner,
repo,
path,
headers: { Accept: "application/vnd.github.raw+json" },
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
}
export default GitHubCrawler;

View file

@ -299,30 +299,32 @@ const preIndexedDocs: Record<
rootUrl: "https://docs.godotengine.org/en/latest/",
faviconUrl: "https://godotengine.org/favicon.ico",
},
"https://docs.amplify.aws/react/": {
"https://docs.amplify.aws/react/start/": {
title: "AWS Amplify (Gen 2)",
startUrl: "https://docs.amplify.aws/react/start/",
rootUrl: "https://docs.amplify.aws/react/",
faviconUrl: "https://docs.amplify.aws/favicon.ico"
faviconUrl: "https://docs.amplify.aws/favicon.ico",
},
"https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": {
title: "AWS SDK for JavaScript v3",
startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
faviconUrl: "https://docs.aws.amazon.com/favicon.ico"
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
},
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": {
title: "AWS CDK v2",
startUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html",
startUrl:
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html",
rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/",
faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png"
faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png",
},
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": {
title: "AWS CLI commands",
startUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html",
startUrl:
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html",
rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/",
faviconUrl: "https://docs.aws.amazon.com/favicon.ico"
}
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
},
};
export default preIndexedDocs;

View file

@ -146,7 +146,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
lower.includes("command") ||
lower.includes("chat-bison") ||
lower.includes("pplx") ||
lower.includes("gemini")
lower.includes("gemini") ||
lower.includes("grok")
) {
return undefined;
}

View file

@ -501,15 +501,20 @@ export abstract class BaseLLM implements ILLM {
}
let completion = "";
for await (const chunk of this._streamComplete(prompt, completionOptions)) {
completion += chunk;
yield chunk;
}
try {
for await (const chunk of this._streamComplete(
prompt,
completionOptions,
)) {
completion += chunk;
yield chunk;
}
} finally {
this._logTokensGenerated(completionOptions.model, prompt, completion);
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
}
return {

View file

@ -11,16 +11,17 @@ import { streamSse } from "../stream.js";
class Anthropic extends BaseLLM {
static providerName: ModelProvider = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
model: "claude-3-5-sonnet-20240620",
model: "claude-3-5-sonnet-latest",
contextLength: 200_000,
completionOptions: {
model: "claude-3-5-sonnet-20240620",
model: "claude-3-5-sonnet-latest",
maxTokens: 4096,
},
apiBase: "https://api.anthropic.com/v1/",
};
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
public convertArgs(options: CompletionOptions) {
// should be public for use within VertexAI
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
@ -34,53 +35,61 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
public convertMessages(msgs: ChatMessage[]): any[] {
// should be public for use within VertexAI
const filteredmessages = msgs.filter((m) => m.role !== "system");
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1).slice(-2);
.filter((index) => index !== -1)
.slice(-2);
const messages = filteredmessages.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx);
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
const addCaching =
this.cacheBehavior?.cacheConversation &&
lastTwoUserMsgIndices.includes(filteredMsgIdx);
if (typeof message.content === "string") {
var chatMessage = {
...message,
content: [{
type: "text",
text: message.content,
...(addCaching? { cache_control: { type: "ephemeral" } } : {})
}]
};
return chatMessage;
}
return {
if (typeof message.content === "string") {
var chatMessage = {
...message,
content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
const newpart = {
...part,
// If multiple text parts, only add cache_control to the last one
...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {})
};
return newpart;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
content: [
{
type: "text",
text: message.content,
...(addCaching ? { cache_control: { type: "ephemeral" } } : {}),
},
],
};
});
return chatMessage;
}
return {
...message,
content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
const newpart = {
...part,
// If multiple text parts, only add cache_control to the last one
...(addCaching && contentIdx == message.content.length - 1
? { cache_control: { type: "ephemeral" } }
: {}),
};
return newpart;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
}
@ -98,7 +107,8 @@ class Anthropic extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
);

View file

@ -164,7 +164,7 @@ class FreeTrial extends BaseLLM {
async listModels(): Promise<string[]> {
return [
"codestral-latest",
"claude-3-5-sonnet-20240620",
"claude-3-5-sonnet-latest",
"llama3.1-405b",
"llama3.1-70b",
"gpt-4o",

View file

@ -45,6 +45,7 @@ import WatsonX from "./WatsonX";
import ContinueProxy from "./stubs/ContinueProxy";
import VertexAI from "./VertexAI";
import Asksage from "./Asksage";
import xAI from "./xAI";
const LLMs = [
Anthropic,
@ -84,7 +85,8 @@ const LLMs = [
Cerebras,
Asksage,
Nebius,
VertexAI
VertexAI,
xAI
];
export async function llmFromDescription(

20
core/llm/llms/xAI.ts Normal file
View file

@ -0,0 +1,20 @@
import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class xAI extends OpenAI {
static providerName: ModelProvider = "xAI";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.x.ai/v1/",
};
private static MODEL_IDS: { [name: string]: string } = {
"grok-beta": "grok-beta", // Future names might not line up
};
protected _convertModelName(model: string) {
return xAI.MODEL_IDS[model] || this.model;
}
}
export default xAI;

64
core/package-lock.json generated
View file

@ -64,6 +64,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
@ -14850,6 +14851,69 @@
"node": ">=4"
}
},
"node_modules/wink-distance": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz",
"integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==",
"dependencies": {
"wink-helpers": "^2.0.0",
"wink-jaro-distance": "^2.0.0"
}
},
"node_modules/wink-eng-lite-web-model": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz",
"integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/wink-helpers": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz",
"integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg=="
},
"node_modules/wink-jaro-distance": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz",
"integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA=="
},
"node_modules/wink-nlp": {
"version": "1.14.3",
"resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz",
"integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A=="
},
"node_modules/wink-nlp-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz",
"integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==",
"dependencies": {
"wink-distance": "^2.0.1",
"wink-eng-lite-web-model": "^1.4.3",
"wink-helpers": "^2.0.0",
"wink-nlp": "^1.12.0",
"wink-porter2-stemmer": "^2.0.1",
"wink-tokenizer": "^5.2.3"
}
},
"node_modules/wink-porter2-stemmer": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz",
"integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ=="
},
"node_modules/wink-tokenizer": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz",
"integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==",
"dependencies": {
"emoji-regex": "^9.0.0"
}
},
"node_modules/wink-tokenizer/node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",

View file

@ -95,6 +95,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"

View file

@ -1,8 +1,9 @@
import type { RangeInFileWithContents } from "../commands/util.js";
import type { ContextSubmenuItem } from "../index.js";
import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
import type { RangeInFileWithContents } from "../commands/util.js";
import type { ContextSubmenuItem, MessageContent } from "../index.js";
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
onLoad: [
undefined,
@ -17,8 +18,13 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
openUrl: [string, void];
// We pass the `curSelectedModel` because we currently cannot access the
// default model title in the GUI from JB
applyToCurrentFile: [
{ text: string; streamId: string; curSelectedModelTitle: string },
applyToFile: [
{
text: string;
streamId: string;
curSelectedModelTitle: string;
filepath: string;
},
void,
];
showTutorial: [undefined, void];
@ -35,8 +41,23 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string }, void];
rejectDiff: [{ filepath: string }, void];
"edit/sendPrompt": [
{ prompt: MessageContent; range: RangeInFileWithContents },
void,
];
"edit/acceptReject": [
{ accept: boolean; onlyFirst: boolean; filepath: string },
void,
];
"edit/escape": [undefined, void];
};
export interface EditModeArgs {
highlightedCode: RangeInFileWithContents;
}
export type EditStatus = "not-started" | "streaming" | "accepting" | "done";
export interface ApplyState {
streamId: string;
status: "streaming" | "done" | "closed";
@ -44,7 +65,6 @@ export interface ApplyState {
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
setTTSActive: [boolean, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
updateSubmenuItems: [
{ provider: string; submenuItems: ContextSubmenuItem[] },
@ -82,4 +102,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
openOnboardingCard: [undefined, void];
applyCodeFromChat: [undefined, void];
updateApplyState: [ApplyState, void];
startEditMode: [EditModeArgs, void];
setEditStatus: [{ status: EditStatus }, void];
exitEditMode: [undefined, void];
};

View file

@ -60,4 +60,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"isContinueInputFocused",
"didChangeAvailableProfiles",
"setTTSActive",
"getWebviewHistoryLength"
];

View file

@ -16,4 +16,5 @@ export type ToWebviewFromIdeOrCoreProtocol = {
void,
];
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
};

View file

@ -27,7 +27,7 @@ export class MessageIde implements IDE {
messageType: T,
callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1],
) => void,
) {}
) { }
pathSep(): Promise<string> {
return this.request("pathSep", undefined);

View file

@ -25,7 +25,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz
{
"title": "Claude 3.5 Sonnet",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20240620",
"model": "claude-3-5-sonnet-latest",
"apiKey": "[ANTHROPIC_API_KEY]"
}
]

View file

@ -6,7 +6,7 @@ toc_max_heading_level: 5
# @Docs
The [`@Docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding.
The [`@Docs` context provider](customize/context-providers.md#docs) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding.
## Enabling the `@Docs` context provider

View file

@ -19,7 +19,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
{
"title": "Claude 3.5 Sonnet",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20240620",
"model": "claude-3-5-sonnet-latest",
"apiKey": "[API_KEY]"
}
]
@ -61,7 +61,7 @@ To enable caching of the system message and the turn-by-turn conversation, updat
},
"title": "Anthropic",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20240620",
"model": "claude-3-5-sonnet-latest",
"apiKey": "[API_KEY]"
}
]

View file

@ -0,0 +1,53 @@
---
title: xAI
slug: ../xai
---
:::info
You can get an API key from the [xAI console](https://console.x.ai/)
:::
## Chat model
We recommend configuring **grok-beta** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Grok Beta",
"provider": "xAI",
"model": "grok-beta",
"apiKey": "[API_KEY]"
}
]
}
```
## Autocomplete model
xAI currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
xAI currently does not offer any embeddings models.
[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers.
## Reranking model
xAI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Legacy Completions
To force usage of `chat/completions` instead of `completions` endpoint you can set
```json
"useLegacyCompletionsEndpoint": false
```

View file

@ -72,6 +72,7 @@ The `"modelTitle"` field must match one of the models in your "models" array in
"name": "huggingface-tei",
"params": {
"apiBase": "http://localhost:8080",
"apiKey": "<TEI_API_KEY>",
"truncate": true,
"truncation_direction": "Right"
}

View file

@ -421,7 +421,7 @@ Several experimental config parameters are available, as described below:
- `fix`: Prompt for fixing code.
- `optimize`: Prompt for optimizing code.
- `fixGrammar`: Prompt for fixing grammar or spelling.
- `useChromiumForDocsCrawling`: Use chromium to crawl docs instead of default lighter-weight tool that can't render sites. Downloads and installs Chromium to `~/.continue/.utils`.
- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`..
Example

View file

@ -1,2 +1,5 @@
src/main/resources/webview
src/main/resources/bin
!src/main/resources/webview/index.html
src/main/resources/bin
src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json

View file

@ -14,7 +14,7 @@ const val DEFAULT_CONFIG =
{
"models": [
{
"model": "claude-3-5-sonnet-20240620",
"model": "claude-3-5-sonnet-latest",
"provider": "anthropic",
"apiKey": "",
"title": "Claude 3.5 Sonnet"

View file

@ -22,7 +22,7 @@ class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory {
class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider {
override fun isAvailable(file: VirtualFile): Boolean {
return file.path.endsWith(".continue/config.json")
return file.path.endsWith("/.continue/config.json")
}
override fun getName(): String {

View file

@ -632,7 +632,7 @@ class IdeProtocolClient(
}
}
"applyToCurrentFile" -> {
"applyToFile" -> {
val msg = data as Map<String, String>;
val text = msg["text"] as String
val curSelectedModelTitle = msg["curSelectedModelTitle"] as String

View file

@ -2,10 +2,12 @@ package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.messages.Topic
import kotlinx.serialization.Serializable
@ -28,6 +30,7 @@ class ContinueSettingsComponent : DumbAware {
val userToken: JTextField = JTextField()
val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete")
val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta")
val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering")
val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip")
init {
@ -56,6 +59,8 @@ class ContinueSettingsComponent : DumbAware {
constraints.gridy++
panel.add(enableContinueTeamsBeta, constraints)
constraints.gridy++
panel.add(enableOSR, constraints)
constraints.gridy++
panel.add(displayEditorTooltip, constraints)
constraints.gridy++
@ -87,6 +92,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
var enableTabAutocomplete: Boolean = true
var ghAuthToken: String? = null
var enableContinueTeamsBeta: Boolean = false
var enableOSR: Boolean = shouldRenderOffScreen()
var displayEditorTooltip: Boolean = true
}
@ -107,6 +113,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
get() = ServiceManager.getService(ContinueExtensionSettings::class.java)
}
// Sync remote config from server
private fun syncRemoteConfig() {
val state = instance.continueState
@ -198,6 +205,7 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.userToken?.text != settings.continueState.userToken ||
mySettingsComponent?.enableTabAutocomplete?.isSelected != settings.continueState.enableTabAutocomplete ||
mySettingsComponent?.enableContinueTeamsBeta?.isSelected != settings.continueState.enableContinueTeamsBeta ||
mySettingsComponent?.enableOSR?.isSelected != settings.continueState.enableOSR ||
mySettingsComponent?.displayEditorTooltip?.isSelected != settings.continueState.displayEditorTooltip
return modified
}
@ -210,6 +218,7 @@ class ContinueExtensionConfigurable : Configurable {
settings.continueState.enableTabAutocomplete = mySettingsComponent?.enableTabAutocomplete?.isSelected ?: false
settings.continueState.enableContinueTeamsBeta =
mySettingsComponent?.enableContinueTeamsBeta?.isSelected ?: false
settings.continueState.enableOSR = mySettingsComponent?.enableOSR?.isSelected ?: true
settings.continueState.displayEditorTooltip = mySettingsComponent?.displayEditorTooltip?.isSelected ?: true
ApplicationManager.getApplication().messageBus.syncPublisher(SettingsListener.TOPIC)
@ -224,6 +233,7 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.userToken?.text = settings.continueState.userToken
mySettingsComponent?.enableTabAutocomplete?.isSelected = settings.continueState.enableTabAutocomplete
mySettingsComponent?.enableContinueTeamsBeta?.isSelected = settings.continueState.enableContinueTeamsBeta
mySettingsComponent?.enableOSR?.isSelected = settings.continueState.enableOSR
mySettingsComponent?.displayEditorTooltip?.isSelected = settings.continueState.displayEditorTooltip
ContinueExtensionSettings.instance.addRemoteSyncJob()
@ -237,3 +247,38 @@ class ContinueExtensionConfigurable : Configurable {
return "Continue Extension Settings"
}
}
/**
* This function checks if off-screen rendering (OSR) should be used.
*
* If ui.useOSR is set in config.json, that value is used.
*
* Otherwise, we check if the pluginSinceBuild is greater than or equal to 233, which corresponds
* to IntelliJ platform version 2023.3 and later.
*
* Setting `setOffScreenRendering` to `false` causes a number of issues such as a white screen flash when loading
* the GUI and the inability to set `cursor: pointer`. However, setting `setOffScreenRendering` to `true` on
* platform versions prior to 2023.3.4 causes larger issues such as an inability to type input for certain languages,
* e.g. Korean.
*
* References:
* 1. https://youtrack.jetbrains.com/issue/IDEA-347828/JCEF-white-flash-when-tool-window-show#focus=Comments-27-9334070.0-0
* This issue mentions that white screen flash problems were resolved in platformVersion 2023.3.4.
* 2. https://www.jetbrains.com/idea/download/other.html
* This documentation shows mappings from platformVersion to branchNumber.
*
* We use the branchNumber (e.g., 233) instead of the full version number (e.g., 2023.3.4) because
* it's a simple integer without dot notation, making it easier to compare.
*/
private fun shouldRenderOffScreen(): Boolean {
// With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality
// in the browser. Disabling OSR for all non-Mac users for now.
if (!SystemInfo.isMac) {
return false
}
val minBuildNumber = 233
val applicationInfo = ApplicationInfo.getInstance()
val currentBuildNumber = applicationInfo.build.baselineVersion
return currentBuildNumber >= minBuildNumber
}

View file

@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.JsonObject
@ -78,7 +79,8 @@ class ContinueBrowser(val project: Project, url: String) {
val browser: JBCefBrowser
init {
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(shouldRenderOffScreen()).build()
val enableOSR = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(enableOSR).build()
browser.jbCefClient.setProperty(
@ -274,34 +276,4 @@ class ContinueBrowser(val project: Project, url: String) {
return """window.postMessage($jsonData, "*");"""
}
/**
* This function checks if the pluginSinceBuild is greater than or equal to 233, which corresponds
* to IntelliJ platform version 2023.3 and later.
*
* Setting `setOffScreenRendering` to `false` causes a number of issues such as a white screen flash when loading
* the GUI and the inability to set `cursor: pointer`. However, setting `setOffScreenRendering` to `true` on
* platform versions prior to 2023.3.4 causes larger issues such as an inability to type input for certain langauges,
* e.g. Korean.
*
* References:
* 1. https://youtrack.jetbrains.com/issue/IDEA-347828/JCEF-white-flash-when-tool-window-show#focus=Comments-27-9334070.0-0
* This issue mentions that white screen flash problems were resolved in platformVersion 2023.3.4.
* 2. https://www.jetbrains.com/idea/download/other.html
* This documentation shows mappings from platformVersion to branchNumber.
*
* We use the branchNumber (e.g., 233) instead of the full version number (e.g., 2023.3.4) because
* it's a simple integer without dot notation, making it easier to compare.
*/
private fun shouldRenderOffScreen(): Boolean {
// With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality
// in the browser. Disabling OSR for all non-Mac users for now.
if (!SystemInfo.isMac) {
return false
}
val minBuildNumber = 233
val applicationInfo = ApplicationInfo.getInstance()
val currentBuildNumber = applicationInfo.build.baselineVersion
return currentBuildNumber >= minBuildNumber
}
}

View file

@ -1,3 +0,0 @@
<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" fill="#6C707E"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -1,3 +0,0 @@
{
"customCommands": []
}

View file

@ -10,8 +10,10 @@ exe
bin
assets
gui/*
gui/**
!gui/onigasm.wasm
.devcontainer
.github
.github
continue_rc_schema.json

View file

@ -1,28 +0,0 @@
temperature: 0.0
---
{{{ diff }}}
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
- If you found any problems, an h3 like "❌ <filename>"
- If you didn't find any problems, an h3 like "✅ <filename>"
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
- If you didn't find any problems, you don't need to add anything else
Here is an example. The example is surrounded in backticks, but your response should not be:
```
### ✅ <Filename1>
### ❌ <Filename2>
<Description>
```
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
- console.logs that have been left after debugging
- repeated code
- algorithmic errors that could fail under edge cases
- something that could be refactored
Make sure to review ALL files that were changed, do not skip any.

View file

@ -1,17 +0,0 @@
temperature: 0.5
maxTokens: 4096
---
<system>
You are an expert programmer
</system>
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:
- Use `jest`
- Properly set up and tear down
- Include important edge cases
- The tests should be complete and sophisticated
- Give the tests just as chat output, don't edit any file
- Don't explain how to set up `jest`
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")

View file

@ -5,6 +5,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
### Added
* New Edit mode in sidebar (cmd/ctrl+I)
* Significantly faster and more accurate docs crawler by default
## 0.8.55 - 2024-10-25
### Added
* Web context provider

View file

@ -201,7 +201,8 @@
"cerebras",
"askSage",
"nebius",
"vertexai"
"vertexai",
"xAI"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)",
@ -236,7 +237,8 @@
"### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)",
"### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.",
"### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).",
"### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)"
"### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)",
"### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)"
],
"type": "string"
},
@ -471,7 +473,8 @@
"together",
"cloudflare",
"sambanova",
"nebius"
"nebius",
"xAI"
]
}
},
@ -655,6 +658,37 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"xAI"
]
}
},
"required": [
"provider"
]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"grok-beta",
"AUTODETECT"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {
@ -719,7 +753,7 @@
"llama3.1-405b",
"gpt-3.5-turbo",
"gemini-pro",
"claude-3-5-sonnet-20240620",
"claude-3-5-sonnet-latest",
"claude-3-haiku-20240307",
"AUTODETECT"
]
@ -834,7 +868,7 @@
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-5-sonnet-20240620",
"claude-3-5-sonnet-latest",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
@ -1301,7 +1335,10 @@
]
},
"then": {
"required": ["deployment", "apiBase"]
"required": [
"deployment",
"apiBase"
]
}
},
{
@ -1491,6 +1528,7 @@
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-5-sonnet-latest",
"claude-3-5-sonnet-20240620",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
@ -2962,6 +3000,9 @@
"type": "string",
"default": "http://localhost:8080"
},
"apiKey": {
"type": "string"
},
"truncate": {
"type": "boolean",
"description": "Whether to truncate long sequences to the maximum allowed context length.",
@ -3279,6 +3320,11 @@
"default": "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing."
}
}
},
"useChromiumForDocsCrawling": {
"type": "boolean",
"description": "Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.",
"default": false
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

View file

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/play_button.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Continue</title>
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" href="/assets/index.css">
</head>
<body>
<div id="root"></div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 483 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1,017 B

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.223",
"version": "0.9.227",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.223",
"version": "0.9.227",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -149,6 +149,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
@ -12598,4 +12599,4 @@
}
}
}
}
}

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.223",
"version": "0.9.227",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -182,6 +182,18 @@
"title": "Debug Terminal",
"group": "Continue"
},
{
"command": "continue.edit",
"category": "Continue",
"title": "Edit code with natural language",
"group": "Continue"
},
{
"command": "continue.exitEditMode",
"category": "Continue",
"title": "Exit Edit Mode",
"group": "Continue"
},
{
"command": "continue.toggleFullScreen",
"category": "Continue",
@ -339,9 +351,20 @@
},
{
"command": "continue.quickEdit",
"mac": "cmd+shift+i",
"key": "ctrl+shift+i"
},
{
"command": "continue.edit",
"mac": "cmd+i",
"key": "ctrl+i"
},
{
"command": "continue.exitEditMode",
"mac": "escape",
"key": "escape",
"when": "continue.inEditMode && editorFocus"
},
{
"command": "continue.debugTerminal",
"mac": "cmd+shift+r",

View file

@ -30,4 +30,5 @@ const esbuildConfig = {
} else {
await esbuild.build(esbuildConfig);
}
})();
console.log("VS Code Extension esbuild complete"); // Used in task endpattern to signal completion
})();

View file

@ -18,8 +18,8 @@ function copyConfigSchema() {
enum: ["merge", "overwrite"],
default: "merge",
title: "Merge behavior",
markdownDescription:
"If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.",
markdownDescription: "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.",
"x-intellij-html-description": "<p>If set to <code>merge</code>, <code>.continuerc.json</code> will be applied on top of <code>config.json</code> (arrays and objects are merged). If set to <code>overwrite</code>, then every top-level property of <code>.continuerc.json</code> will overwrite that property from <code>config.json</code>.</p>"
};
fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2));

View file

@ -384,7 +384,7 @@ class VsCodeIde implements IDE {
}
async openFile(path: string): Promise<void> {
this.ideUtils.openFile(path);
await this.ideUtils.openFile(path);
}
async showLines(

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,10 @@
import { DiffLine } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { streamDiffLines } from "core/edit/streamDiffLines";
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
import { getMarkdownLanguageTagForFile } from "core/util";
import { DiffLine } from "core";
import { streamDiffLines } from "core/edit/streamDiffLines";
import * as vscode from "vscode";
import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
@ -27,6 +28,7 @@ export class VerticalDiffManager {
constructor(
private readonly configHandler: ConfigHandler,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly editDecorationManager: EditDecorationManager,
) {
this.userChangeListener = undefined;
}
@ -240,7 +242,7 @@ export class VerticalDiffManager {
try {
this.logDiffs = await diffHandler.run(diffStream);
// enable a listener for user edits to file while diff is open
this.enableDocumentChangeListener();
} catch (e) {
@ -255,30 +257,6 @@ export class VerticalDiffManager {
}
}
/**
* Streams an edit to the current document based on user input and model output.
*
* @param input - The user's input or instruction for the edit.
* @param modelTitle - The title of the language model to be used.
* @param [onlyOneInsertion] - Optional flag to limit the edit to a single insertion.
* @param [quickEdit] - Optional string indicating if this is a quick edit.
* @param [range] - Optional range to use instead of the highlighted text. Note that the `quickEdit`
* property currently can't be passed with `range` since it assumes there is an
* active selection.
*
* This method performs the following steps:
* 1. Sets up the editor context for the diff.
* 2. Determines the range of text to be edited.
* 3. Clears any existing diff handlers for the file.
* 4. Creates a new vertical diff handler.
* 5. Prepares the context (prefix and suffix) for the language model.
* 6. Streams the diff lines from the language model.
* 7. Applies the changes to the document.
* 8. Sets up a listener for subsequent user edits.
*
* The method handles various edge cases, such as quick edits and existing diffs,
* and manages the lifecycle of diff handlers and document change listeners.
*/
async streamEdit(
input: string,
modelTitle: string | undefined,
@ -411,6 +389,8 @@ export class VerticalDiffManager {
true,
);
this.editDecorationManager.clear();
try {
this.logDiffs = await diffHandler.run(
streamDiffLines(

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 EditDecorationManager from "../quickEdit/EditDecorationManager";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
import {
@ -42,6 +43,7 @@ export class VsCodeExtension {
private sidebar: ContinueGUIWebviewViewProvider;
private windowId: string;
private diffManager: DiffManager;
private editDecorationManager: EditDecorationManager;
private verticalDiffManager: VerticalDiffManager;
webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
private core: Core;
@ -54,6 +56,8 @@ export class VsCodeExtension {
this.workOsAuthProvider.refreshSessions();
context.subscriptions.push(this.workOsAuthProvider);
this.editDecorationManager = new EditDecorationManager(context);
let resolveWebviewProtocol: any = undefined;
this.webviewProtocolPromise = new Promise<VsCodeWebviewProtocol>(
(resolve) => {
@ -110,6 +114,7 @@ export class VsCodeExtension {
verticalDiffManagerPromise,
configHandlerPromise,
this.workOsAuthProvider,
this.editDecorationManager,
);
this.core = new Core(inProcessMessenger, this.ide, async (log: string) => {
@ -128,6 +133,7 @@ export class VsCodeExtension {
this.verticalDiffManager = new VerticalDiffManager(
this.configHandler,
this.sidebar.webviewProtocol,
this.editDecorationManager,
);
resolveVerticalDiffManager?.(this.verticalDiffManager);
this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler);
@ -221,6 +227,7 @@ export class VsCodeExtension {
this.battery,
quickEdit,
this.core,
this.editDecorationManager,
);
// Disabled due to performance issues

View file

@ -1,6 +1,7 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
import { stripImages } from "core/llm/images";
import {
FromCoreProtocol,
FromWebviewProtocol,
@ -20,6 +21,7 @@ import * as fs from "node:fs";
import * as path from "node:path";
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
@ -27,6 +29,7 @@ import {
import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { getFullyQualifiedPath } from "../util/util";
/**
* A shared messenger class between Core and Webview
@ -79,10 +82,15 @@ export class VsCodeMessenger {
private readonly verticalDiffManagerPromise: Promise<VerticalDiffManager>,
private readonly configHandlerPromise: Promise<ConfigHandler>,
private readonly workOsAuthProvider: WorkOsAuthProvider,
private readonly editDecorationManager: EditDecorationManager,
) {
/** WEBVIEW ONLY LISTENERS **/
this.onWebview("showFile", (msg) => {
this.ide.openFile(msg.data.filepath);
const fullPath = getFullyQualifiedPath(this.ide, msg.data.filepath);
if (fullPath) {
this.ide.openFile(fullPath);
}
});
this.onWebview("vscode/openMoveRightMarkdown", (msg) => {
@ -150,9 +158,33 @@ export class VsCodeMessenger {
await vscode.commands.executeCommand("continue.rejectDiff", filepath);
});
this.onWebview("applyToCurrentFile", async ({ data }) => {
this.onWebview("applyToFile", async ({ data }) => {
const fullPath = getFullyQualifiedPath(ide, data.filepath);
if (!fullPath) {
return;
}
const fileExists = await this.ide.fileExists(fullPath);
// If it's a new file, no need to apply, just write directly
if (!fileExists) {
await this.ide.writeFile(fullPath, data.text);
await this.ide.openFile(fullPath);
await webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
});
return;
}
await this.ide.openFile(fullPath);
// Get active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage("No active editor to apply edits to");
return;
@ -160,7 +192,9 @@ export class VsCodeMessenger {
// If document is empty, insert at 0,0 and finish
if (!editor.document.getText().trim()) {
editor.edit(builder => builder.insert(new vscode.Position(0, 0), data.text));
editor.edit((builder) =>
builder.insert(new vscode.Position(0, 0), data.text),
);
await webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
@ -175,7 +209,9 @@ export class VsCodeMessenger {
let llm = getModelByRole(config, "applyCodeBlock");
if (!llm) {
llm = config.models.find((model) => model.title === data.curSelectedModelTitle);
llm = config.models.find(
(model) => model.title === data.curSelectedModelTitle,
);
if (!llm) {
vscode.window.showErrorMessage(
@ -263,6 +299,57 @@ export class VsCodeMessenger {
);
});
});
this.onWebview("edit/sendPrompt", async (msg) => {
const prompt = msg.data.prompt;
const { start, end } = msg.data.range.range;
const verticalDiffManager = await verticalDiffManagerPromise;
const modelTitle = await this.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
);
await verticalDiffManager.streamEdit(
stripImages(prompt),
modelTitle,
"edit",
undefined,
undefined,
new vscode.Range(
new vscode.Position(start.line, start.character),
new vscode.Position(end.line, end.character),
),
);
this.webviewProtocol.request("setEditStatus", {
status: "accepting",
});
});
this.onWebview("edit/acceptReject", async (msg) => {
const { onlyFirst, accept, filepath } = msg.data;
if (accept && onlyFirst) {
// Accept first
vscode.commands.executeCommand(
"continue.acceptVerticalDiffBlock",
filepath,
0,
);
} else if (accept) {
vscode.commands.executeCommand("continue.acceptDiff", filepath);
// Accept all
} else if (onlyFirst) {
// Reject first
vscode.commands.executeCommand(
"continue.rejectVerticalDiffBlock",
filepath,
0,
);
} else {
// Reject all
vscode.commands.executeCommand("continue.rejectDiff", filepath);
}
});
this.onWebview("edit/escape", async (msg) => {
this.editDecorationManager.clear();
});
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {

View file

@ -0,0 +1,44 @@
import vscode from "vscode";
class EditDecorationManager {
private _lastEditor: vscode.TextEditor | undefined;
private decorationType: vscode.TextEditorDecorationType;
constructor(context: vscode.ExtensionContext) {
this.decorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: "rgba(255, 255, 0, 0.1)",
borderWidth: "0 0 0 1px",
borderColor: "rgba(255, 255, 0)",
borderStyle: "solid",
isWholeLine: true,
cursor: "pointer",
// gutterIconPath: context.asAbsolutePath("media/gutterIcon.png"),
gutterIconSize: "contain",
});
}
private updateInEditMode(inEditMode: boolean) {
vscode.commands.executeCommand(
"setContext",
"continue.inEditMode",
inEditMode,
);
}
setDecoration(editor: vscode.TextEditor, range: vscode.Range) {
if (this._lastEditor) {
this._lastEditor.setDecorations(this.decorationType, []);
}
editor.setDecorations(this.decorationType, [range]);
this._lastEditor = editor;
this.updateInEditMode(true);
}
clear() {
if (this._lastEditor) {
this._lastEditor.setDecorations(this.decorationType, []);
this._lastEditor = undefined;
this.updateInEditMode(false);
}
}
}
export default EditDecorationManager;

View file

@ -136,9 +136,7 @@ export class VsCodeIdeUtils {
);
}
private async resolveAbsFilepathInWorkspace(
filepath: string,
): Promise<string> {
async resolveAbsFilepathInWorkspace(filepath: string): Promise<string> {
// If the filepath is already absolute, return it as is
if (this.path.isAbsolute(filepath)) {
return filepath;
@ -158,7 +156,7 @@ export class VsCodeIdeUtils {
async openFile(filepath: string, range?: vscode.Range) {
// vscode has a builtin open/get open files
return openEditorAndRevealRange(
return await openEditorAndRevealRange(
await this.resolveAbsFilepathInWorkspace(filepath),
range,
vscode.ViewColumn.One,

View file

@ -2,17 +2,12 @@ import type { ILLM } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import Ollama from "core/llm/llms/Ollama";
import { GlobalContext } from "core/util/GlobalContext";
import * as vscode from "vscode";
export class TabAutocompleteModel {
private _llm: ILLM | undefined;
private defaultTag = "starcoder2:3b";
private defaultTagName = "Starcoder2 3b";
private globalContext: GlobalContext = new GlobalContext();
private shownOllamaWarning = false;
private shownDeepseekWarning = false;
constructor(private configHandler: ConfigHandler) {}
clearLlm() {
@ -27,49 +22,9 @@ export class TabAutocompleteModel {
try {
const models = await llm.listModels();
if (!models.includes(this.defaultTag)) {
if (!this.shownDeepseekWarning) {
vscode.window
.showWarningMessage(
`Your local Ollama instance doesn't yet have ${this.defaultTagName}. To download this model, run \`ollama run ${this.defaultTag}\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`,
"Documentation",
"Copy Command",
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/features/tab-autocomplete",
),
);
} else if (value === "Copy Command") {
vscode.env.clipboard.writeText(`ollama run ${this.defaultTag}`);
}
});
this.shownDeepseekWarning = true;
}
return undefined;
}
} catch (e) {
if (!this.shownOllamaWarning) {
vscode.window
.showWarningMessage(
"Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs",
"Download Ollama",
"Documentation",
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/features/tab-autocomplete",
),
);
} else if (value === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai"));
}
});
this.shownOllamaWarning = true;
}
return undefined;
}

View file

@ -1,6 +1,7 @@
const os = require("node:os");
import path from "node:path";
import * as vscode from "vscode";
import { VsCodeIde } from "../VsCodeIde";
function charIsEscapedAtIndex(index: number, str: string): boolean {
if (index === 0) {
@ -123,15 +124,12 @@ export function getExtensionVersion(): string {
return extension?.packageJSON.version || "0.1.0";
}
export function getFullyQualifiedPath(filepath?: string) {
if (filepath && !path.isAbsolute(filepath)) {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (workspaceFolders && workspaceFolders.length > 0) {
return path.join(workspaceFolders[0].uri.fsPath, filepath);
} else {
vscode.window.showErrorMessage(
"Unable to resolve filepath: no workspace folder found",
);
}
export function getFullyQualifiedPath(ide: VsCodeIde, filepath: string) {
if (ide.ideUtils.path.isAbsolute(filepath)) return filepath;
const workspaceFolders = vscode.workspace.workspaceFolders;
if (workspaceFolders && workspaceFolders.length > 0) {
return ide.ideUtils.path.join(workspaceFolders[0].uri.fsPath, filepath);
}
}

3
gui/package-lock.json generated
View file

@ -37,7 +37,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.10.3",
"react-intersection-observer": "^9.13.1",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",
@ -151,6 +151,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"

View file

@ -45,7 +45,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.10.3",
"react-intersection-observer": "^9.13.1",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",

BIN
gui/public/logos/xAI.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View file

@ -7,8 +7,10 @@ import useSetup from "./hooks/useSetup";
import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders";
import { useVscTheme } from "./hooks/useVscTheme";
import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel";
import ConfigErrorPage from "./pages/config-error";
import Edit from "./pages/edit";
import ErrorPage from "./pages/error";
import GUI from "./pages/gui";
import Chat from "./pages/gui";
import History from "./pages/history";
import MigrationPage from "./pages/migration";
import MonacoPage from "./pages/monaco";
@ -16,7 +18,6 @@ import MorePage from "./pages/More";
import SettingsPage from "./pages/settings";
import Stats from "./pages/stats";
import { ROUTES } from "./util/navigation";
import ConfigErrorPage from "./pages/config-error";
const router = createMemoryRouter([
{
@ -26,11 +27,15 @@ const router = createMemoryRouter([
children: [
{
path: "/index.html",
element: <GUI />,
element: <Chat />,
},
{
path: "/",
element: <GUI />,
element: <Chat />,
},
{
path: "/edit",
element: <Edit />,
},
{
path: "/history",

View file

@ -7,6 +7,11 @@ import { IdeMessengerContext } from "../context/IdeMessenger";
import { LastSessionProvider } from "../context/LastSessionContext";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useConfigError } from "../redux/hooks";
import {
setEditDone,
setEditStatus,
startEditMode,
} from "../redux/slices/editModeState";
import { setShowDialog, updateApplyState } from "../redux/slices/uiStateSlice";
import { RootState } from "../redux/store";
import { getFontSize, isMetaEquivalentKeyPressed } from "../util";
@ -174,6 +179,24 @@ const Layout = () => {
[],
);
useWebviewListener(
"startEditMode",
async (args) => {
dispatch(startEditMode(args));
navigate("/edit");
},
[navigate],
);
useWebviewListener("setEditStatus", async ({ status }) => {
dispatch(setEditStatus(status));
});
useWebviewListener("exitEditMode", async () => {
dispatch(setEditDone());
navigate("/");
});
useEffect(() => {
if (
isNewUserOnboarding() &&

View file

@ -1,5 +1,4 @@
import {
ArrowPathIcon,
BarsArrowDownIcon,
HandThumbDownIcon,
HandThumbUpIcon,
@ -14,7 +13,7 @@ import { vscBackground, vscInputBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import useUIConfig from "../../hooks/useUIConfig";
import { RootState } from "../../redux/store";
import { getFontSize } from "../../util";
import { getFontSize, getMetaKeyLabel } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import { CopyButton } from "../markdown/CopyButton";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
@ -50,7 +49,7 @@ function StepContainer(props: StepContainerProps) {
const isUserInput = props.item.message.role === "user";
const uiConfig = useUIConfig();
const shouldRenderActions = !props.isLast || (props.isLast && !active);
const shouldRenderActions = !active || !props.isLast;
useEffect(() => {
if (!active) {
@ -84,7 +83,11 @@ function StepContainer(props: StepContainerProps) {
};
return (
<div className="relative">
<div className="relative"
style={{
minHeight: props.isLast ? "50vh" : 0
}}
>
<ContentDiv
hidden={!props.open}
isUserInput={isUserInput}
@ -104,52 +107,55 @@ function StepContainer(props: StepContainerProps) {
/>
)}
</ContentDiv>
{shouldRenderActions && (
<div className="flex items-center justify-end gap-0.5 xs:flex text-xs text-gray-400 p-2 pb-0 cursor-default">
{truncatedEarly && (
<ButtonWithTooltip
tabIndex={-1}
text="Continue generation"
onClick={props.onContinueGeneration}
>
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
)}
{props.index !== 1 && (
<ButtonWithTooltip
text="Delete"
tabIndex={-1}
onClick={props.onDelete}
>
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
)}
<CopyButton
tabIndex={-1}
text={stripImages(props.item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
/>
<div className="h-7 mb-2 mx-2 flex items-center justify-end gap-0.5 xs:flex text-xs text-gray-400 pb-0 cursor-default"
style={{
opacity: shouldRenderActions ? 1 : 0,
pointerEvents: shouldRenderActions ? "auto" : "none"
}}
>
{truncatedEarly && (
<ButtonWithTooltip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
text="Continue generation"
onClick={props.onContinueGeneration}
>
<HandThumbUpIcon className="h-3.5 w-3.5 text-gray-500 mx-0.5" />
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
)}
{props.index !== 1 && (
<ButtonWithTooltip
text="Unhelpful"
text="Delete"
tabIndex={-1}
onClick={() => sendFeedback(false)}
onClick={props.onDelete}
>
<HandThumbDownIcon className="h-3.5 w-3.5 text-gray-500" />
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
</div>
)}
)}
<CopyButton
tabIndex={-1}
text={stripImages(props.item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<ButtonWithTooltip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
>
<HandThumbUpIcon className={`h-3.5 w-3.5 mx-0.5 ${feedback === true ? 'text-green-400' : 'text-gray-500'}`} />
</ButtonWithTooltip>
<ButtonWithTooltip
text="Unhelpful"
tabIndex={-1}
onClick={() => sendFeedback(false)}
>
<HandThumbDownIcon className={`h-3.5 w-3.5 ${feedback === false ? 'text-red-400' : 'text-gray-500'}`} />
</ButtonWithTooltip>
</div>
</div>
);
}

View file

@ -1,5 +1,6 @@
import { JSONContent } from "@tiptap/react";
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
@ -9,12 +10,15 @@ import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice";
import { RootState } from "../../redux/store";
import ContextItemsPeek from "./ContextItemsPeek";
import TipTapEditor from "./TipTapEditor";
import { useState, useRef, useEffect } from "react";
interface ContinueInputBoxProps {
isLastUserInput: boolean;
isMainInput?: boolean;
onEnter: (editorState: JSONContent, modifiers: InputModifiers) => void;
onEnter: (
editorState: JSONContent,
modifiers: InputModifiers,
editor: Editor,
) => void;
editorState?: JSONContent;
contextItems?: ContextItemWithId[];
hidden?: boolean;
@ -105,8 +109,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}, [isGatheringContextStore]);
return (
<div className={`mt-3 mb-1 ${props.hidden ? "hidden" : ""}`}>
<div className={`flex px-2 relative`}>
<div className={`mb-1 ${props.hidden ? "hidden" : ""}`}>
<div className={`relative flex px-2`}>
<GradientBorder
loading={active && props.isLastUserInput ? 1 : 0}
borderColor={
@ -116,10 +120,16 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
>
<TipTapEditor
editorState={props.editorState}
onEnter={props.onEnter}
onEnter={(...args) => {
props.onEnter(...args);
if (props.isMainInput) {
args[2].commands.clearContent(true);
}
}}
isMainInput={props.isMainInput ?? false}
availableContextProviders={availableContextProviders ?? []}
availableSlashCommands={availableSlashCommands}
historyKey="chat"
/>
</GradientBorder>
</div>

View file

@ -1,8 +1,4 @@
import {
AtSymbolIcon,
PhotoIcon,
SlashIcon,
} from "@heroicons/react/24/outline";
import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { useRef } from "react";
@ -11,8 +7,6 @@ import styled from "styled-components";
import {
defaultBorderRadius,
lightGray,
vscBadgeBackground,
vscBadgeForeground,
vscForeground,
vscInputBackground,
} from "..";
@ -24,8 +18,8 @@ import {
getMetaKeyLabel,
isMetaEquivalentKeyPressed,
} from "../../util";
import ModelSelect from "../modelSelection/ModelSelect";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
const StyledDiv = styled.div<{ isHidden: boolean }>`
padding: 4px 0;
@ -69,6 +63,14 @@ const EnterButton = styled.button`
}
`;
export interface ToolbarOptions {
hideUseCodebase?: boolean;
hideImageUpload?: boolean;
hideAddContext?: boolean;
enterText?: string;
hideSelectModel?: boolean;
}
interface InputToolbarProps {
onEnter?: (modifiers: InputModifiers) => void;
onAddContextItem?: () => void;
@ -77,6 +79,7 @@ interface InputToolbarProps {
onImageFileSelected?: (file: File) => void;
hidden?: boolean;
activeKey: string | null;
toolbarOptions?: ToolbarOptions;
disabled?: boolean;
}
@ -105,69 +108,73 @@ function InputToolbar(props: InputToolbarProps) {
<div className="flex items-center justify-start gap-2 whitespace-nowrap">
<ModelSelect />
<div className="xs:flex -mb-1 hidden items-center gap-1 text-gray-400 transition-colors duration-200">
{supportsImages && (
<>
<input
type="file"
ref={fileInputRef}
style={{ display: "none" }}
accept=".jpg,.jpeg,.png,.gif,.svg,.webp"
onChange={(e) => {
for (const file of e.target.files) {
props.onImageFileSelected(file);
}
}}
/>
<HoverItem>
<PhotoIcon
className="h-4 w-4"
onClick={(e) => {
fileInputRef.current?.click();
{props.toolbarOptions?.hideImageUpload ||
(supportsImages && (
<>
<input
type="file"
ref={fileInputRef}
style={{ display: "none" }}
accept=".jpg,.jpeg,.png,.gif,.svg,.webp"
onChange={(e) => {
for (const file of e.target.files) {
props.onImageFileSelected(file);
}
}}
/>
</HoverItem>
</>
)}
<HoverItem>
<PhotoIcon
className="h-4 w-4"
onClick={(e) => {
fileInputRef.current?.click();
}}
/>
</HoverItem>
</>
))}
{props.toolbarOptions?.hideAddContext || (
<HoverItem onClick={props.onAddContextItem}>
<AtSymbolIcon
data-tooltip-id="add-context-item-tooltip"
className="h-4 w-4"
/>
<HoverItem onClick={props.onAddContextItem}>
<AtSymbolIcon
data-tooltip-id="add-context-item-tooltip"
className="h-4 w-4"
/>
<ToolTip id="add-context-item-tooltip" place="top-start">
Add context (files, docs, urls, etc.)
</ToolTip>
</HoverItem>
</div>
</div>
<div className="flex items-center gap-2 whitespace-nowrap text-gray-400">
<div className="hidden transition-colors duration-200 hover:underline sm:flex">
{props.activeKey === "Alt" ? (
<HoverItem className="underline">
{`${getAltKeyLabel()}⏎
${useActiveFile ? "No active file" : "Active file"}`}
</HoverItem>
) : (
<HoverItem
className={props.activeKey === "Meta" && "underline"}
onClick={(e) =>
props.onEnter({
useCodebase: true,
noContext: !useActiveFile,
})
}
>
<span data-tooltip-id="add-codebase-context-tooltip">
{getMetaKeyLabel()}⏎ @codebase
</span>
<ToolTip id="add-codebase-context-tooltip" place="top-end">
Submit with the codebase as context ({getMetaKeyLabel()}⏎)
<ToolTip id="add-context-item-tooltip" place="top-start">
Add context (files, docs, urls, etc.)
</ToolTip>
</HoverItem>
)}
</div>
</div>
<div className="flex items-center gap-2 whitespace-nowrap text-gray-400">
{props.toolbarOptions?.hideUseCodebase || (
<div className="hidden transition-colors duration-200 hover:underline sm:flex">
{props.activeKey === "Alt" ? (
<HoverItem className="underline">
{`${getAltKeyLabel()}⏎
${useActiveFile ? "No active file" : "Active file"}`}
</HoverItem>
) : (
<HoverItem
className={props.activeKey === "Meta" && "underline"}
onClick={(e) =>
props.onEnter({
useCodebase: true,
noContext: !useActiveFile,
})
}
>
<span data-tooltip-id="add-codebase-context-tooltip">
{getMetaKeyLabel()}⏎ @codebase
</span>
<ToolTip id="add-codebase-context-tooltip" place="top-end">
Submit with the codebase as context ({getMetaKeyLabel()}⏎)
</ToolTip>
</HoverItem>
)}
</div>
)}
<EnterButton
onClick={(e) => {
@ -178,7 +185,9 @@ function InputToolbar(props: InputToolbarProps) {
}}
disabled={props.disabled}
>
<span className="hidden md:inline">⏎ Enter</span>
<span className="hidden md:inline">
⏎ {props.toolbarOptions?.enterText ?? "Enter"}
</span>
<span className="md:hidden">⏎</span>
</EnterButton>
</div>

View file

@ -0,0 +1,23 @@
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscForeground } from "..";
import { getFontSize } from "../../util";
export const NewSessionButton = styled.div`
width: fit-content;
margin-right: auto;
margin-left: 6px;
margin-top: 2px;
margin-bottom: 8px;
font-size: ${getFontSize() - 2}px;
border-radius: ${defaultBorderRadius};
padding: 2px 6px;
color: ${lightGray};
&:hover {
background-color: ${lightGray}33;
color: ${vscForeground};
}
cursor: pointer;
`;

View file

@ -50,12 +50,14 @@ import {
getFontSize,
isJetBrains,
isMetaEquivalentKeyPressed,
isWebEnvironment,
} from "../../util";
import { handleMetaKeyPressJetBrains } from "../../util/handleMetaKeyPressJetBrains";
import {
handleJetBrainsMetaKeyPress,
handleMetaKeyPress,
} from "./handleMetaKeyPress";
import { CodeBlockExtension } from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
import InputToolbar from "./InputToolbar";
import InputToolbar, { ToolbarOptions } from "./InputToolbar";
import { Mention } from "./MentionExtension";
import "./TipTapEditor.css";
import {
@ -64,20 +66,21 @@ import {
} from "./getSuggestion";
import { ComboBoxItem } from "./types";
const InputBoxDiv = styled.div`
const InputBoxDiv = styled.div<{ border?: string }>`
resize: none;
padding: 8px 12px;
padding-bottom: 4px;
font-family: inherit;
border-radius: ${defaultBorderRadius};
margin: 0;
height: auto;
width: calc(100% - 24px);
width: 100%;
background-color: ${vscInputBackground};
color: ${vscForeground};
border: 0.5px solid ${vscInputBorder};
border: ${(props) =>
props.border ? props.border : `0.5px solid ${vscInputBorder}`};
outline: none;
font-size: ${getFontSize()}px;
&:focus {
outline: none;
@ -92,6 +95,11 @@ const InputBoxDiv = styled.div`
flex-direction: column;
`;
const PaddingDiv = styled.div`
padding: 8px 12px;
padding-bottom: 4px;
`;
const HoverDiv = styled.div`
position: absolute;
width: 100%;
@ -141,8 +149,17 @@ interface TipTapEditorProps {
availableContextProviders: ContextProviderDescription[];
availableSlashCommands: ComboBoxItem[];
isMainInput: boolean;
onEnter: (editorState: JSONContent, modifiers: InputModifiers) => void;
onEnter: (
editorState: JSONContent,
modifiers: InputModifiers,
editor: Editor,
) => void;
editorState?: JSONContent;
toolbarOptions?: ToolbarOptions;
border?: string;
placeholder?: string;
header?: React.ReactNode;
historyKey: string;
}
function TipTapEditor(props: TipTapEditorProps) {
@ -231,8 +248,8 @@ function TipTapEditor(props: TipTapEditorProps) {
const timer = setTimeout(() => {
setHasDefaultModel(
!!defaultModel &&
defaultModel.apiKey !== undefined &&
defaultModel.apiKey !== "",
defaultModel.apiKey !== undefined &&
defaultModel.apiKey !== "",
);
}, 3500);
@ -285,7 +302,7 @@ function TipTapEditor(props: TipTapEditorProps) {
(store: RootState) => store.state.mainEditorContent,
);
const { prevRef, nextRef, addRef } = useInputHistory();
const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey);
function getPlaceholder() {
if (!hasDefaultModel) {
@ -337,7 +354,11 @@ function TipTapEditor(props: TipTapEditorProps) {
},
}),
Placeholder.configure({
placeholder: getPlaceholder,
placeholder:
props.placeholder ??
(historyLengthRef.current === 0
? "Ask anything, '/' for slash commands, '@' to add context"
: "Ask a follow-up"),
}),
Paragraph.extend({
addKeyboardShortcuts() {
@ -429,37 +450,41 @@ function TipTapEditor(props: TipTapEditorProps) {
},
}),
Text,
Mention.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getContextProviderDropdownOptions(
availableContextProvidersRef,
getSubmenuContextItemsRef,
enterSubmenu,
onClose,
onOpen,
inSubmenuRef,
ideMessenger,
),
renderHTML: (props) => {
return `@${props.node.attrs.label || props.node.attrs.id}`;
},
}),
SlashCommand.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
onClose,
onOpen,
ideMessenger,
),
renderText: (props) => {
return props.node.attrs.label;
},
}),
props.availableContextProviders.length
? Mention.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getContextProviderDropdownOptions(
availableContextProvidersRef,
getSubmenuContextItemsRef,
enterSubmenu,
onClose,
onOpen,
inSubmenuRef,
ideMessenger,
),
renderHTML: (props) => {
return `@${props.node.attrs.label || props.node.attrs.id}`;
},
})
: undefined,
props.availableSlashCommands.length
? SlashCommand.configure({
HTMLAttributes: {
class: "mention",
},
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
onClose,
onOpen,
ideMessenger,
),
renderText: (props) => {
return props.node.attrs.label;
},
})
: undefined,
CodeBlockExtension,
],
editorProps: {
@ -539,86 +564,28 @@ function TipTapEditor(props: TipTapEditorProps) {
/**
* This handles various issues with meta key actions
* - In JetBrains, when using "off screen rendering", there is a bug where using the meta key to
* - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to
* highlight code using arrow keys is not working
* - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect
* the actual notebook cells, even when performing them in our GUI
*
* Currently keydown events for a number of keys are not registering if the
* meta/shift key is pressed, for example "x", "c", "v", "z", etc.
* Until this is resolved we can't turn on OSR for non-Mac users due to issues
* with those key actions.
*/
const handleKeyDown = async (e: KeyboardEvent<HTMLDivElement>) => {
if (!editor || !editorFocusedRef.current) return;
if (!editorFocusedRef?.current) return;
setActiveKey(e.key);
// Handle meta key issues
if (isMetaEquivalentKeyPressed(e)) {
const { key, code } = e;
const isWebEnv = isWebEnvironment();
const text = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
if (isJetBrains()) {
if (code === "KeyJ") {
e.stopPropagation();
e.preventDefault();
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
}
if (isMetaEquivalentKeyPressed(e)) {
e.stopPropagation();
e.preventDefault();
handleMetaKeyPressJetBrains(e, text, editor.commands.setContent);
}
} else {
if (code === "KeyL") {
e.stopPropagation();
e.preventDefault();
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
return;
}
switch (key) {
case "x":
e.stopPropagation();
e.preventDefault();
if (isWebEnv) {
await navigator.clipboard.writeText(text);
editor.commands.deleteSelection();
} else {
document.execCommand("cut");
}
break;
case "c":
e.stopPropagation();
e.preventDefault();
if (isWebEnv) {
await navigator.clipboard.writeText(text);
} else {
document.execCommand("copy");
}
break;
case "v":
e.stopPropagation();
e.preventDefault();
if (isWebEnv) {
const clipboardText = await navigator.clipboard.readText();
editor.commands.insertContent(clipboardText);
} else {
document.execCommand("paste");
}
break;
}
handleJetBrainsMetaKeyPress(e, editor);
}
} else if (e.key === "Escape") {
e.stopPropagation();
e.preventDefault();
ideMessenger.post("focusEditor", undefined);
await handleMetaKeyPress(e, editor);
}
};
@ -639,20 +606,16 @@ function TipTapEditor(props: TipTapEditorProps) {
return;
}
props.onEnter(json, modifiers);
props.onEnter(json, modifiers, editor);
if (props.isMainInput) {
const content = editor.state.toJSON().doc;
addRef.current(content);
editor.commands.clearContent(true);
}
},
[props.onEnter, editor, props.isMainInput],
);
// This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview
const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false);
// Re-focus main input after done generating
useEffect(() => {
if (editor && !active && props.isMainInput && document.hasFocus()) {
@ -684,7 +647,7 @@ function TipTapEditor(props: TipTapEditorProps) {
return;
}
if (historyLength > 0) {
saveSession();
await saveSession();
}
setTimeout(() => {
editor?.commands.blur();
@ -713,12 +676,12 @@ function TipTapEditor(props: TipTapEditorProps) {
if (!props.isMainInput) {
return;
}
saveSession();
await saveSession();
setTimeout(() => {
editor?.commands.focus("end");
}, 20);
},
[editor, props.isMainInput],
[editor, props.isMainInput, saveSession],
);
useWebviewListener(
@ -727,71 +690,67 @@ function TipTapEditor(props: TipTapEditorProps) {
if (!props.isMainInput || !editor) {
return;
}
if (!ignoreHighlightedCode) {
const rif: RangeInFile & { contents: string } =
data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const relativePath = getRelativePath(
rif.filepath,
await ideMessenger.ide.getWorkspaceDirs(),
);
const rangeStr = `(${rif.range.start.line + 1}-${
rif.range.end.line + 1
const rif: RangeInFile & { contents: string } =
data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const relativePath = getRelativePath(
rif.filepath,
await ideMessenger.ide.getWorkspaceDirs(),
);
const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1
})`;
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} ${rangeStr}`,
// Description is passed on to the LLM to give more context on file path
description: `${relativePath} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: v4(),
},
uri: {
type: "file",
value: rif.filepath,
},
};
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} ${rangeStr}`,
// Description is passed on to the LLM to give more context on file path
description: `${relativePath} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: v4(),
},
uri: {
type: "file",
value: rif.filepath,
},
};
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.run();
if (data.prompt) {
editor.commands.focus("end");
editor.commands.insertContent(data.prompt);
}
if (data.shouldRun) {
onEnterRef.current({ useCodebase: false, noContext: true });
}
setTimeout(() => {
editor.commands.blur();
editor.commands.focus("end");
}, 20);
}
setIgnoreHighlightedCode(false);
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.run();
if (data.prompt) {
editor.commands.focus("end");
editor.commands.insertContent(data.prompt);
}
if (data.shouldRun) {
onEnterRef.current({ useCodebase: false, noContext: true });
}
setTimeout(() => {
editor.commands.blur();
editor.commands.focus("end");
}, 20);
},
[
editor,
props.isMainInput,
historyLength,
ignoreHighlightedCode,
props.isMainInput,
onEnterRef.current,
],
@ -859,6 +818,7 @@ function TipTapEditor(props: TipTapEditorProps) {
return (
<InputBoxDiv
border={props.border}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
className="cursor-text"
@ -903,31 +863,36 @@ function TipTapEditor(props: TipTapEditorProps) {
event.preventDefault();
}}
>
<EditorContent
spellCheck={false}
editor={editor}
onClick={(event) => {
event.stopPropagation();
}}
/>
<InputToolbar
activeKey={activeKey}
hidden={shouldHideToolbar && !props.isMainInput}
onAddContextItem={() => insertCharacterWithWhitespace("@")}
onAddSlashCommand={() => insertCharacterWithWhitespace("/")}
onEnter={onEnterRef.current}
onImageFileSelected={(file) => {
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = editor.state;
const node = schema.nodes.image.create({ src: dataUrl });
editor.commands.command(({ tr }) => {
tr.insert(0, node);
return true;
<div>{props.header}</div>
<PaddingDiv>
<EditorContent
spellCheck={false}
editor={editor}
onClick={(event) => {
event.stopPropagation();
}}
/>
<InputToolbar
toolbarOptions={props.toolbarOptions}
activeKey={activeKey}
hidden={shouldHideToolbar && !props.isMainInput}
onAddContextItem={() => insertCharacterWithWhitespace("@")}
onAddSlashCommand={() => insertCharacterWithWhitespace("/")}
onEnter={onEnterRef.current}
onImageFileSelected={(file) => {
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = editor.state;
const node = schema.nodes.image.create({ src: dataUrl });
editor.commands.command(({ tr }) => {
tr.insert(0, node);
return true;
});
});
});
}}
disabled={active}
/>
}}
disabled={active}
/>
</PaddingDiv>
{showDragOverMsg &&
modelSupportsImages(

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