Dev (#1678)
* Fix an issue where CMD+K does not clear the terminal when the terminal has focus (#1671) On MacOS, ⌘+K is bound, by default, to Terminal:Clear. Without this change ⌘+K does not clear the terminal but instead iniates a chord sequence and waits for the next stroke of the chord. Co-authored-by: Rob Leidle <rleidle@tesla.com> * Change treeSitter to cache the Language objects it loads from wasm (#1672) Without this change, for a repository with 600 typescript files, the indexer would fail to finish correctly and there would be many of the following errors in the webview console log: 'Unable to load language for file ${path} RuntimeError: table index is out of bounds' The following bash will create a repo that reproduces the problem: current_path="." for ((i=1; i<=20; i++)); do new_folder="folder-$i" mkdir -p "$current_path/$new_folder" current_path="$current_path/$new_folder" for ((a=1; a<=30; a++)); do head -c 10000 /dev/urandom | base64 > "$current_path/file-$a.ts" done done Co-authored-by: Rob Leidle <rleidle@tesla.com> * acknowledge sourcemap flag in esbuild.js * don't run jetbrains-release.yaml on vscode releases * further testing for walkDir * chore: add telemetry to commands (#1673) * test: Add basic unit test to baseLLM (#1668) * update version * test: Add basic unit test to baseLLM --------- Co-authored-by: Nate Sesti <sestinj@gmail.com> Co-authored-by: inimaz <imaz@ai-verse.com> * feat: add Quick Actions CodeLens feature (#1674) * docs: add docs and schema for "OS" provider (#1536) * ignore .env * ✨ use and cache imports for autocomplete (#1456) * ✨ use and cache imports for autocomplete * fix tsc * add voyage rerank-1 * import Handlebars * feat: open pane on install (#1564) * feat: open pane on activation * comment out testing code * chore: add telemetry for pageviews (#1576) * feat: update onboarding w/ embeddings model (#1570) * chore(gui): remove unused pages * feat: add embeddings step * feat: update styles * feat: copy button updates * fix: correct pull command for embed model * fix: remove commented code * fix: remove commented code * feat: simplify copy btn props * chore: rename onboarding selection event * feat: add provider config * fix: undo msg name * remove dead code * fix: invalid mode check * fix: remove testing logic * fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582) * small UI tweaks * media query * feat: add best experience onboarding * small fixes * feat: add free trial card to onboarding (#1600) * feat: add free trial card to onboarding * add import * chore: add telemetry for full screen toggle (#1618) * rerank-lite-1 * remove doccs * basic tests for VS Code extension * improved testing of VS Code extension * manually implement stop tokens for hf inference api * chore: onboarding metrics (#1626) * fix: pageview tracking * feat: add onboarding telemetry * create single `onboardingStatus` type * improved var naming * remove console logs * fix windows performance issue * rename vscodeExtension.ts * migration of onboarding variables * "stash" instead of "delete" in indexing progress * fix preview.yaml * also fix main.yaml * Update troubleshooting.md (#1637) * feat: add quick actions * Update index.d.ts * quick actions mvp * update docs * subscribe to vscode change settings * Update commands.ts * cleanup * Update quick-actions.md * Update VerticalPerLineCodeLensProvider.ts * resolve feedback --------- Co-authored-by: Nate Sesti <sestinj@gmail.com> Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com> Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com> * chore: add `isCommandEvent` to command telemetry (#1675) * chore: add `isCommandEvent` to command telemetry * Update commands.ts * Nate/better retrieval (#1677) * deduplicatearray tests * break out separate retrieval pipelines * IConfigHandler * tests for codebase indexer * better .continueignore for continue * indexing fixes * ignore .gitignore and .continueignore when indexing * retrieval pipeline improvements * fix formatting err in out .continueignore * add necessary filter to lance_db_cache * update package.json version --------- Co-authored-by: Rob Leidle <rleidle@gmail.com> Co-authored-by: Rob Leidle <rleidle@tesla.com> Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com> Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com> Co-authored-by: inimaz <imaz@ai-verse.com> Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
This commit is contained in:
parent
8858bfb7fe
commit
f72b00d38d
71 changed files with 2035 additions and 713 deletions
|
|
@ -1,4 +1,7 @@
|
|||
**/*.run.xml
|
||||
archive/**/*
|
||||
extensions/vscode/models/**/*
|
||||
docs/docs/languages
|
||||
docs/docs/languages
|
||||
.changes/
|
||||
.idea/
|
||||
.vscode/
|
||||
.archive/
|
||||
**/*.scm
|
||||
15
.github/workflows/jetbrains-release.yaml
vendored
15
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -12,8 +12,23 @@ defaults:
|
|||
working-directory: ./extensions/intellij
|
||||
|
||||
jobs:
|
||||
check_release_name:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
should_run: ${{ steps.check.outputs.should_run }}
|
||||
steps:
|
||||
- id: check
|
||||
run: |
|
||||
if [[ "${{ github.event.release.name }}" == *-jetbrains ]]; then
|
||||
echo "should_run=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "should_run=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
# Prepare and publish the plugin to JetBrains Marketplace repository
|
||||
release:
|
||||
needs: check_release_name
|
||||
if: needs.check_release_name.outputs.should_run == 'true'
|
||||
name: Publish Plugin
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
|
|
|
|||
|
|
@ -1 +1,2 @@
|
|||
extensions/vscode/continue_rc_schema.json
|
||||
extensions/vscode/continue_rc_schema.json
|
||||
**/.continueignore
|
||||
|
|
@ -73,7 +73,11 @@ describe("Test Suite", () => {
|
|||
);
|
||||
}
|
||||
|
||||
const ide = new FileSystemIde();
|
||||
const testDir = path.join(__dirname, "..", ".test");
|
||||
if (!fs.existsSync(testDir)) {
|
||||
fs.mkdirSync(testDir);
|
||||
}
|
||||
const ide = new FileSystemIde(testDir);
|
||||
const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide);
|
||||
|
||||
// Wait for core to set itself up
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import OpenAI from "openai";
|
|||
import path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { ConfigHandler } from "../config/handler.js";
|
||||
import { IConfigHandler } from "../config/IConfigHandler.js";
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import { streamLines } from "../diff/util.js";
|
||||
import {
|
||||
|
|
@ -145,7 +145,7 @@ export class CompletionProvider {
|
|||
private static lastUUID: string | undefined = undefined;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly configHandler: IConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly getLlm: () => Promise<ILLM | undefined>,
|
||||
private readonly _onError: (e: any) => void,
|
||||
|
|
|
|||
|
|
@ -8,9 +8,10 @@ import {
|
|||
ILLM,
|
||||
} from "../index.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { IConfigHandler } from "./IConfigHandler.js";
|
||||
import { finalToBrowserConfig, loadFullConfigNode } from "./load.js";
|
||||
|
||||
export class ConfigHandler {
|
||||
export class ConfigHandler implements IConfigHandler {
|
||||
private savedConfig: ContinueConfig | undefined;
|
||||
private savedBrowserConfig?: BrowserSerializedContinueConfig;
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
|
|
@ -35,8 +36,8 @@ export class ConfigHandler {
|
|||
this.reloadConfig();
|
||||
}
|
||||
|
||||
private updateListeners: (() => void)[] = [];
|
||||
onConfigUpdate(listener: () => void) {
|
||||
private updateListeners: ((newConfig: ContinueConfig) => void)[] = [];
|
||||
onConfigUpdate(listener: (newConfig: ContinueConfig) => void) {
|
||||
this.updateListeners.push(listener);
|
||||
}
|
||||
|
||||
|
|
@ -45,10 +46,10 @@ export class ConfigHandler {
|
|||
this.savedBrowserConfig = undefined;
|
||||
this._pendingConfigPromise = undefined;
|
||||
|
||||
await this.loadConfig();
|
||||
const newConfig = await this.loadConfig();
|
||||
|
||||
for (const listener of this.updateListeners) {
|
||||
listener();
|
||||
listener(newConfig);
|
||||
}
|
||||
}
|
||||
|
||||
17
core/config/IConfigHandler.ts
Normal file
17
core/config/IConfigHandler.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContinueConfig,
|
||||
IContextProvider,
|
||||
IdeSettings,
|
||||
ILLM,
|
||||
} from "../index.js";
|
||||
|
||||
export interface IConfigHandler {
|
||||
updateIdeSettings(ideSettings: IdeSettings): void;
|
||||
onConfigUpdate(listener: (newConfig: ContinueConfig) => void): void;
|
||||
reloadConfig(): Promise<void>;
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
|
||||
loadConfig(): Promise<ContinueConfig>;
|
||||
llmFromTitle(title?: string): Promise<ILLM>;
|
||||
registerCustomContextProvider(contextProvider: IContextProvider): void;
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { BranchAndDir, Chunk } from "../../index.js";
|
||||
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch.js";
|
||||
|
||||
export async function retrieveFts(
|
||||
query: string,
|
||||
n: number,
|
||||
|
|
|
|||
59
core/context/retrieval/pipelines/BaseRetrievalPipeline.ts
Normal file
59
core/context/retrieval/pipelines/BaseRetrievalPipeline.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import {
|
||||
BranchAndDir,
|
||||
Chunk,
|
||||
EmbeddingsProvider,
|
||||
IDE,
|
||||
Reranker,
|
||||
} from "../../..";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
|
||||
import { retrieveFts } from "../fullTextSearch";
|
||||
|
||||
export interface RetrievalPipelineOptions {
|
||||
ide: IDE;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
reranker: Reranker | undefined;
|
||||
|
||||
input: string;
|
||||
nRetrieve: number;
|
||||
nFinal: number;
|
||||
tags: BranchAndDir[];
|
||||
filterDirectory?: string;
|
||||
}
|
||||
|
||||
export interface IRetrievalPipeline {
|
||||
run(options: RetrievalPipelineOptions): Promise<Chunk[]>;
|
||||
}
|
||||
|
||||
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
||||
private lanceDbIndex: LanceDbIndex;
|
||||
constructor(protected readonly options: RetrievalPipelineOptions) {
|
||||
this.lanceDbIndex = new LanceDbIndex(options.embeddingsProvider, (path) =>
|
||||
options.ide.readFile(path),
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
): Promise<Chunk[]> {
|
||||
return this.lanceDbIndex.retrieve(
|
||||
input,
|
||||
n,
|
||||
this.options.tags,
|
||||
this.options.filterDirectory,
|
||||
);
|
||||
}
|
||||
|
||||
run(): Promise<Chunk[]> {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import { Chunk } from "../../..";
|
||||
import { deduplicateChunks } from "../util";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline";
|
||||
|
||||
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
||||
async run(): Promise<Chunk[]> {
|
||||
const { input } = this.options;
|
||||
|
||||
// Get all retrieval results
|
||||
const retrievalResults: Chunk[] = [];
|
||||
|
||||
// Full-text search
|
||||
const ftsResults = await this.retrieveFts(input, this.options.nFinal / 2);
|
||||
retrievalResults.push(...ftsResults);
|
||||
|
||||
// Embeddings
|
||||
const embeddingResults = await this.retrieveEmbeddings(
|
||||
input,
|
||||
this.options.nFinal / 2,
|
||||
);
|
||||
retrievalResults.push(...embeddingResults);
|
||||
|
||||
const finalResults: Chunk[] = deduplicateChunks(retrievalResults);
|
||||
return finalResults;
|
||||
}
|
||||
}
|
||||
125
core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts
Normal file
125
core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import { Chunk } from "../../..";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
|
||||
import { deduplicateChunks } from "../util";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline";
|
||||
|
||||
export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
||||
private async _retrieveInitial(): Promise<Chunk[]> {
|
||||
const { input, nRetrieve } = this.options;
|
||||
|
||||
// Get all retrieval results
|
||||
const retrievalResults: Chunk[] = [];
|
||||
|
||||
// Full-text search
|
||||
const ftsResults = await this.retrieveFts(input, nRetrieve / 2);
|
||||
retrievalResults.push(...ftsResults);
|
||||
|
||||
// Embeddings
|
||||
const embeddingResults = await this.retrieveEmbeddings(input, nRetrieve);
|
||||
retrievalResults.push(
|
||||
...embeddingResults.slice(0, nRetrieve - ftsResults.length),
|
||||
);
|
||||
|
||||
const results: Chunk[] = deduplicateChunks(retrievalResults);
|
||||
return results;
|
||||
}
|
||||
|
||||
private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> {
|
||||
if (!this.options.reranker) {
|
||||
throw new Error("No reranker provided");
|
||||
}
|
||||
|
||||
let scores: number[] = await this.options.reranker.rerank(input, chunks);
|
||||
|
||||
// Filter out low-scoring results
|
||||
let results = chunks;
|
||||
// let results = chunks.filter(
|
||||
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
// );
|
||||
// scores = scores.filter(
|
||||
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
// );
|
||||
|
||||
results.sort(
|
||||
(a, b) => scores[results.indexOf(a)] - scores[results.indexOf(b)],
|
||||
);
|
||||
results = results.slice(-this.options.nFinal);
|
||||
return results;
|
||||
}
|
||||
|
||||
private async _expandWithEmbeddings(chunks: Chunk[]): Promise<Chunk[]> {
|
||||
const topResults = chunks.slice(
|
||||
-RETRIEVAL_PARAMS.nResultsToExpandWithEmbeddings,
|
||||
);
|
||||
|
||||
const expanded = await Promise.all(
|
||||
topResults.map(async (chunk, i) => {
|
||||
const results = await this.retrieveEmbeddings(
|
||||
chunk.content,
|
||||
RETRIEVAL_PARAMS.nEmbeddingsExpandTo,
|
||||
);
|
||||
return results;
|
||||
}),
|
||||
);
|
||||
return expanded.flat();
|
||||
}
|
||||
|
||||
private async _expandRankedResults(chunks: Chunk[]): Promise<Chunk[]> {
|
||||
let results: Chunk[] = [];
|
||||
|
||||
const embeddingsResults = await this._expandWithEmbeddings(chunks);
|
||||
results.push(...embeddingsResults);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async run(): Promise<Chunk[]> {
|
||||
// Retrieve initial results
|
||||
let results = await this._retrieveInitial();
|
||||
|
||||
// Rerank
|
||||
const { input } = this.options;
|
||||
results = await this._rerank(input, results);
|
||||
|
||||
// // // Expand top reranked results
|
||||
// const expanded = await this._expandRankedResults(results);
|
||||
// results.push(...expanded);
|
||||
|
||||
// // De-duplicate
|
||||
// results = deduplicateChunks(results);
|
||||
|
||||
// // Rerank again
|
||||
// results = await this._rerank(input, results);
|
||||
|
||||
// TODO: stitch together results
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
// Source: expansion with code graph
|
||||
// consider doing this after reranking? Or just having a lower reranking threshold
|
||||
// This is VS Code only until we use PSI for JetBrains or build our own general solution
|
||||
// TODO: Need to pass in the expandSnippet function as a function argument
|
||||
// because this import causes `tsc` to fail
|
||||
// if ((await extras.ide.getIdeInfo()).ideType === "vscode") {
|
||||
// const { expandSnippet } = await import(
|
||||
// "../../../extensions/vscode/src/util/expandSnippet"
|
||||
// );
|
||||
// let expansionResults = (
|
||||
// await Promise.all(
|
||||
// extras.selectedCode.map(async (rif) => {
|
||||
// return expandSnippet(
|
||||
// rif.filepath,
|
||||
// rif.range.start.line,
|
||||
// rif.range.end.line,
|
||||
// extras.ide,
|
||||
// );
|
||||
// }),
|
||||
// )
|
||||
// ).flat() as Chunk[];
|
||||
// retrievalResults.push(...expansionResults);
|
||||
// }
|
||||
|
||||
// Source: Open file exact match
|
||||
// Source: Class/function name exact match
|
||||
|
|
@ -1,24 +1,14 @@
|
|||
import {
|
||||
BranchAndDir,
|
||||
Chunk,
|
||||
ContextItem,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { LanceDbIndex } from "../../indexing/LanceDbIndex.js";
|
||||
|
||||
import { deduplicateArray, getRelativePath } from "../../util/index.js";
|
||||
import { getRelativePath } from "../../util/index.js";
|
||||
import { RETRIEVAL_PARAMS } from "../../util/parameters.js";
|
||||
import { retrieveFts } from "./fullTextSearch.js";
|
||||
|
||||
function deduplicateChunks(chunks: Chunk[]): Chunk[] {
|
||||
return deduplicateArray(chunks, (a, b) => {
|
||||
return (
|
||||
a.filepath === b.filepath &&
|
||||
a.startLine === b.startLine &&
|
||||
a.endLine === b.endLine
|
||||
);
|
||||
});
|
||||
}
|
||||
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js";
|
||||
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js";
|
||||
import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline.js";
|
||||
|
||||
export async function retrieveContextItemsFromEmbeddings(
|
||||
extras: ContextProviderExtras,
|
||||
|
|
@ -66,80 +56,21 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
branch: branches[i],
|
||||
}));
|
||||
|
||||
// Get all retrieval results
|
||||
const retrievalResults: Chunk[] = [];
|
||||
|
||||
// Source: Full-text search
|
||||
const ftsResults = await retrieveFts(
|
||||
extras.fullInput,
|
||||
nRetrieve / 2,
|
||||
tags,
|
||||
filterDirectory,
|
||||
);
|
||||
retrievalResults.push(...ftsResults);
|
||||
|
||||
// Source: expansion with code graph
|
||||
// consider doing this after reranking? Or just having a lower reranking threshold
|
||||
// This is VS Code only until we use PSI for JetBrains or build our own general solution
|
||||
// TODO: Need to pass in the expandSnippet function as a function argument
|
||||
// because this import causes `tsc` to fail
|
||||
// if ((await extras.ide.getIdeInfo()).ideType === "vscode") {
|
||||
// const { expandSnippet } = await import(
|
||||
// "../../../extensions/vscode/src/util/expandSnippet"
|
||||
// );
|
||||
// let expansionResults = (
|
||||
// await Promise.all(
|
||||
// extras.selectedCode.map(async (rif) => {
|
||||
// return expandSnippet(
|
||||
// rif.filepath,
|
||||
// rif.range.start.line,
|
||||
// rif.range.end.line,
|
||||
// extras.ide,
|
||||
// );
|
||||
// }),
|
||||
// )
|
||||
// ).flat() as Chunk[];
|
||||
// retrievalResults.push(...expansionResults);
|
||||
// }
|
||||
|
||||
// Source: Open file exact match
|
||||
// Source: Class/function name exact match
|
||||
|
||||
// Source: Embeddings
|
||||
const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) =>
|
||||
extras.ide.readFile(path),
|
||||
);
|
||||
const vecResults = await lanceDbIndex.retrieve(
|
||||
extras.fullInput,
|
||||
const pipelineType = useReranking
|
||||
? RerankerRetrievalPipeline
|
||||
: NoRerankerRetrievalPipeline;
|
||||
const pipelineOptions: RetrievalPipelineOptions = {
|
||||
nFinal,
|
||||
nRetrieve,
|
||||
tags,
|
||||
embeddingsProvider: extras.embeddingsProvider,
|
||||
reranker: extras.reranker,
|
||||
filterDirectory,
|
||||
);
|
||||
retrievalResults.push(...vecResults);
|
||||
|
||||
// De-duplicate
|
||||
let results: Chunk[] = deduplicateChunks(retrievalResults);
|
||||
|
||||
// Re-rank
|
||||
if (useReranking && extras.reranker) {
|
||||
let scores: number[] = await extras.reranker.rerank(
|
||||
extras.fullInput,
|
||||
results,
|
||||
);
|
||||
|
||||
// Filter out low-scoring results
|
||||
results = results.filter(
|
||||
(_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
);
|
||||
scores = scores.filter(
|
||||
(score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
);
|
||||
|
||||
results.sort(
|
||||
(a, b) => scores[results.indexOf(a)] - scores[results.indexOf(b)],
|
||||
);
|
||||
results = results.slice(-nFinal);
|
||||
}
|
||||
ide: extras.ide,
|
||||
input: extras.fullInput,
|
||||
};
|
||||
const pipeline = new pipelineType(pipelineOptions);
|
||||
const results = await pipeline.run();
|
||||
|
||||
if (results.length === 0) {
|
||||
throw new Error(
|
||||
|
|
|
|||
12
core/context/retrieval/util.ts
Normal file
12
core/context/retrieval/util.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { Chunk } from "../..";
|
||||
import { deduplicateArray } from "../../util";
|
||||
|
||||
export function deduplicateChunks(chunks: Chunk[]): Chunk[] {
|
||||
return deduplicateArray(chunks, (a, b) => {
|
||||
return (
|
||||
a.filepath === b.filepath &&
|
||||
a.startLine === b.startLine &&
|
||||
a.endLine === b.endLine
|
||||
);
|
||||
});
|
||||
}
|
||||
15
core/core.ts
15
core/core.ts
|
|
@ -6,7 +6,8 @@ import type {
|
|||
SiteIndexingConfig,
|
||||
} from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider.js";
|
||||
import { ConfigHandler } from "./config/handler.js";
|
||||
import { ConfigHandler } from "./config/ConfigHandler.js";
|
||||
import { IConfigHandler } from "./config/IConfigHandler";
|
||||
import {
|
||||
setupApiKeysMode,
|
||||
setupFreeTrialMode,
|
||||
|
|
@ -16,9 +17,9 @@ import {
|
|||
import { createNewPromptFile } from "./config/promptFile.js";
|
||||
import { addModel, addOpenAIKey, deleteModel } from "./config/util.js";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client.js";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js";
|
||||
import { DocsService } from "./indexing/docs/DocsService";
|
||||
import TransformersJsEmbeddingsProvider from "./indexing/embeddings/TransformersJsEmbeddingsProvider.js";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/indexCodebase.js";
|
||||
import Ollama from "./llm/llms/Ollama.js";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { GlobalContext } from "./util/GlobalContext.js";
|
||||
|
|
@ -33,7 +34,7 @@ import { streamDiffLines } from "./util/verticalEdit.js";
|
|||
|
||||
export class Core {
|
||||
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
|
||||
configHandler: ConfigHandler;
|
||||
configHandler: IConfigHandler;
|
||||
codebaseIndexerPromise: Promise<CodebaseIndexer>;
|
||||
completionProvider: CompletionProvider;
|
||||
continueServerClientPromise: Promise<ContinueServerClient>;
|
||||
|
|
@ -286,7 +287,7 @@ export class Core {
|
|||
});
|
||||
|
||||
async function* llmStreamChat(
|
||||
configHandler: ConfigHandler,
|
||||
configHandler: IConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
|
||||
) {
|
||||
|
|
@ -321,7 +322,7 @@ export class Core {
|
|||
);
|
||||
|
||||
async function* llmStreamComplete(
|
||||
configHandler: ConfigHandler,
|
||||
configHandler: IConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
|
||||
msg: Message<ToCoreProtocol["llm/streamComplete"][0]>,
|
||||
|
|
@ -387,7 +388,7 @@ export class Core {
|
|||
});
|
||||
|
||||
async function* runNodeJsSlashCommand(
|
||||
configHandler: ConfigHandler,
|
||||
configHandler: IConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["command/run"][0]>,
|
||||
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
|
|
@ -476,7 +477,7 @@ export class Core {
|
|||
});
|
||||
|
||||
async function* streamDiffLinesGenerator(
|
||||
configHandler: ConfigHandler,
|
||||
configHandler: IConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
) {
|
||||
|
|
|
|||
31
core/index.d.ts
vendored
31
core/index.d.ts
vendored
|
|
@ -807,11 +807,42 @@ interface ModelRoles {
|
|||
applyCodeBlock?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the configuration for a quick action in the Code Lens.
|
||||
* Quick actions are custom commands that can be added to function and class declarations.
|
||||
*/
|
||||
interface QuickActionConfig {
|
||||
/**
|
||||
* The title of the quick action that will display in the Code Lens.
|
||||
*/
|
||||
title: string;
|
||||
|
||||
/**
|
||||
* The prompt that will be sent to the model when the quick action is invoked,
|
||||
* with the function or class body concatenated.
|
||||
*/
|
||||
prompt: string;
|
||||
|
||||
/**
|
||||
* If `true`, the result of the quick action will be sent to the chat panel.
|
||||
* If `false`, the streamed result will be inserted into the document.
|
||||
*
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
sendToChat: boolean;
|
||||
}
|
||||
|
||||
interface ExperimentalConfig {
|
||||
contextMenuPrompts?: ContextMenuConfig;
|
||||
modelRoles?: ModelRoles;
|
||||
defaultContext?: "activeFile"[];
|
||||
promptPath?: string;
|
||||
|
||||
/**
|
||||
* Quick actions are a way to add custom commands to the Code Lens of
|
||||
* function and class declarations.
|
||||
*/
|
||||
quickActions?: QuickActionConfig[];
|
||||
}
|
||||
|
||||
// config.json
|
||||
|
|
|
|||
|
|
@ -116,7 +116,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
}
|
||||
|
||||
yield {
|
||||
desc: `Indexing ${compute.path}`,
|
||||
desc: `Indexing ${getBasename(compute.path)}`,
|
||||
progress: i / results.compute.length,
|
||||
status: "indexing",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigHandler } from "../config/handler.js";
|
||||
import { IConfigHandler } from "../config/IConfigHandler.js";
|
||||
import { IContinueServerClient } from "../continueServer/interface.js";
|
||||
import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js";
|
||||
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
|
||||
|
|
@ -23,7 +23,7 @@ export class PauseToken {
|
|||
|
||||
export class CodebaseIndexer {
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly configHandler: IConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly pauseToken: PauseToken,
|
||||
private readonly continueServerClient: IContinueServerClient,
|
||||
|
|
@ -4,6 +4,7 @@ import {
|
|||
IndexTag,
|
||||
IndexingProgressUpdate,
|
||||
} from "../index.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
import { RETRIEVAL_PARAMS } from "../util/parameters.js";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
|
||||
|
|
@ -71,7 +72,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
yield {
|
||||
progress: i / results.compute.length,
|
||||
desc: `Indexing ${item.path}`,
|
||||
desc: `Indexing ${getBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
markComplete([item], IndexResultType.Compute);
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
} from "../index.js";
|
||||
import { MAX_CHUNK_SIZE } from "../llm/constants.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
import { getLanceDbPath } from "../util/paths.js";
|
||||
import { getLanceDbPath, migrate } from "../util/paths.js";
|
||||
import { chunkDocument } from "./chunk/chunk.js";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
|
||||
import {
|
||||
|
|
@ -53,11 +53,25 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
uuid TEXT PRIMARY KEY,
|
||||
cacheKey TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
artifact_id TEXT NOT NULL,
|
||||
vector TEXT NOT NULL,
|
||||
startLine INTEGER NOT NULL,
|
||||
endLine INTEGER NOT NULL,
|
||||
contents TEXT NOT NULL
|
||||
)`);
|
||||
|
||||
await new Promise((resolve) =>
|
||||
migrate(
|
||||
"lancedb_sqlite_artifact_id_column",
|
||||
async () => {
|
||||
await db.exec(
|
||||
`ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'`,
|
||||
);
|
||||
resolve(undefined);
|
||||
},
|
||||
() => resolve(undefined),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async *computeChunks(
|
||||
|
|
@ -231,10 +245,11 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
rows.push(row);
|
||||
|
||||
await sqlite.run(
|
||||
"INSERT INTO lance_db_cache (uuid, cacheKey, path, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
row.uuid,
|
||||
row.cachekey,
|
||||
row.path,
|
||||
this.artifactId,
|
||||
JSON.stringify(row.vector),
|
||||
chunk.startLine,
|
||||
chunk.endLine,
|
||||
|
|
@ -265,10 +280,11 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
|
||||
// Add the computed row to the cache
|
||||
await sqlite.run(
|
||||
"INSERT INTO lance_db_cache (uuid, cacheKey, path, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
row.uuid,
|
||||
row.cachekey,
|
||||
row.path,
|
||||
this.artifactId,
|
||||
JSON.stringify(row.vector),
|
||||
data.startLine,
|
||||
data.endLine,
|
||||
|
|
@ -290,9 +306,10 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
// Add tag - retrieve the computed info from lance sqlite cache
|
||||
for (const { path, cacheKey } of results.addTag) {
|
||||
const stmt = await sqlite.prepare(
|
||||
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ?",
|
||||
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
|
||||
cacheKey,
|
||||
path,
|
||||
this.artifactId,
|
||||
);
|
||||
const cachedItems = await stmt.all();
|
||||
|
||||
|
|
@ -347,9 +364,10 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
// Delete - also remove from sqlite cache
|
||||
for (const { path, cacheKey } of results.del) {
|
||||
await sqlite.run(
|
||||
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ?",
|
||||
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
|
||||
cacheKey,
|
||||
path,
|
||||
this.artifactId,
|
||||
);
|
||||
accumulatedProgress += 1 / results.del.length / 3;
|
||||
yield {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
|
|||
...options,
|
||||
};
|
||||
this.fetch = fetch;
|
||||
this.id = this.options.model || this.constructor.name;
|
||||
this.id = `${this.constructor.name}::${this.options.model}`;
|
||||
}
|
||||
|
||||
abstract embed(chunks: string[]): Promise<number[][]>;
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
constructor(options: EmbedOptions, fetch: FetchFunction) {
|
||||
super(options, fetch);
|
||||
this.options.model = FreeTrialEmbeddingsProvider.defaultOptions?.model;
|
||||
this.id = this.options.model || this.constructor.name;
|
||||
this.id = `${this.constructor.name}::${this.options.model}`;
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
|
|
|
|||
|
|
@ -60,6 +60,11 @@ export const DEFAULT_IGNORE_FILETYPES = [
|
|||
"*.gcno",
|
||||
"go.sum",
|
||||
".env",
|
||||
".gitignore",
|
||||
".gitkeep",
|
||||
".continueignore",
|
||||
"config.json",
|
||||
"*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
|
||||
];
|
||||
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
|
||||
export const DEFAULT_IGNORE_DIRS = [
|
||||
|
|
@ -85,6 +90,7 @@ export const DEFAULT_IGNORE_DIRS = [
|
|||
".gradle",
|
||||
".cache",
|
||||
"gems",
|
||||
"vendor",
|
||||
];
|
||||
export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
|
||||
|
||||
|
|
|
|||
|
|
@ -19,4 +19,5 @@ export default {
|
|||
__dirname: path.dirname(fileURLToPath(import.meta.url)),
|
||||
__filename: path.resolve(fileURLToPath(import.meta.url)),
|
||||
},
|
||||
globalSetup: "<rootDir>/jest.global-setup.ts",
|
||||
};
|
||||
|
|
|
|||
6
core/jest.global-setup.ts
Normal file
6
core/jest.global-setup.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
// jest.global-setup.js
|
||||
import path from "path";
|
||||
|
||||
export default async function () {
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
|
||||
}
|
||||
1
core/test/.gitignore
vendored
Normal file
1
core/test/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
scratch.test.ts
|
||||
6
core/test/_testEnv.test.ts
Normal file
6
core/test/_testEnv.test.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
describe("Test environment", () => {
|
||||
test("should have CONTINUE_GLOBAL_DIR env var set to .continue-test", () => {
|
||||
expect(process.env.CONTINUE_GLOBAL_DIR).toBeDefined();
|
||||
expect(process.env.CONTINUE_GLOBAL_DIR)?.toMatch(/\.continue-test$/);
|
||||
});
|
||||
});
|
||||
140
core/test/baseLLM.test.ts
Normal file
140
core/test/baseLLM.test.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import { ChatMessage, LLMOptions, ModelProvider } from "../index";
|
||||
import { BaseLLM } from "../llm/index.js";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
static providerName: ModelProvider = "openai";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "dummy-model",
|
||||
contextLength: 200_000,
|
||||
completionOptions: {
|
||||
model: "some-model",
|
||||
maxTokens: 4096,
|
||||
},
|
||||
apiBase: "https://api.test-api-dummy.com/v1/",
|
||||
};
|
||||
}
|
||||
describe("BaseLLM", () => {
|
||||
let baseLLM: BaseLLM;
|
||||
|
||||
beforeEach(() => {
|
||||
const options: LLMOptions = {
|
||||
model: "dummy-model",
|
||||
};
|
||||
// Instantiate a DummyLLM instance
|
||||
baseLLM = new DummyLLM(options);
|
||||
});
|
||||
|
||||
describe("BaseLLM constructor", () => {
|
||||
it("should correctly initialize with given options", () => {
|
||||
const templatMessagesFunction = (messages: ChatMessage[]) => {
|
||||
return messages[0]?.content.toString() ?? "";
|
||||
};
|
||||
const writeLogFunction = async () => {};
|
||||
const options: LLMOptions = {
|
||||
model: "gpt-3.5-turbo",
|
||||
uniqueId: "testId",
|
||||
systemMessage: "Test System Message",
|
||||
contextLength: 1024,
|
||||
completionOptions: {
|
||||
model: "some-model",
|
||||
maxTokens: 150,
|
||||
},
|
||||
requestOptions: {},
|
||||
promptTemplates: {},
|
||||
templateMessages: templatMessagesFunction,
|
||||
writeLog: writeLogFunction,
|
||||
llmRequestHook: () => {},
|
||||
apiKey: "testApiKey",
|
||||
aiGatewaySlug: "testSlug",
|
||||
apiBase: "https://api.example.com",
|
||||
accountId: "testAccountId",
|
||||
engine: "davinci",
|
||||
apiVersion: "v1",
|
||||
apiType: "public",
|
||||
region: "us",
|
||||
projectId: "testProjectId",
|
||||
};
|
||||
|
||||
const instance = new DummyLLM(options);
|
||||
|
||||
expect(instance.title).toBeDefined();
|
||||
expect(instance.uniqueId).toBe("testId");
|
||||
expect(instance.model).toBe("gpt-3.5-turbo");
|
||||
expect(instance.systemMessage).toBe("Test System Message");
|
||||
expect(instance.contextLength).toBe(1024);
|
||||
expect(instance.completionOptions.maxTokens).toBe(150);
|
||||
expect(instance.requestOptions).toEqual({});
|
||||
expect(instance.promptTemplates).toEqual({});
|
||||
expect(instance.templateMessages).toEqual(templatMessagesFunction);
|
||||
expect(instance.writeLog).toBe(writeLogFunction);
|
||||
expect(instance.apiKey).toBe("testApiKey");
|
||||
expect(instance.aiGatewaySlug).toBe("testSlug");
|
||||
expect(instance.apiBase).toBe("https://api.example.com/");
|
||||
expect(instance.accountId).toBe("testAccountId");
|
||||
expect(instance.engine).toBe("davinci");
|
||||
expect(instance.apiVersion).toBe("v1");
|
||||
expect(instance.apiType).toBe("public");
|
||||
expect(instance.region).toBe("us");
|
||||
expect(instance.projectId).toBe("testProjectId");
|
||||
});
|
||||
});
|
||||
|
||||
test("model should return correct provider model", () => {
|
||||
expect(baseLLM.model).toBe("dummy-model");
|
||||
});
|
||||
|
||||
test("supportsFim should always return false", () => {
|
||||
expect(baseLLM.supportsFim()).toBe(false);
|
||||
});
|
||||
|
||||
describe("supportsImages", () => {
|
||||
test("should return true when modelSupportsImages returns true", () => {
|
||||
baseLLM.model = "gpt-4-vision";
|
||||
expect(baseLLM.supportsImages()).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false when modelSupportsImages returns false", () => {
|
||||
expect(baseLLM.supportsImages()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsCompletions", () => {
|
||||
test("should return correctly under specific conditions", () => {
|
||||
// Mocking properties and scenarios to match the conditions in supportsCompletions
|
||||
baseLLM.apiBase = "api.groq.com";
|
||||
expect(baseLLM.supportsCompletions()).toBe(false);
|
||||
|
||||
baseLLM.apiBase = "api.mistral.ai";
|
||||
expect(baseLLM.supportsCompletions()).toBe(false);
|
||||
|
||||
baseLLM.apiBase = ":1337";
|
||||
expect(baseLLM.supportsCompletions()).toBe(false);
|
||||
|
||||
baseLLM.apiBase = "something:3000";
|
||||
expect(baseLLM.supportsCompletions()).toBe(true);
|
||||
});
|
||||
});
|
||||
describe("supportsPrefill", () => {
|
||||
test("should return correctly under specific conditions", () => {
|
||||
expect(baseLLM.supportsPrefill()).toBe(false);
|
||||
|
||||
class PrefillLLM extends BaseLLM {
|
||||
static providerName: ModelProvider = "ollama";
|
||||
}
|
||||
const prefillLLM = new PrefillLLM({ model: "some-model" });
|
||||
expect(prefillLLM.supportsPrefill()).toBe(true);
|
||||
});
|
||||
});
|
||||
describe("fetch", () => {
|
||||
// TODO: Implement tests for fetch method
|
||||
});
|
||||
describe("*_streamFim", () => {
|
||||
// TODO: Implement tests for *_streamFim method
|
||||
});
|
||||
describe("complete", () => {
|
||||
// TODO: Implement tests for complete method
|
||||
});
|
||||
describe("*streamChat", () => {
|
||||
// TODO: Implement tests for *streamChat method
|
||||
});
|
||||
});
|
||||
20
core/test/context/retrieval/RetrievalPipeline.test.ts
Normal file
20
core/test/context/retrieval/RetrievalPipeline.test.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline";
|
||||
|
||||
function testRetrievalPipeline(pipeline: IRetrievalPipeline) {
|
||||
test("should successfully run");
|
||||
}
|
||||
|
||||
// describe("Retrieval Pipelines", () => {
|
||||
// const ide = new FileSystemIde();
|
||||
// const options: RetrievalPipelineOptions;
|
||||
|
||||
// test("NoRerankerRetrievalPipeline", () => {
|
||||
// const pipeline = new NoRerankerRetrievalPipeline(options);
|
||||
// testRetrievalPipeline(pipeline);
|
||||
// });
|
||||
|
||||
// test("NoRerankerRetrievalPipeline", () => {
|
||||
// const pipeline = new NoRerankerRetrievalPipeline(options);
|
||||
// testRetrievalPipeline(pipeline);
|
||||
// });
|
||||
// });
|
||||
174
core/test/indexing/CodebaseIndexer.test.ts
Normal file
174
core/test/indexing/CodebaseIndexer.test.ts
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { ContinueServerClient } from "../../continueServer/stubs/client";
|
||||
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer";
|
||||
import { LanceDbIndex } from "../../indexing/LanceDbIndex";
|
||||
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
|
||||
import FileSystemIde from "../../util/filesystem";
|
||||
import {
|
||||
getIndexFolderPath,
|
||||
getIndexSqlitePath,
|
||||
getLanceDbPath,
|
||||
} from "../../util/paths";
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
TEST_DIR,
|
||||
} from "../testUtils/testDir";
|
||||
|
||||
const TEST_TS = `\
|
||||
function main() {
|
||||
console.log("Hello, world!");
|
||||
}
|
||||
|
||||
class Foo {
|
||||
constructor(public bar: string) {}
|
||||
}
|
||||
`;
|
||||
|
||||
const TEST_PY = `\
|
||||
def main():
|
||||
print("Hello, world!")
|
||||
|
||||
class Foo:
|
||||
def __init__(self, bar: str):
|
||||
self.bar = bar
|
||||
`;
|
||||
|
||||
const TEST_RS = `\
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
|
||||
struct Foo {
|
||||
bar: String,
|
||||
}
|
||||
`;
|
||||
|
||||
// These are more like integration tests, whereas we should separately test
|
||||
// the individual CodebaseIndex classes
|
||||
describe.skip("CodebaseIndexer", () => {
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
const ideSettingsPromise = ide.getIdeSettings();
|
||||
const configHandler = new ConfigHandler(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
async (text) => {},
|
||||
);
|
||||
const pauseToken = new PauseToken(false);
|
||||
const continueServerClient = new ContinueServerClient(undefined, undefined);
|
||||
const codebaseIndexer = new CodebaseIndexer(
|
||||
configHandler,
|
||||
ide,
|
||||
pauseToken,
|
||||
continueServerClient,
|
||||
);
|
||||
const lancedbIndex = new LanceDbIndex(
|
||||
new TransformersJsEmbeddingsProvider(),
|
||||
ide.readFile.bind(ide),
|
||||
continueServerClient,
|
||||
);
|
||||
|
||||
beforeAll(async () => {
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
test("should index test folder without problem", async () => {
|
||||
addToTestDir([
|
||||
["test.ts", TEST_TS],
|
||||
["py/main.py", TEST_PY],
|
||||
]);
|
||||
const abortController = new AbortController();
|
||||
const abortSignal = abortController.signal;
|
||||
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refresh(
|
||||
[TEST_DIR],
|
||||
abortSignal,
|
||||
)) {
|
||||
updates.push(update);
|
||||
}
|
||||
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should have created index folder with all necessary files", async () => {
|
||||
expect(fs.existsSync(getIndexFolderPath())).toBe(true);
|
||||
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
|
||||
expect(fs.existsSync(getLanceDbPath())).toBe(true);
|
||||
});
|
||||
|
||||
test("should be able to query lancedb index", async () => {
|
||||
const chunks = await lancedbIndex.retrieve(
|
||||
"What is the main function doing?",
|
||||
10,
|
||||
await ide.getTags(lancedbIndex.artifactId),
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(chunks.length).toBe(2);
|
||||
// Check that the main function from both files is returned
|
||||
expect(chunks.some((chunk) => chunk.filepath.endsWith("test.ts"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(chunks.some((chunk) => chunk.filepath.endsWith("main.py"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("should successfully re-index after adding a file", async () => {
|
||||
addToTestDir([["main.rs", TEST_RS]]);
|
||||
const abortController = new AbortController();
|
||||
const abortSignal = abortController.signal;
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refresh(
|
||||
[TEST_DIR],
|
||||
abortSignal,
|
||||
)) {
|
||||
updates.push(update);
|
||||
}
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
// Check that the new file was indexed
|
||||
const chunks = await lancedbIndex.retrieve(
|
||||
"What is the main function doing?",
|
||||
3,
|
||||
await ide.getTags(lancedbIndex.artifactId),
|
||||
undefined,
|
||||
);
|
||||
expect(chunks.length).toBe(3);
|
||||
expect(chunks.some((chunk) => chunk.filepath.endsWith("main.rs"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("should successfully re-index after deleting a file", async () => {
|
||||
fs.rmSync(path.join(TEST_DIR, "main.rs"));
|
||||
const abortController = new AbortController();
|
||||
const abortSignal = abortController.signal;
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refresh(
|
||||
[TEST_DIR],
|
||||
abortSignal,
|
||||
)) {
|
||||
updates.push(update);
|
||||
}
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
// Check that the deleted file was removed from the index
|
||||
const chunks = await lancedbIndex.retrieve(
|
||||
"What is the main function doing?",
|
||||
10,
|
||||
await ide.getTags(lancedbIndex.artifactId),
|
||||
undefined,
|
||||
);
|
||||
expect(chunks.length).toBe(2);
|
||||
expect(chunks.every((chunk) => !chunk.filepath.endsWith("main.rs"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
27
core/test/testUtils/testDir.ts
Normal file
27
core/test/testUtils/testDir.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
export const TEST_DIR = path.join(__dirname, "testDir");
|
||||
|
||||
export function setUpTestDir() {
|
||||
if (fs.existsSync(TEST_DIR)) {
|
||||
fs.rmSync(TEST_DIR, { recursive: true });
|
||||
}
|
||||
fs.mkdirSync(TEST_DIR);
|
||||
}
|
||||
|
||||
export function tearDownTestDir() {
|
||||
fs.rmSync(TEST_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
export function addToTestDir(paths: (string | string[])[]) {
|
||||
for (const p of paths) {
|
||||
if (Array.isArray(p)) {
|
||||
fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]);
|
||||
} else if (p.endsWith("/")) {
|
||||
fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true });
|
||||
} else {
|
||||
fs.writeFileSync(path.join(TEST_DIR, p), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
82
core/test/util/deduplicateArray.test.ts
Normal file
82
core/test/util/deduplicateArray.test.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { deduplicateArray } from "../../util";
|
||||
|
||||
describe("deduplicateArray", () => {
|
||||
it("should return an empty array when given an empty array", () => {
|
||||
const result = deduplicateArray([], (a, b) => a === b);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return the same array when there are no duplicates", () => {
|
||||
const input = [1, 2, 3, 4, 5];
|
||||
const result = deduplicateArray(input, (a, b) => a === b);
|
||||
expect(result).toEqual(input);
|
||||
});
|
||||
|
||||
it("should remove duplicates based on the equality function", () => {
|
||||
const input = [1, 2, 2, 3, 4, 4, 5];
|
||||
const result = deduplicateArray(input, (a, b) => a === b);
|
||||
expect(result).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it("should work with objects using custom equality function", () => {
|
||||
const input = [
|
||||
{ id: 1, name: "Alice" },
|
||||
{ id: 2, name: "Bob" },
|
||||
{ id: 1, name: "Alice" },
|
||||
{ id: 3, name: "Charlie" },
|
||||
];
|
||||
const result = deduplicateArray(input, (a, b) => a.id === b.id);
|
||||
expect(result).toEqual([
|
||||
{ id: 1, name: "Alice" },
|
||||
{ id: 2, name: "Bob" },
|
||||
{ id: 3, name: "Charlie" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should preserve the order of items", () => {
|
||||
const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
|
||||
const result = deduplicateArray(input, (a, b) => a === b);
|
||||
expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]);
|
||||
});
|
||||
|
||||
it("should work with strings", () => {
|
||||
const input = ["apple", "banana", "apple", "cherry", "banana", "date"];
|
||||
const result = deduplicateArray(input, (a, b) => a === b);
|
||||
expect(result).toEqual(["apple", "banana", "cherry", "date"]);
|
||||
});
|
||||
|
||||
it("should handle arrays with all duplicate elements", () => {
|
||||
const input = [1, 1, 1, 1, 1];
|
||||
const result = deduplicateArray(input, (a, b) => a === b);
|
||||
expect(result).toEqual([1]);
|
||||
});
|
||||
|
||||
it("should work with custom equality function for complex objects", () => {
|
||||
const input = [
|
||||
{ x: 1, y: 2 },
|
||||
{ x: 2, y: 1 },
|
||||
{ x: 1, y: 2 },
|
||||
{ x: 3, y: 4 },
|
||||
];
|
||||
const result = deduplicateArray(
|
||||
input,
|
||||
(a, b) => a.x === b.x && a.y === b.y,
|
||||
);
|
||||
expect(result).toEqual([
|
||||
{ x: 1, y: 2 },
|
||||
{ x: 2, y: 1 },
|
||||
{ x: 3, y: 4 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle large arrays efficiently", () => {
|
||||
const input = Array(10000)
|
||||
.fill(0)
|
||||
.map((_, i) => i % 100);
|
||||
const start = performance.now();
|
||||
const result = deduplicateArray(input, (a, b) => a === b);
|
||||
const end = performance.now();
|
||||
expect(result).toHaveLength(100);
|
||||
expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second
|
||||
});
|
||||
});
|
||||
|
|
@ -1,22 +1,13 @@
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { walkDir, WalkerOptions } from "../indexing/walkDir";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
const ide = new FileSystemIde();
|
||||
|
||||
const TEST_DIR = path.join(__dirname, "testDir");
|
||||
|
||||
function buildTestDir(paths: (string | string[])[]) {
|
||||
for (const p of paths) {
|
||||
if (Array.isArray(p)) {
|
||||
fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]);
|
||||
} else if (p.endsWith("/")) {
|
||||
fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true });
|
||||
} else {
|
||||
fs.writeFileSync(path.join(TEST_DIR, p), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
TEST_DIR,
|
||||
} from "./testUtils/testDir";
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
|
||||
async function walkTestDir(
|
||||
options?: WalkerOptions,
|
||||
|
|
@ -44,14 +35,11 @@ async function expectPaths(
|
|||
|
||||
describe("walkDir", () => {
|
||||
beforeEach(() => {
|
||||
if (fs.existsSync(TEST_DIR)) {
|
||||
fs.rmSync(TEST_DIR, { recursive: true });
|
||||
}
|
||||
fs.mkdirSync(TEST_DIR);
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(TEST_DIR, { recursive: true });
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
test("should return nothing for empty dir", async () => {
|
||||
|
|
@ -61,20 +49,20 @@ describe("walkDir", () => {
|
|||
|
||||
test("should return all files in flat dir", async () => {
|
||||
const files = ["a.txt", "b.py", "c.ts"];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
const result = await walkTestDir();
|
||||
expect(result).toEqual(files);
|
||||
});
|
||||
|
||||
test("should ignore ignored files in flat dir", async () => {
|
||||
const files = [[".gitignore", "*.py"], "a.txt", "c.ts", "b.py"];
|
||||
buildTestDir(files);
|
||||
await expectPaths(["a.txt", "c.ts", ".gitignore"], ["b.py"]);
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "c.ts"], ["b.py"]);
|
||||
});
|
||||
|
||||
test("should handle negation in flat folder", async () => {
|
||||
const files = [[".gitignore", "**/*\n!*.py"], "a.txt", "c.ts", "b.py"];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(["b.py"], [".gitignore", "a.txt", "c.ts"]);
|
||||
});
|
||||
|
||||
|
|
@ -89,7 +77,7 @@ describe("walkDir", () => {
|
|||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
files.filter((files) => !files.endsWith("/")),
|
||||
[],
|
||||
|
|
@ -108,16 +96,16 @@ describe("walkDir", () => {
|
|||
"d/g/h.ts",
|
||||
["d/.gitignore", "*.py"],
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["a.txt", "b.py", "c.ts", "d/e.txt", "d/g/h.ts", "d/.gitignore"],
|
||||
["a.txt", "b.py", "c.ts", "d/e.txt", "d/g/h.ts"],
|
||||
["d/f.py"],
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle leading slash in gitignore", async () => {
|
||||
const files = [[".gitignore", "/no.txt"], "a.txt", "b.py", "no.txt"];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "b.py"], ["no.txt"]);
|
||||
});
|
||||
|
||||
|
|
@ -131,7 +119,7 @@ describe("walkDir", () => {
|
|||
"c/e.py",
|
||||
["c/.gitignore", "*.py"],
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.py"], ["b.txt", "c/e.py", "c/d.txt"]);
|
||||
});
|
||||
|
||||
|
|
@ -146,7 +134,7 @@ describe("walkDir", () => {
|
|||
"d/f.py",
|
||||
"d/g.ts",
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["c.ts", "d/g.ts"],
|
||||
["a.txt", "b.py", "d/e.txt", "d/f.py"],
|
||||
|
|
@ -162,7 +150,7 @@ describe("walkDir", () => {
|
|||
"ignored_dir/c/",
|
||||
"ignored_dir/c/d.py",
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]);
|
||||
});
|
||||
|
||||
|
|
@ -178,7 +166,7 @@ describe("walkDir", () => {
|
|||
"temp/",
|
||||
"temp/c.txt",
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["important.what", "subdir/root_only.txt"],
|
||||
["a.what", "root_only.txt", "subdir/b.what", "temp/c.txt"],
|
||||
|
|
@ -194,11 +182,8 @@ describe("walkDir", () => {
|
|||
"c.ts",
|
||||
"d.js",
|
||||
];
|
||||
buildTestDir(files);
|
||||
await expectPaths(
|
||||
["a.txt", "d.js", ".gitignore", ".continueignore"],
|
||||
["b.py", "c.ts"],
|
||||
);
|
||||
addToTestDir(files);
|
||||
await expectPaths(["a.txt", "d.js"], ["b.py", "c.ts"]);
|
||||
});
|
||||
|
||||
test("should return dirs and only dirs in onlyDirs mode", async () => {
|
||||
|
|
@ -212,7 +197,7 @@ describe("walkDir", () => {
|
|||
"d/g/",
|
||||
"d/g/h.ts",
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["d", "d/g"],
|
||||
["a.txt", "b.py", "c.ts", "d/e.txt", "d/f.py", "d/g/h.ts"],
|
||||
|
|
@ -222,7 +207,7 @@ describe("walkDir", () => {
|
|||
|
||||
test("should return valid paths in absolute path mode", async () => {
|
||||
const files = ["a.txt", "b/", "b/c.txt"];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
[path.join(TEST_DIR, "a.txt"), path.join(TEST_DIR, "b", "c.txt")],
|
||||
[],
|
||||
|
|
@ -232,28 +217,60 @@ describe("walkDir", () => {
|
|||
);
|
||||
});
|
||||
|
||||
test.skip("should walk continue repo", async () => {
|
||||
const results = await walkDir(path.join(__dirname, "..", ".."), ide, {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
});
|
||||
console.log(results);
|
||||
});
|
||||
|
||||
test.skip("should skip .git and node_modules folders", async () => {
|
||||
test("should skip .git and node_modules folders", async () => {
|
||||
const files = [
|
||||
"a.txt",
|
||||
".git/",
|
||||
".git/config",
|
||||
".git/HEAD",
|
||||
".git/objects/",
|
||||
".git/objects/1234567890abcdef",
|
||||
"node_modules/",
|
||||
"node_modules/package/",
|
||||
"node_modules/package/index.js",
|
||||
"src/",
|
||||
"src/index.ts",
|
||||
];
|
||||
buildTestDir(files);
|
||||
addToTestDir(files);
|
||||
await expectPaths(
|
||||
["a.txt", "src/index.ts"],
|
||||
[".git/config", ".git/HEAD", "node_modules/package/index.js"],
|
||||
[
|
||||
".git/config",
|
||||
".git/HEAD",
|
||||
"node_modules/package/index.js",
|
||||
".git/objects/1234567890abcdef",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("should walk continue repo without getting any files of the default ignore types", async () => {
|
||||
const results = await walkDir(path.join(__dirname, "..", ".."), ide, {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
});
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results.some((file) => file.includes("/node_modules/"))).toBe(false);
|
||||
expect(results.some((file) => file.includes("/.git/"))).toBe(false);
|
||||
expect(
|
||||
results.some(
|
||||
(file) =>
|
||||
file.endsWith(".gitignore") ||
|
||||
file.endsWith(".continueignore") ||
|
||||
file.endsWith("package-lock.json"),
|
||||
),
|
||||
).toBe(false);
|
||||
// At some point we will cross this number, but in case we leap past it suddenly I think we'd want to investigate why
|
||||
expect(results.length).toBeLessThan(1500);
|
||||
});
|
||||
|
||||
test("should walk continue/extensions/vscode without getting any files in the .continueignore", async () => {
|
||||
const vscodePath = path.join(__dirname, "..", "..", "extensions", "vscode");
|
||||
const results = await walkDir(vscodePath, ide, {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
});
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results.some((file) => file.includes("/textmate-syntaxes/"))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(results.some((file) => file.includes(".tmLanguage"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,11 +17,7 @@ import {
|
|||
import { getContinueGlobalPath } from "./paths.js";
|
||||
|
||||
class FileSystemIde implements IDE {
|
||||
static workspaceDir = "/tmp/continue";
|
||||
|
||||
constructor() {
|
||||
fs.mkdirSync(FileSystemIde.workspaceDir, { recursive: true });
|
||||
}
|
||||
constructor(private readonly workspaceDir: string) {}
|
||||
pathSep(): Promise<string> {
|
||||
return Promise.resolve(path.sep);
|
||||
}
|
||||
|
|
@ -141,14 +137,7 @@ class FileSystemIde implements IDE {
|
|||
}
|
||||
|
||||
getWorkspaceDirs(): Promise<string[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.mkdtemp(FileSystemIde.workspaceDir, (err, folder) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve([folder]);
|
||||
});
|
||||
});
|
||||
return Promise.resolve([this.workspaceDir]);
|
||||
}
|
||||
|
||||
listFolders(): Promise<string[]> {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,9 @@ export const DO_NOT_COUNT_REJECTED_BEFORE = 250;
|
|||
|
||||
export const RETRIEVAL_PARAMS = {
|
||||
rerankThreshold: 0.3,
|
||||
nFinal: 10,
|
||||
nRetrieve: 20,
|
||||
nFinal: 20,
|
||||
nRetrieve: 50,
|
||||
bm25Threshold: -2.5,
|
||||
nResultsToExpandWithEmbeddings: 5,
|
||||
nEmbeddingsExpandTo: 5,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -177,12 +177,22 @@ function getMigrationsFolderPath(): string {
|
|||
return migrationsPath;
|
||||
}
|
||||
|
||||
export function migrate(id: string, callback: () => void) {
|
||||
export function migrate(
|
||||
id: string,
|
||||
callback: () => void,
|
||||
onAlreadyComplete?: () => void,
|
||||
) {
|
||||
const migrationsPath = getMigrationsFolderPath();
|
||||
const migrationPath = path.join(migrationsPath, id);
|
||||
if (!fs.existsSync(migrationPath)) {
|
||||
fs.writeFileSync(migrationPath, "");
|
||||
callback();
|
||||
try {
|
||||
callback();
|
||||
fs.writeFileSync(migrationPath, "");
|
||||
} catch (e) {
|
||||
console.error(`Migration ${id} failed`, e);
|
||||
}
|
||||
} else if (onAlreadyComplete) {
|
||||
onAlreadyComplete();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -93,6 +93,11 @@ export async function getParserForFile(filepath: string) {
|
|||
}
|
||||
}
|
||||
|
||||
// Loading the wasm files to create a Language object is an expensive operation and with
|
||||
// sufficient number of files can result in errors, instead keep a map of language name
|
||||
// to Language object
|
||||
const nameToLanguage = new Map<string, Language>();
|
||||
|
||||
export async function getLanguageForFile(
|
||||
filepath: string,
|
||||
): Promise<Language | undefined> {
|
||||
|
|
@ -100,18 +105,15 @@ export async function getLanguageForFile(
|
|||
await Parser.init();
|
||||
const extension = path.extname(filepath).slice(1);
|
||||
|
||||
if (!supportedLanguages[extension]) {
|
||||
const languageName = supportedLanguages[extension];
|
||||
if (!languageName) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const wasmPath = path.join(
|
||||
__dirname,
|
||||
...(process.env.NODE_ENV === "test"
|
||||
? ["node_modules", "tree-sitter-wasms", "out"]
|
||||
: ["tree-sitter-wasms"]),
|
||||
`tree-sitter-${supportedLanguages[extension]}.wasm`,
|
||||
);
|
||||
const language = await Parser.Language.load(wasmPath);
|
||||
let language = nameToLanguage.get(languageName);
|
||||
if (!language) {
|
||||
language = await loadLanguageForFileExt(extension);
|
||||
nameToLanguage.set(languageName, language);
|
||||
}
|
||||
return language;
|
||||
} catch (e) {
|
||||
console.error("Unable to load language for file", filepath, e);
|
||||
|
|
@ -149,3 +151,14 @@ export async function getQueryForFile(
|
|||
const query = language.query(querySource);
|
||||
return query;
|
||||
}
|
||||
|
||||
async function loadLanguageForFileExt(fileExtension: string): Promise<Language> {
|
||||
const wasmPath = path.join(
|
||||
__dirname,
|
||||
...(process.env.NODE_ENV === "test"
|
||||
? ["node_modules", "tree-sitter-wasms", "out"]
|
||||
: ["tree-sitter-wasms"]),
|
||||
`tree-sitter-${supportedLanguages[fileExtension]}.wasm`,
|
||||
);
|
||||
return await Parser.Language.load(wasmPath);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ All data is anonymous and cleaned of PII before being sent to PostHog.
|
|||
## What we track
|
||||
|
||||
- Whether you accept or reject suggestions (never including the code or the prompt)
|
||||
- The name of the model and slash command used
|
||||
- The name of the model and command used
|
||||
- The number of tokens generated
|
||||
- The name of your OS and IDE
|
||||
- Pageviews
|
||||
|
|
|
|||
95
docs/docs/walkthroughs/quick-actions.md
Normal file
95
docs/docs/walkthroughs/quick-actions.md
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
---
|
||||
title: Quick Actions (experimental, VS Code only)
|
||||
description: Quick Actions automate repetitive tasks and streamline your development workflow
|
||||
keywords: [experimental, automate, configuration]
|
||||
toc_max_heading_level: 5
|
||||
---
|
||||
|
||||
# Quick Actions (experimental, VS Code only)
|
||||
|
||||
Quick Actions automate repetitive tasks and streamline your development workflow. Configure custom actions to execute complex operations with a single click.
|
||||
|
||||

|
||||
|
||||
## How It Works
|
||||
|
||||
:::info[Note]
|
||||
For the language of the file you have open, you must have the Language Server Protocol extension installed.
|
||||
:::
|
||||
|
||||
Quick Actions use a CodeLens provider to add interactive elements above functions and classes in your code.
|
||||
|
||||
By default, Quick Actions include two predefined actions:
|
||||
|
||||
1. `Explain`: This action provides a short explanation of the selected code.
|
||||
2. `Docstring`: This action generates a docstring comment and inserts it above the code.
|
||||
|
||||
## How to disable Quick Actions
|
||||
|
||||
Quick Actions are enabled by default _for pre-release versions of Contine_.
|
||||
|
||||
To disable Quick Actions, open the settings menu (`⌘ + ,`), search for `"continue.enableQuickActions"`, and toggle the checkbox to disable.
|
||||
|
||||
## Custom Quick Actions
|
||||
|
||||
Custom Quick Actions allow you to tailor functionality to your specific needs, extending beyond the default actions. You can easily configure these custom actions in your `~/.continue/config.json` file.
|
||||
|
||||
:::info
|
||||
[View the Configuration Options reference](../reference/config) for specific schema details.
|
||||
:::
|
||||
|
||||
### Example Use Cases
|
||||
|
||||
#### 1. Write an inline unit test
|
||||
|
||||
A quick action that generates and inserts a unit test above the selected code.
|
||||
|
||||
```json title=~/.continue/config.json
|
||||
"experimental": {
|
||||
"quickActions": [
|
||||
{
|
||||
"title": "Unit test",
|
||||
"prompt": "Write a unit test for this code. Do not change anything about the code itself.",
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Send code to chat panel to learn more about it
|
||||
|
||||
The default "Explain" aims to provide a brief overview of the code. This quick action sends the prompt and the code to the chat to provides a more detailed explanation.
|
||||
|
||||
```json title=~/.continue/config.json
|
||||
"experimental": {
|
||||
"quickActions": [
|
||||
{
|
||||
"title": "Detailed explanation",
|
||||
"prompt": "Explain the following code in detail, including all methods and properties.",
|
||||
"sendToChat": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Create a Typescript interface
|
||||
|
||||
A quick action that generates and inserts a Typescript interface above the selected code.
|
||||
|
||||
```json title=~/.continue/config.json
|
||||
"experimental": {
|
||||
"quickActions": [
|
||||
{
|
||||
"title": "Create Interface",
|
||||
"prompt": "Create a new Typescript interface for the following code.",
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Share your feedback
|
||||
|
||||
We'd love to hear your thoughts on Quick Actions! Share your feedback and help us improve.
|
||||
|
||||
<!-- Discord Feedback channel -->
|
||||
|
||||
<a href="https://discord.com/channels/1108621136150929458/1156679146932535376" className="button button--primary">Give Feedback on Discord</a>
|
||||
|
|
@ -50,6 +50,7 @@ const sidebars = {
|
|||
"walkthroughs/codebase-embeddings",
|
||||
"walkthroughs/tab-autocomplete",
|
||||
"walkthroughs/prompt-files",
|
||||
"walkthroughs/quick-actions",
|
||||
],
|
||||
},
|
||||
"development-data",
|
||||
|
|
|
|||
BIN
docs/static/img/quick-actions-demo.gif
vendored
Normal file
BIN
docs/static/img/quick-actions-demo.gif
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 MiB |
23
docs/static/schemas/config.json
vendored
23
docs/static/schemas/config.json
vendored
|
|
@ -2161,6 +2161,29 @@
|
|||
"promptPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"quickActions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The title of the quick action that will display in the Code Lens."
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated."
|
||||
},
|
||||
"sendToChat": {
|
||||
"type": "boolean",
|
||||
"description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": ["prompt", "title"]
|
||||
},
|
||||
"description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations."
|
||||
},
|
||||
"contextMenuPrompts": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
|
|||
|
|
@ -2161,6 +2161,29 @@
|
|||
"promptPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"quickActions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The title of the quick action that will display in the Code Lens."
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated."
|
||||
},
|
||||
"sendToChat": {
|
||||
"type": "boolean",
|
||||
"description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": ["prompt", "title"]
|
||||
},
|
||||
"description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations."
|
||||
},
|
||||
"contextMenuPrompts": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
media
|
||||
**/*.tmLanguage
|
||||
textmate-syntaxes
|
||||
models/**/*
|
||||
builtin-themes/
|
||||
**/textmate-syntaxes/
|
||||
**/*.scm
|
||||
|
|
@ -2161,6 +2161,29 @@
|
|||
"promptPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"quickActions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The title of the quick action that will display in the Code Lens."
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated."
|
||||
},
|
||||
"sendToChat": {
|
||||
"type": "boolean",
|
||||
"description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": ["prompt", "title"]
|
||||
},
|
||||
"description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations."
|
||||
},
|
||||
"contextMenuPrompts": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
|
|||
|
|
@ -2425,6 +2425,32 @@
|
|||
"promptPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"quickActions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The title of the quick action that will display in the Code Lens."
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated."
|
||||
},
|
||||
"sendToChat": {
|
||||
"type": "boolean",
|
||||
"description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"prompt",
|
||||
"title"
|
||||
]
|
||||
},
|
||||
"description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations."
|
||||
},
|
||||
"contextMenuPrompts": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
|
|||
4
extensions/vscode/package-lock.json
generated
4
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "0.9.172",
|
||||
"version": "0.9.174",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "0.9.172",
|
||||
"version": "0.9.174",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@electron/rebuild": "^3.2.10",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"version": "0.9.174",
|
||||
"version": "0.9.175",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -79,10 +79,15 @@
|
|||
"default": true,
|
||||
"description": "Show inline suggestion to use the Continue keyboard shortcuts (e.g. \"Cmd/Ctrl L to select code, Cmd/Ctrl I to edit\")."
|
||||
},
|
||||
"continue.enableQuickActions": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/walkthroughs/quick-actions)"
|
||||
},
|
||||
"continue.enableTabAutocomplete": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"markdownDescription": "Enable Continue's tab autocomplete feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete](https://docs.continue.dev/walkthroughs/tab-autocomplete)"
|
||||
"markdownDescription": "Enable Continue's tab autocomplete feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete (beta)](https://docs.continue.dev/walkthroughs/tab-autocomplete)"
|
||||
},
|
||||
"continue.pauseTabAutocompleteOnBattery": {
|
||||
"type": "boolean",
|
||||
|
|
@ -317,7 +322,8 @@
|
|||
{
|
||||
"command": "continue.toggleTabAutocompleteEnabled",
|
||||
"mac": "cmd+k cmd+a",
|
||||
"key": "ctrl+k ctrl+a"
|
||||
"key": "ctrl+k ctrl+a",
|
||||
"when": "!terminalFocus"
|
||||
}
|
||||
],
|
||||
"submenus": [
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const esbuildConfig = {
|
|||
external: ["vscode", "esbuild", "./xhr-sync-worker.js"],
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: false,
|
||||
sourcemap: flags.includes("--sourcemap"),
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
".node": "file",
|
||||
|
|
|
|||
|
|
@ -4,13 +4,18 @@ import {
|
|||
CompletionProvider,
|
||||
type AutocompleteInput,
|
||||
} from "core/autocomplete/completionProvider";
|
||||
import type { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
import type { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import { getDefinitionsFromLsp } from "./lsp";
|
||||
import { RecentlyEditedTracker } from "./recentlyEdited";
|
||||
import { StatusBarStatus, setupStatusBar, stopStatusBarLoading, getStatusBarStatus } from "./statusBar";
|
||||
import {
|
||||
StatusBarStatus,
|
||||
getStatusBarStatus,
|
||||
setupStatusBar,
|
||||
stopStatusBarLoading,
|
||||
} from "./statusBar";
|
||||
|
||||
interface VsCodeCompletionInput {
|
||||
document: vscode.TextDocument;
|
||||
|
|
@ -43,7 +48,7 @@ export class ContinueCompletionProvider
|
|||
private recentlyEditedTracker = new RecentlyEditedTracker();
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly configHandler: IConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly tabAutocompleteModel: TabAutocompleteModel,
|
||||
) {
|
||||
|
|
@ -73,7 +78,8 @@ export class ContinueCompletionProvider
|
|||
token: vscode.CancellationToken,
|
||||
//@ts-ignore
|
||||
): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
|
||||
const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled;
|
||||
const enableTabAutocomplete =
|
||||
getStatusBarStatus() === StatusBarStatus.Enabled;
|
||||
if (token.isCancellationRequested || !enableTabAutocomplete) {
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import * as vscode from "vscode";
|
||||
import { Battery } from "../util/battery";
|
||||
import {
|
||||
CONTINUE_WORKSPACE_KEY,
|
||||
getContinueWorkspaceConfig,
|
||||
} from "../util/workspaceConfig";
|
||||
|
||||
export enum StatusBarStatus {
|
||||
Disabled,
|
||||
|
|
@ -91,13 +95,18 @@ export function setupStatusBar(
|
|||
statusBarItem.command = "continue.openTabAutocompleteConfigMenu";
|
||||
|
||||
statusBarItem.show();
|
||||
if (status !== undefined) statusBarStatus = status;
|
||||
if (status !== undefined) {
|
||||
statusBarStatus = status;
|
||||
}
|
||||
|
||||
vscode.workspace.onDidChangeConfiguration((event) => {
|
||||
if (event.affectsConfiguration("continue")) {
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const enabled = config.get<boolean>("enableTabAutocomplete");
|
||||
if (enabled && statusBarStatus === StatusBarStatus.Paused) return;
|
||||
if (event.affectsConfiguration(CONTINUE_WORKSPACE_KEY)) {
|
||||
const enabled = getContinueWorkspaceConfig().get<boolean>(
|
||||
"enableTabAutocomplete",
|
||||
);
|
||||
if (enabled && statusBarStatus === StatusBarStatus.Paused) {
|
||||
return;
|
||||
}
|
||||
setupStatusBar(
|
||||
enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
|
@ -5,7 +6,7 @@ import * as vscode from "vscode";
|
|||
|
||||
import { ContextMenuConfig, IDE } from "core";
|
||||
import { CompletionProvider } from "core/autocomplete/completionProvider";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import { ContinueServerClient } from "core/continueServer/stubs/client";
|
||||
import { GlobalContext } from "core/util/GlobalContext";
|
||||
import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths";
|
||||
|
|
@ -34,6 +35,18 @@ function getFullScreenTab() {
|
|||
);
|
||||
}
|
||||
|
||||
type TelemetryCaptureParams = Parameters<typeof Telemetry.capture>;
|
||||
|
||||
/**
|
||||
* Helper method to add the `isCommandEvent` to all telemetry captures
|
||||
*/
|
||||
function captureCommandTelemetry(
|
||||
commandName: TelemetryCaptureParams[0],
|
||||
properties: TelemetryCaptureParams[1] = {},
|
||||
) {
|
||||
Telemetry.capture(commandName, { isCommandEvent: true, ...properties });
|
||||
}
|
||||
|
||||
async function addHighlightedCodeToContext(
|
||||
edit: boolean,
|
||||
webviewProtocol: VsCodeWebviewProtocol | undefined,
|
||||
|
|
@ -153,7 +166,7 @@ const commandsMap: (
|
|||
ide: IDE,
|
||||
extensionContext: vscode.ExtensionContext,
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
configHandler: ConfigHandler,
|
||||
configHandler: IConfigHandler,
|
||||
diffManager: DiffManager,
|
||||
verticalDiffManager: VerticalPerLineDiffManager,
|
||||
continueServerClientPromise: Promise<ContinueServerClient>,
|
||||
|
|
@ -168,23 +181,42 @@ const commandsMap: (
|
|||
continueServerClientPromise,
|
||||
battery,
|
||||
) => {
|
||||
/**
|
||||
* Streams an inline edit to the vertical diff manager.
|
||||
*
|
||||
* This function retrieves the configuration, determines the appropriate model title,
|
||||
* increments the FTC count, and then streams an edit to the
|
||||
* vertical diff manager.
|
||||
*
|
||||
* @param promptName - The key for the prompt in the context menu configuration.
|
||||
* @param fallbackPrompt - The prompt to use if the configured prompt is not available.
|
||||
* @param [onlyOneInsertion] - Optional. If true, only one insertion will be made.
|
||||
* @param [range] - Optional. The range to edit if provided.
|
||||
* @returns
|
||||
*/
|
||||
async function streamInlineEdit(
|
||||
promptName: keyof ContextMenuConfig,
|
||||
fallbackPrompt: string,
|
||||
onlyOneInsertion?: boolean,
|
||||
range?: vscode.Range,
|
||||
) {
|
||||
const config = await configHandler.loadConfig();
|
||||
|
||||
const modelTitle =
|
||||
config.experimental?.modelRoles?.inlineEdit ??
|
||||
(await sidebar.webviewProtocol.request(
|
||||
"getDefaultModelTitle",
|
||||
undefined,
|
||||
));
|
||||
|
||||
sidebar.webviewProtocol.request("incrementFtc", undefined);
|
||||
|
||||
await verticalDiffManager.streamEdit(
|
||||
config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt,
|
||||
modelTitle,
|
||||
onlyOneInsertion,
|
||||
undefined,
|
||||
range,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -202,6 +234,8 @@ const commandsMap: (
|
|||
|
||||
return {
|
||||
"continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => {
|
||||
captureCommandTelemetry("acceptDiff");
|
||||
|
||||
if (newFilepath instanceof vscode.Uri) {
|
||||
newFilepath = newFilepath.fsPath;
|
||||
}
|
||||
|
|
@ -209,6 +243,8 @@ const commandsMap: (
|
|||
await diffManager.acceptDiff(newFilepath);
|
||||
},
|
||||
"continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => {
|
||||
captureCommandTelemetry("rejectDiff");
|
||||
|
||||
if (newFilepath instanceof vscode.Uri) {
|
||||
newFilepath = newFilepath.fsPath;
|
||||
}
|
||||
|
|
@ -216,9 +252,11 @@ const commandsMap: (
|
|||
await diffManager.rejectDiff(newFilepath);
|
||||
},
|
||||
"continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => {
|
||||
captureCommandTelemetry("acceptVerticalDiffBlock");
|
||||
verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index);
|
||||
},
|
||||
"continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => {
|
||||
captureCommandTelemetry("rejectVerticalDiffBlock");
|
||||
verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index);
|
||||
},
|
||||
"continue.quickFix": async (
|
||||
|
|
@ -226,6 +264,10 @@ const commandsMap: (
|
|||
code: string,
|
||||
edit: boolean,
|
||||
) => {
|
||||
captureCommandTelemetry("rejectVerticalDiffBlock", {
|
||||
edit,
|
||||
});
|
||||
|
||||
sidebar.webviewProtocol?.request("newSessionWithPrompt", {
|
||||
prompt: `${
|
||||
edit ? "/edit " : ""
|
||||
|
|
@ -236,6 +278,47 @@ const commandsMap: (
|
|||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
}
|
||||
},
|
||||
"continue.defaultQuickActionDocstring": async (range: vscode.Range) => {
|
||||
captureCommandTelemetry("defaultQuickActionDocstring");
|
||||
|
||||
streamInlineEdit(
|
||||
"docstring",
|
||||
"Write a docstring for this code. Do not change anything about the code itself.",
|
||||
true,
|
||||
range,
|
||||
);
|
||||
},
|
||||
"continue.defaultQuickActionExplain": async (code: string) => {
|
||||
captureCommandTelemetry("defaultQuickActionExplain");
|
||||
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
|
||||
sidebar.webviewProtocol?.request("userInput", {
|
||||
input:
|
||||
`Explain the following code in a few sentences without ` +
|
||||
`going into detail on specific methods:\n\n ${code}`,
|
||||
});
|
||||
},
|
||||
"continue.customQuickActionSendToChat": async (
|
||||
prompt: string,
|
||||
code: string,
|
||||
) => {
|
||||
captureCommandTelemetry("customQuickActionSendToChat");
|
||||
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
|
||||
sidebar.webviewProtocol?.request("userInput", {
|
||||
input: `${prompt}:\n\n ${code}`,
|
||||
});
|
||||
},
|
||||
"continue.customQuickActionStreamInlineEdit": async (
|
||||
prompt: string,
|
||||
range: vscode.Range,
|
||||
) => {
|
||||
captureCommandTelemetry("customQuickActionStreamInlineEdit");
|
||||
|
||||
streamInlineEdit("docstring", prompt, false, range);
|
||||
},
|
||||
"continue.focusContinueInput": async () => {
|
||||
const fullScreenTab = getFullScreenTab();
|
||||
if (!fullScreenTab) {
|
||||
|
|
@ -262,15 +345,20 @@ const commandsMap: (
|
|||
vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar");
|
||||
},
|
||||
"continue.quickEdit": (injectedPrompt?: string) => {
|
||||
captureCommandTelemetry("quickEdit");
|
||||
quickEdit.run(injectedPrompt);
|
||||
},
|
||||
"continue.writeCommentsForCode": async () => {
|
||||
captureCommandTelemetry("writeCommentsForCode");
|
||||
|
||||
streamInlineEdit(
|
||||
"comment",
|
||||
"Write comments for this code. Do not change anything about the code itself.",
|
||||
);
|
||||
},
|
||||
"continue.writeDocstringForCode": async () => {
|
||||
captureCommandTelemetry("writeDocstringForCode");
|
||||
|
||||
streamInlineEdit(
|
||||
"docstring",
|
||||
"Write a docstring for this code. Do not change anything about the code itself.",
|
||||
|
|
@ -278,21 +366,27 @@ const commandsMap: (
|
|||
);
|
||||
},
|
||||
"continue.fixCode": async () => {
|
||||
captureCommandTelemetry("fixCode");
|
||||
|
||||
streamInlineEdit(
|
||||
"fix",
|
||||
"Fix this code. If it is already 100% correct, simply rewrite the code.",
|
||||
);
|
||||
},
|
||||
"continue.optimizeCode": async () => {
|
||||
captureCommandTelemetry("optimizeCode");
|
||||
streamInlineEdit("optimize", "Optimize this code");
|
||||
},
|
||||
"continue.fixGrammar": async () => {
|
||||
captureCommandTelemetry("fixGrammar");
|
||||
streamInlineEdit(
|
||||
"fixGrammar",
|
||||
"If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.",
|
||||
);
|
||||
},
|
||||
"continue.viewLogs": async () => {
|
||||
captureCommandTelemetry("viewLogs");
|
||||
|
||||
// Open ~/.continue/continue.log
|
||||
const logFile = path.join(os.homedir(), ".continue", "continue.log");
|
||||
// Make sure the file/directory exist
|
||||
|
|
@ -305,8 +399,12 @@ const commandsMap: (
|
|||
await vscode.window.showTextDocument(uri);
|
||||
},
|
||||
"continue.debugTerminal": async () => {
|
||||
captureCommandTelemetry("debugTerminal");
|
||||
|
||||
const terminalContents = await ide.getTerminalContents();
|
||||
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
|
||||
sidebar.webviewProtocol?.request("userInput", {
|
||||
input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`,
|
||||
});
|
||||
|
|
@ -319,6 +417,8 @@ const commandsMap: (
|
|||
|
||||
// Commands without keyboard shortcuts
|
||||
"continue.addModel": () => {
|
||||
captureCommandTelemetry("addModel");
|
||||
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
sidebar.webviewProtocol?.request("addModel", undefined);
|
||||
},
|
||||
|
|
@ -354,6 +454,7 @@ const commandsMap: (
|
|||
});
|
||||
},
|
||||
"continue.sendToTerminal": (text: string) => {
|
||||
captureCommandTelemetry("sendToTerminal");
|
||||
ide.runCommand(text);
|
||||
},
|
||||
"continue.newSession": () => {
|
||||
|
|
@ -380,7 +481,7 @@ const commandsMap: (
|
|||
}
|
||||
|
||||
//Full screen not open - open it
|
||||
Telemetry.capture("openFullScreen", {});
|
||||
captureCommandTelemetry("openFullScreen");
|
||||
|
||||
// Close the sidebar.webviews
|
||||
// vscode.commands.executeCommand("workbench.action.closeSidebar");
|
||||
|
|
@ -437,6 +538,8 @@ const commandsMap: (
|
|||
completionProvider.accept(completionId);
|
||||
},
|
||||
"continue.toggleTabAutocompleteEnabled": () => {
|
||||
captureCommandTelemetry("toggleTabAutocompleteEnabled");
|
||||
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const enabled = config.get("enableTabAutocomplete");
|
||||
const pauseOnBattery = config.get<boolean>(
|
||||
|
|
@ -471,6 +574,8 @@ const commandsMap: (
|
|||
}
|
||||
},
|
||||
"continue.openTabAutocompleteConfigMenu": async () => {
|
||||
captureCommandTelemetry("openTabAutocompleteConfigMenu");
|
||||
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const quickPick = vscode.window.createQuickPick();
|
||||
const selected = new GlobalContext().get("selectedTabAutocompleteModel");
|
||||
|
|
@ -565,9 +670,11 @@ const commandsMap: (
|
|||
}
|
||||
},
|
||||
"continue.quickEditHistoryUp": async () => {
|
||||
captureCommandTelemetry("quickEditHistoryUp");
|
||||
historyUpEventEmitter.fire();
|
||||
},
|
||||
"continue.quickEditHistoryDown": async () => {
|
||||
captureCommandTelemetry("quickEditHistoryDown");
|
||||
historyDownEventEmitter.fire();
|
||||
},
|
||||
};
|
||||
|
|
@ -578,7 +685,7 @@ export function registerAllCommands(
|
|||
ide: IDE,
|
||||
extensionContext: vscode.ExtensionContext,
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
configHandler: ConfigHandler,
|
||||
configHandler: IConfigHandler,
|
||||
diffManager: DiffManager,
|
||||
verticalDiffManager: VerticalPerLineDiffManager,
|
||||
continueServerClientPromise: Promise<ContinueServerClient>,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { FileEdit } from "core";
|
||||
import type { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import * as vscode from "vscode";
|
||||
import { getTheme } from "./util/getTheme";
|
||||
import { getExtensionVersion } from "./util/util";
|
||||
|
|
@ -46,7 +46,7 @@ export class ContinueGUIWebviewViewProvider
|
|||
}
|
||||
|
||||
constructor(
|
||||
private readonly configHandlerPromise: Promise<ConfigHandler>,
|
||||
private readonly configHandlerPromise: Promise<IConfigHandler>,
|
||||
private readonly windowId: string,
|
||||
private readonly extensionContext: vscode.ExtensionContext,
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
|
||||
import { getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { streamDiffLines } from "core/util/verticalEdit";
|
||||
|
|
@ -21,7 +21,7 @@ export class VerticalPerLineDiffManager {
|
|||
|
||||
private userChangeListener: vscode.Disposable | undefined;
|
||||
|
||||
constructor(private readonly configHandler: ConfigHandler) {
|
||||
constructor(private readonly configHandler: IConfigHandler) {
|
||||
this.userChangeListener = undefined;
|
||||
}
|
||||
|
||||
|
|
@ -172,11 +172,36 @@ export class VerticalPerLineDiffManager {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
onlyOneInsertion?: boolean,
|
||||
quickEdit?: string,
|
||||
range?: vscode.Range,
|
||||
) {
|
||||
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
|
||||
|
||||
|
|
@ -188,9 +213,15 @@ export class VerticalPerLineDiffManager {
|
|||
|
||||
const filepath = editor.document.uri.fsPath;
|
||||
|
||||
// Initialize start/end at editor selection
|
||||
let startLine = editor.selection.start.line;
|
||||
let endLine = editor.selection.end.line;
|
||||
let startLine, endLine: number;
|
||||
|
||||
if (range) {
|
||||
startLine = range.start.line;
|
||||
endLine = range.end.line;
|
||||
} else {
|
||||
startLine = editor.selection.start.line;
|
||||
endLine = editor.selection.end.line;
|
||||
}
|
||||
|
||||
// Check for existing handlers in the same file the new one will be created in
|
||||
const existingHandler = this.getHandlerForFile(filepath);
|
||||
|
|
@ -274,11 +305,13 @@ export class VerticalPerLineDiffManager {
|
|||
llm.model,
|
||||
);
|
||||
|
||||
// Unselect the range
|
||||
editor.selection = new vscode.Selection(
|
||||
editor.selection.active,
|
||||
editor.selection.active,
|
||||
);
|
||||
if (editor.selection) {
|
||||
// Unselect the range
|
||||
editor.selection = new vscode.Selection(
|
||||
editor.selection.active,
|
||||
editor.selection.active,
|
||||
);
|
||||
}
|
||||
|
||||
vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { IContextProvider } from "core";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import { Core } from "core/core";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
|
||||
import { InProcessMessenger } from "core/util/messenger";
|
||||
|
|
@ -25,11 +25,12 @@ import { Battery } from "../util/battery";
|
|||
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
import { VsCodeMessenger } from "./VsCodeMessenger";
|
||||
import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig";
|
||||
|
||||
export class VsCodeExtension {
|
||||
// Currently some of these are public so they can be used in testing (test/test-suites)
|
||||
|
||||
private configHandler: ConfigHandler;
|
||||
private configHandler: IConfigHandler;
|
||||
private extensionContext: vscode.ExtensionContext;
|
||||
private ide: VsCodeIde;
|
||||
private tabAutocompleteModel: TabAutocompleteModel;
|
||||
|
|
@ -40,6 +41,7 @@ export class VsCodeExtension {
|
|||
webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
|
||||
private core: Core;
|
||||
private battery: Battery;
|
||||
private quickActionsCodeLensDisposable?: vscode.Disposable;
|
||||
|
||||
constructor(context: vscode.ExtensionContext) {
|
||||
let resolveWebviewProtocol: any = undefined;
|
||||
|
|
@ -64,7 +66,7 @@ export class VsCodeExtension {
|
|||
},
|
||||
);
|
||||
let resolveConfigHandler: any = undefined;
|
||||
const configHandlerPromise = new Promise<ConfigHandler>((resolve) => {
|
||||
const configHandlerPromise = new Promise<IConfigHandler>((resolve) => {
|
||||
resolveConfigHandler = resolve;
|
||||
});
|
||||
this.sidebar = new ContinueGUIWebviewViewProvider(
|
||||
|
|
@ -113,9 +115,6 @@ export class VsCodeExtension {
|
|||
});
|
||||
this.configHandler = this.core.configHandler;
|
||||
resolveConfigHandler?.(this.configHandler);
|
||||
this.configHandler.onConfigUpdate(() => {
|
||||
this.sidebar.webviewProtocol?.request("configUpdate", undefined);
|
||||
});
|
||||
|
||||
this.configHandler.reloadConfig();
|
||||
this.verticalDiffManager = new VerticalPerLineDiffManager(
|
||||
|
|
@ -131,14 +130,30 @@ export class VsCodeExtension {
|
|||
// Indexing + pause token
|
||||
this.diffManager.webviewProtocol = this.sidebar.webviewProtocol;
|
||||
|
||||
// CodeLens
|
||||
const verticalDiffCodeLens = registerAllCodeLensProviders(
|
||||
context,
|
||||
this.diffManager,
|
||||
this.verticalDiffManager.filepathToCodeLens,
|
||||
);
|
||||
this.verticalDiffManager.refreshCodeLens =
|
||||
verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens);
|
||||
this.configHandler.loadConfig().then((config) => {
|
||||
const { verticalDiffCodeLens } = registerAllCodeLensProviders(
|
||||
context,
|
||||
this.diffManager,
|
||||
this.verticalDiffManager.filepathToCodeLens,
|
||||
config,
|
||||
);
|
||||
|
||||
this.verticalDiffManager.refreshCodeLens =
|
||||
verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens);
|
||||
});
|
||||
|
||||
this.configHandler.onConfigUpdate((newConfig) => {
|
||||
this.sidebar.webviewProtocol?.request("configUpdate", undefined);
|
||||
|
||||
this.tabAutocompleteModel.clearLlm.bind(this.tabAutocompleteModel);
|
||||
|
||||
registerAllCodeLensProviders(
|
||||
context,
|
||||
this.diffManager,
|
||||
this.verticalDiffManager.filepathToCodeLens,
|
||||
newConfig,
|
||||
);
|
||||
});
|
||||
|
||||
// Tab autocomplete
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
|
|
@ -189,10 +204,6 @@ export class VsCodeExtension {
|
|||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
this.configHandler.onConfigUpdate(
|
||||
this.tabAutocompleteModel.clearLlm.bind(this.tabAutocompleteModel),
|
||||
);
|
||||
|
||||
vscode.workspace.onDidSaveTextDocument((event) => {
|
||||
// Listen for file changes in the workspace
|
||||
const filepath = event.uri.fsPath;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
|
||||
import { ToWebviewFromCoreProtocol } from "core/protocol/coreWebview";
|
||||
import { ToIdeFromWebviewOrCoreProtocol } from "core/protocol/ide";
|
||||
|
|
@ -70,7 +70,7 @@ export class VsCodeMessenger {
|
|||
private readonly webviewProtocol: VsCodeWebviewProtocol,
|
||||
private readonly ide: VsCodeIde,
|
||||
private readonly verticalDiffManagerPromise: Promise<VerticalPerLineDiffManager>,
|
||||
private readonly configHandlerPromise: Promise<ConfigHandler>,
|
||||
private readonly configHandlerPromise: Promise<IConfigHandler>,
|
||||
) {
|
||||
/** WEBVIEW ONLY LISTENERS **/
|
||||
this.onWebview("showFile", (msg) => {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ import type {
|
|||
Thread,
|
||||
} from "core";
|
||||
import { Range } from "core";
|
||||
import { defaultIgnoreDir, defaultIgnoreFile } from "core/indexing/ignore";
|
||||
import { walkDir } from "core/indexing/walkDir";
|
||||
import {
|
||||
editConfigJson,
|
||||
|
|
@ -505,15 +504,7 @@ class VsCodeIde implements IDE {
|
|||
}
|
||||
|
||||
async listDir(dir: string): Promise<[string, FileType][]> {
|
||||
const files = await vscode.workspace.fs.readDirectory(uriFromFilePath(dir));
|
||||
const results = files.filter(
|
||||
([name, type]) =>
|
||||
!(
|
||||
(type === vscode.FileType.File && defaultIgnoreFile.ignores(name)) ||
|
||||
(type === vscode.FileType.Directory && defaultIgnoreDir.ignores(name))
|
||||
),
|
||||
) as any;
|
||||
return results;
|
||||
return vscode.workspace.fs.readDirectory(uriFromFilePath(dir)) as any;
|
||||
}
|
||||
|
||||
getIdeSettingsSync(): IdeSettings {
|
||||
|
|
|
|||
|
|
@ -1,442 +0,0 @@
|
|||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import * as vscode from "vscode";
|
||||
import { DIFF_DIRECTORY, type DiffManager } from "../diff/horizontal";
|
||||
import type { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager";
|
||||
import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions";
|
||||
import { getAltOrOption, getMetaKeyLabel, getPlatform } from "../util/util";
|
||||
import { getExtensionUri } from "../util/vscode";
|
||||
|
||||
class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
|
||||
private _eventEmitter: vscode.EventEmitter<void> =
|
||||
new vscode.EventEmitter<void>();
|
||||
onDidChangeCodeLenses: vscode.Event<void> = this._eventEmitter.event;
|
||||
|
||||
public refresh(): void {
|
||||
this._eventEmitter.fire();
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly editorToVerticalDiffCodeLens: Map<
|
||||
string,
|
||||
VerticalDiffCodeLens[]
|
||||
>,
|
||||
) {}
|
||||
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const filepath = document.uri.fsPath;
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(filepath);
|
||||
if (!blocks) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const block = blocks[i];
|
||||
const start = new vscode.Position(block.start, 0);
|
||||
const range = new vscode.Range(
|
||||
start,
|
||||
start.translate(block.numGreen + block.numRed),
|
||||
);
|
||||
if (codeLenses.length === 0) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Accept All (${getMetaKeyLabel()}⇧↩)`,
|
||||
command: "continue.acceptDiff",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Reject All (${getMetaKeyLabel()}⇧⌫)`,
|
||||
command: "continue.rejectDiff",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
);
|
||||
}
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Accept${
|
||||
codeLenses.length === 2
|
||||
? ` (${getAltOrOption()}${getMetaKeyLabel()}Y)`
|
||||
: ""
|
||||
}`,
|
||||
command: "continue.acceptVerticalDiffBlock",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Reject${
|
||||
codeLenses.length === 2
|
||||
? ` (${getAltOrOption()}${getMetaKeyLabel()}N)`
|
||||
: ""
|
||||
}`,
|
||||
command: "continue.rejectVerticalDiffBlock",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
);
|
||||
if (codeLenses.length === 4) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `${getMetaKeyLabel()}I to add instructions`,
|
||||
command: "",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
||||
class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const suggestions = editorToSuggestions.get(document.uri.toString());
|
||||
if (!suggestions) {
|
||||
return [];
|
||||
}
|
||||
const locked = editorSuggestionsLocked.get(document.uri.fsPath.toString());
|
||||
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
for (const suggestion of suggestions) {
|
||||
const range = new vscode.Range(
|
||||
suggestion.oldRange.start,
|
||||
suggestion.newRange.end,
|
||||
);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Accept",
|
||||
command: "continue.acceptSuggestion",
|
||||
arguments: [suggestion],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Reject",
|
||||
command: "continue.rejectSuggestion",
|
||||
arguments: [suggestion],
|
||||
}),
|
||||
);
|
||||
if (codeLenses.length === 2) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `(${getMetaKeyLabel()}⇧⏎/${getMetaKeyLabel()}⇧⌫ to accept/reject all)`,
|
||||
command: "",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
||||
class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
|
||||
diffManager: DiffManager;
|
||||
|
||||
constructor(diffManager: DiffManager) {
|
||||
this.diffManager = diffManager;
|
||||
}
|
||||
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
let range = new vscode.Range(0, 0, 1, 0);
|
||||
const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath);
|
||||
if (diffInfo) {
|
||||
range = diffInfo.range;
|
||||
}
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Accept All ✅ (${getMetaKeyLabel()}⇧⏎)`,
|
||||
command: "continue.acceptDiff",
|
||||
arguments: [document.uri.fsPath],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Reject All ❌ (${getMetaKeyLabel()}⇧⌫)`,
|
||||
command: "continue.rejectDiff",
|
||||
arguments: [document.uri.fsPath],
|
||||
}),
|
||||
// new vscode.CodeLens(range, {
|
||||
// title: `Further Edit ✏️ (${getMetaKeyLabel()}⇧M)`,
|
||||
// command: "continue.focusContinueInputWithEdit",
|
||||
// })
|
||||
);
|
||||
return codeLenses;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ConfigPyCodeLensProvider implements vscode.CodeLensProvider {
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
|
||||
if (
|
||||
!document.uri.fsPath.endsWith(".continue/config.json") &&
|
||||
!document.uri.fsPath.endsWith(".continue\\config.json")
|
||||
) {
|
||||
return codeLenses;
|
||||
}
|
||||
|
||||
const lines = document.getText().split(os.EOL);
|
||||
const lineOfModels = lines.findIndex((line) =>
|
||||
line.includes('"models": ['),
|
||||
);
|
||||
|
||||
if (lineOfModels >= 0) {
|
||||
const range = new vscode.Range(lineOfModels, 0, lineOfModels + 1, 0);
|
||||
// codeLenses.push(
|
||||
// new vscode.CodeLens(range, {
|
||||
// title: `+ Add a Model`,
|
||||
// command: "continue.addModel",
|
||||
// })
|
||||
// );
|
||||
}
|
||||
|
||||
const lineOfSystemMessage = lines.findIndex((line) =>
|
||||
line.includes("ContinueConfig("),
|
||||
);
|
||||
|
||||
if (lineOfSystemMessage >= 0) {
|
||||
const range = new vscode.Range(
|
||||
lineOfSystemMessage,
|
||||
0,
|
||||
lineOfSystemMessage + 1,
|
||||
0,
|
||||
);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "✏️ Edit in UI",
|
||||
command: "continue.openSettingsUI",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
||||
interface TutorialCodeLensItems {
|
||||
lineIncludes: string;
|
||||
commands: vscode.Command[];
|
||||
}
|
||||
|
||||
const cmdCtrl = getPlatform() === "mac" ? "Cmd" : "Ctrl";
|
||||
|
||||
const actions: TutorialCodeLensItems[] = [
|
||||
{
|
||||
lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+L]`,
|
||||
commands: [
|
||||
{
|
||||
title: `${cmdCtrl}+L`,
|
||||
command: "continue.focusContinueInput",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: "Step 3: Ask a question",
|
||||
commands: [
|
||||
{
|
||||
title: `"what does this code do?"`,
|
||||
command: "continue.sendMainUserInput",
|
||||
arguments: ["what does this code do?"],
|
||||
},
|
||||
{
|
||||
title: `"what is an alternative to this?"`,
|
||||
command: "continue.sendMainUserInput",
|
||||
arguments: ["what is an alternative to this?"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+I] to edit`,
|
||||
commands: [
|
||||
{
|
||||
title: `${cmdCtrl}+I`,
|
||||
command: "continue.quickEdit",
|
||||
arguments: ["Add comments"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: "Step 1: Run this Python file",
|
||||
commands: [
|
||||
{
|
||||
title: "Run the file",
|
||||
command: "continue.sendToTerminal",
|
||||
arguments: [
|
||||
`python ${path.join(
|
||||
getExtensionUri().fsPath,
|
||||
"continue_tutorial.py",
|
||||
)}\n`,
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: "Step 2: Use the keyboard shortcut cmd/ctrl + shift + R",
|
||||
commands: [
|
||||
{
|
||||
title: "Debug the error",
|
||||
command: "continue.debugTerminal",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+Shift+R]`,
|
||||
commands: [
|
||||
{
|
||||
title: `${cmdCtrl}+Shift+R`,
|
||||
command: "continue.debugTerminal",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
class TutorialCodeLensProvider implements vscode.CodeLensProvider {
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
|
||||
if (!document.uri.fsPath.endsWith("continue_tutorial.py")) {
|
||||
return codeLenses;
|
||||
}
|
||||
|
||||
const lines = document.getText().split(os.EOL);
|
||||
|
||||
for (const action of actions) {
|
||||
const lineOfAction = lines.findIndex((line) =>
|
||||
line.includes(action.lineIncludes),
|
||||
);
|
||||
|
||||
if (lineOfAction >= 0) {
|
||||
const range = new vscode.Range(lineOfAction, 0, lineOfAction + 1, 0);
|
||||
for (const command of action.commands) {
|
||||
codeLenses.push(new vscode.CodeLens(range, command));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const lineOf11 = lines.findIndex((line) =>
|
||||
line.includes("Step 1: Highlight the function below"),
|
||||
);
|
||||
if (lineOf11 >= 0) {
|
||||
const range = new vscode.Range(lineOf11, 0, lineOf11 + 1, 0);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Highlight the function",
|
||||
command: "continue.selectRange",
|
||||
arguments: [lineOf11 + 3, lineOf11 + 11],
|
||||
}),
|
||||
);
|
||||
}
|
||||
const lineOf21 = lines.findIndex((line) =>
|
||||
line.includes("Step 1: Highlight this code"),
|
||||
);
|
||||
if (lineOf21 >= 0) {
|
||||
const range = new vscode.Range(lineOf21, 0, lineOf21 + 1, 0);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Highlight the function",
|
||||
command: "continue.selectRange",
|
||||
arguments: [lineOf21 + 3, lineOf21 + 14],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Folding of the tutorial
|
||||
// const regionLines = lines
|
||||
// .map((line, i) => [line, i])
|
||||
// .filter(([line, i]) => (line as string).startsWith("# region "))
|
||||
// .map(([line, i]) => i);
|
||||
// for (const lineOfRegion of regionLines as number[]) {
|
||||
// const range = new vscode.Range(lineOfRegion, 0, lineOfRegion + 1, 0);
|
||||
|
||||
// const linesToFold = regionLines
|
||||
// .filter((i) => lineOfRegion !== i)
|
||||
// .flatMap((i) => {
|
||||
// return [i, (i as number) + 1];
|
||||
// });
|
||||
// codeLenses.push(
|
||||
// new vscode.CodeLens(range, {
|
||||
// title: `Begin Section`,
|
||||
// command: "continue.foldAndUnfold",
|
||||
// arguments: [linesToFold, [lineOfRegion, lineOfRegion + 1]],
|
||||
// }),
|
||||
// );
|
||||
// }
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
||||
export let verticalPerLineCodeLensProvider: vscode.Disposable | undefined =
|
||||
undefined;
|
||||
let diffsCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
|
||||
export function registerAllCodeLensProviders(
|
||||
context: vscode.ExtensionContext,
|
||||
diffManager: DiffManager,
|
||||
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]>,
|
||||
) {
|
||||
if (verticalPerLineCodeLensProvider) {
|
||||
verticalPerLineCodeLensProvider.dispose();
|
||||
}
|
||||
if (suggestionsCodeLensDisposable) {
|
||||
suggestionsCodeLensDisposable.dispose();
|
||||
}
|
||||
if (diffsCodeLensDisposable) {
|
||||
diffsCodeLensDisposable.dispose();
|
||||
}
|
||||
if (configPyCodeLensDisposable) {
|
||||
configPyCodeLensDisposable.dispose();
|
||||
}
|
||||
if (tutorialCodeLensDisposable) {
|
||||
tutorialCodeLensDisposable.dispose();
|
||||
}
|
||||
|
||||
const verticalDiffCodeLens = new VerticalPerLineCodeLensProvider(
|
||||
editorToVerticalDiffCodeLens,
|
||||
);
|
||||
verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
verticalDiffCodeLens,
|
||||
);
|
||||
suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
new SuggestionsCodeLensProvider(),
|
||||
);
|
||||
diffsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
new DiffViewerCodeLensProvider(diffManager),
|
||||
);
|
||||
configPyCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
new ConfigPyCodeLensProvider(),
|
||||
);
|
||||
tutorialCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
new TutorialCodeLensProvider(),
|
||||
);
|
||||
context.subscriptions.push(verticalPerLineCodeLensProvider);
|
||||
context.subscriptions.push(suggestionsCodeLensDisposable);
|
||||
context.subscriptions.push(diffsCodeLensDisposable);
|
||||
context.subscriptions.push(configPyCodeLensDisposable);
|
||||
context.subscriptions.push(tutorialCodeLensDisposable);
|
||||
|
||||
return verticalDiffCodeLens;
|
||||
}
|
||||
1
extensions/vscode/src/lang-server/codeLens/index.ts
Normal file
1
extensions/vscode/src/lang-server/codeLens/index.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export { registerAllCodeLensProviders } from "./registerAllCodeLensProviders";
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import * as vscode from "vscode";
|
||||
import * as os from "os";
|
||||
|
||||
export class ConfigPyCodeLensProvider implements vscode.CodeLensProvider {
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
|
||||
if (
|
||||
!document.uri.fsPath.endsWith(".continue/config.json") &&
|
||||
!document.uri.fsPath.endsWith(".continue\\config.json")
|
||||
) {
|
||||
return codeLenses;
|
||||
}
|
||||
|
||||
const lines = document.getText().split(os.EOL);
|
||||
const lineOfModels = lines.findIndex((line) =>
|
||||
line.includes('"models": ['),
|
||||
);
|
||||
|
||||
const lineOfSystemMessage = lines.findIndex((line) =>
|
||||
line.includes("ContinueConfig("),
|
||||
);
|
||||
|
||||
if (lineOfSystemMessage >= 0) {
|
||||
const range = new vscode.Range(
|
||||
lineOfSystemMessage,
|
||||
0,
|
||||
lineOfSystemMessage + 1,
|
||||
0,
|
||||
);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "✏️ Edit in UI",
|
||||
command: "continue.openSettingsUI",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import path from "path";
|
||||
import * as vscode from "vscode";
|
||||
import { DiffManager, DIFF_DIRECTORY } from "../../../diff/horizontal";
|
||||
import { getMetaKeyLabel } from "../../../util/util";
|
||||
|
||||
export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
|
||||
diffManager: DiffManager;
|
||||
|
||||
constructor(diffManager: DiffManager) {
|
||||
this.diffManager = diffManager;
|
||||
}
|
||||
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
let range = new vscode.Range(0, 0, 1, 0);
|
||||
const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath);
|
||||
if (diffInfo) {
|
||||
range = diffInfo.range;
|
||||
}
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Accept All ✅ (${getMetaKeyLabel()}⇧⏎)`,
|
||||
command: "continue.acceptDiff",
|
||||
arguments: [document.uri.fsPath],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Reject All ❌ (${getMetaKeyLabel()}⇧⌫)`,
|
||||
command: "continue.rejectDiff",
|
||||
arguments: [document.uri.fsPath],
|
||||
}),
|
||||
);
|
||||
return codeLenses;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
import { ContinueConfig, QuickActionConfig } from "core";
|
||||
import * as vscode from "vscode";
|
||||
import {
|
||||
CONTINUE_WORKSPACE_KEY,
|
||||
getContinueWorkspaceConfig,
|
||||
} from "../../../util/workspaceConfig";
|
||||
import { isTutorialFile } from "./TutorialCodeLensProvider";
|
||||
import { Telemetry } from "core/util/posthog";
|
||||
|
||||
export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions";
|
||||
|
||||
export function getQuickActionsConfig(config: ContinueConfig) {
|
||||
return config.experimental?.quickActions;
|
||||
}
|
||||
|
||||
export function subscribeToVSCodeQuickActionsSettings(listener: Function) {
|
||||
vscode.workspace.onDidChangeConfiguration((e) => {
|
||||
const configKey = `${CONTINUE_WORKSPACE_KEY}.${ENABLE_QUICK_ACTIONS_KEY}`;
|
||||
|
||||
if (e.affectsConfiguration(configKey)) {
|
||||
Telemetry.capture("VSCode Quick Actions Settings Changed", {
|
||||
enabled: quickActionsEnabledStatus(),
|
||||
});
|
||||
|
||||
listener();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function toggleQuickActions() {
|
||||
const curStatus = quickActionsEnabledStatus();
|
||||
|
||||
getContinueWorkspaceConfig().update(ENABLE_QUICK_ACTIONS_KEY, curStatus);
|
||||
}
|
||||
|
||||
export function quickActionsEnabledStatus() {
|
||||
return getContinueWorkspaceConfig().get<boolean>(ENABLE_QUICK_ACTIONS_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* A CodeLensProvider for Quick Actions.
|
||||
*
|
||||
* This class provides code lenses for Quick Actions, which can be either custom or default actions.
|
||||
* It supports actions for functions and classes, and can be configured with custom quick action settings.
|
||||
*/
|
||||
export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider {
|
||||
/**
|
||||
* Defines which code elements are eligible for Quick Actions.
|
||||
*
|
||||
* Right now, we only allow functions, methods and classes
|
||||
* to keep things simple.
|
||||
*/
|
||||
static quickActionSymbolKinds = [
|
||||
vscode.SymbolKind.Function,
|
||||
vscode.SymbolKind.Method,
|
||||
vscode.SymbolKind.Class,
|
||||
];
|
||||
|
||||
customQuickActionsConfig?: QuickActionConfig[];
|
||||
|
||||
constructor(customQuickActionsConfigs?: QuickActionConfig[]) {
|
||||
if (customQuickActionsConfigs) {
|
||||
this.customQuickActionsConfig = customQuickActionsConfigs;
|
||||
}
|
||||
}
|
||||
|
||||
getCustomCommands(
|
||||
code: string,
|
||||
range: vscode.Range,
|
||||
quickActionConfigs: QuickActionConfig[],
|
||||
): vscode.Command[] {
|
||||
return quickActionConfigs.map(({ title, prompt, sendToChat }) => {
|
||||
return sendToChat
|
||||
? {
|
||||
title,
|
||||
command: "continue.customQuickActionSendToChat",
|
||||
arguments: [prompt, code],
|
||||
}
|
||||
: {
|
||||
title,
|
||||
command: "continue.customQuickActionStreamInlineEdit",
|
||||
arguments: [prompt, range],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
getDefaultCommands(code: string, range: vscode.Range): vscode.Command[] {
|
||||
const explain: vscode.Command = {
|
||||
command: "continue.defaultQuickActionExplain",
|
||||
title: "Explain",
|
||||
arguments: [code],
|
||||
};
|
||||
|
||||
const comment: vscode.Command = {
|
||||
command: "continue.defaultQuickActionDocstring",
|
||||
title: "Docstring",
|
||||
arguments: [range],
|
||||
};
|
||||
|
||||
return [explain, comment];
|
||||
}
|
||||
|
||||
async provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
): Promise<vscode.CodeLens[]> {
|
||||
// The tutorial file already has a lot of Code Lenses
|
||||
// so we don't want to add more to it.
|
||||
if (isTutorialFile(document.uri)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
|
||||
if (!editor) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const symbols = await vscode.commands.executeCommand<
|
||||
Array<vscode.DocumentSymbol>
|
||||
>("vscode.executeDocumentSymbolProvider", document.uri);
|
||||
|
||||
const filteredSmybols = symbols?.filter((def) =>
|
||||
QuickActionsCodeLensProvider.quickActionSymbolKinds.includes(def.kind),
|
||||
);
|
||||
|
||||
return filteredSmybols.flatMap(({ range }) => {
|
||||
const code = editor.document.getText(range);
|
||||
|
||||
const commands: vscode.Command[] = !!this.customQuickActionsConfig
|
||||
? this.getCustomCommands(code, range, this.customQuickActionsConfig)
|
||||
: this.getDefaultCommands(code, range);
|
||||
|
||||
return commands.map((command) => new vscode.CodeLens(range, command));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
import * as vscode from "vscode";
|
||||
import { editorToSuggestions } from "../../../suggestions";
|
||||
import { getMetaKeyLabel } from "../../../util/util";
|
||||
|
||||
export class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const suggestions = editorToSuggestions.get(document.uri.toString());
|
||||
if (!suggestions) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
for (const suggestion of suggestions) {
|
||||
const range = new vscode.Range(
|
||||
suggestion.oldRange.start,
|
||||
suggestion.newRange.end,
|
||||
);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Accept",
|
||||
command: "continue.acceptSuggestion",
|
||||
arguments: [suggestion],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Reject",
|
||||
command: "continue.rejectSuggestion",
|
||||
arguments: [suggestion],
|
||||
}),
|
||||
);
|
||||
if (codeLenses.length === 2) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `(${getMetaKeyLabel()}⇧⏎/${getMetaKeyLabel()}⇧⌫ to accept/reject all)`,
|
||||
command: "",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
import * as os from "node:os";
|
||||
import path from "path";
|
||||
import * as vscode from "vscode";
|
||||
import { getPlatform } from "../../../util/util";
|
||||
import { getExtensionUri } from "../../../util/vscode";
|
||||
|
||||
interface TutorialCodeLensItems {
|
||||
lineIncludes: string;
|
||||
commands: vscode.Command[];
|
||||
}
|
||||
|
||||
const TUTORIAL_FILE_NAME = "continue_tutorial.py";
|
||||
|
||||
const cmdCtrl = getPlatform() === "mac" ? "Cmd" : "Ctrl";
|
||||
|
||||
const actions: TutorialCodeLensItems[] = [
|
||||
{
|
||||
lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+L]`,
|
||||
commands: [
|
||||
{
|
||||
title: `${cmdCtrl}+L`,
|
||||
command: "continue.focusContinueInput",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: "Step 3: Ask a question",
|
||||
commands: [
|
||||
{
|
||||
title: `"what does this code do?"`,
|
||||
command: "continue.sendMainUserInput",
|
||||
arguments: ["what does this code do?"],
|
||||
},
|
||||
{
|
||||
title: `"what is an alternative to this?"`,
|
||||
command: "continue.sendMainUserInput",
|
||||
arguments: ["what is an alternative to this?"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+I] to edit`,
|
||||
commands: [
|
||||
{
|
||||
title: `${cmdCtrl}+I`,
|
||||
command: "continue.quickEdit",
|
||||
arguments: ["Add comments"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: "Step 1: Run this Python file",
|
||||
commands: [
|
||||
{
|
||||
title: "Run the file",
|
||||
command: "continue.sendToTerminal",
|
||||
arguments: [
|
||||
`python ${path.join(
|
||||
getExtensionUri().fsPath,
|
||||
"continue_tutorial.py",
|
||||
)}\n`,
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: "Step 2: Use the keyboard shortcut cmd/ctrl + shift + R",
|
||||
commands: [
|
||||
{
|
||||
title: "Debug the error",
|
||||
command: "continue.debugTerminal",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+Shift+R]`,
|
||||
commands: [
|
||||
{
|
||||
title: `${cmdCtrl}+Shift+R`,
|
||||
command: "continue.debugTerminal",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function isTutorialFile(uri: vscode.Uri) {
|
||||
return uri.fsPath.endsWith(TUTORIAL_FILE_NAME);
|
||||
}
|
||||
|
||||
export class TutorialCodeLensProvider implements vscode.CodeLensProvider {
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
|
||||
if (!isTutorialFile(document.uri)) {
|
||||
return codeLenses;
|
||||
}
|
||||
|
||||
const lines = document.getText().split(os.EOL);
|
||||
|
||||
for (const action of actions) {
|
||||
const lineOfAction = lines.findIndex((line) =>
|
||||
line.includes(action.lineIncludes),
|
||||
);
|
||||
|
||||
if (lineOfAction >= 0) {
|
||||
const range = new vscode.Range(lineOfAction, 0, lineOfAction + 1, 0);
|
||||
for (const command of action.commands) {
|
||||
codeLenses.push(new vscode.CodeLens(range, command));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const lineOf11 = lines.findIndex((line) =>
|
||||
line.includes("Step 1: Highlight the function below"),
|
||||
);
|
||||
if (lineOf11 >= 0) {
|
||||
const range = new vscode.Range(lineOf11, 0, lineOf11 + 1, 0);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Highlight the function",
|
||||
command: "continue.selectRange",
|
||||
arguments: [lineOf11 + 3, lineOf11 + 11],
|
||||
}),
|
||||
);
|
||||
}
|
||||
const lineOf21 = lines.findIndex((line) =>
|
||||
line.includes("Step 1: Highlight this code"),
|
||||
);
|
||||
if (lineOf21 >= 0) {
|
||||
const range = new vscode.Range(lineOf21, 0, lineOf21 + 1, 0);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Highlight the function",
|
||||
command: "continue.selectRange",
|
||||
arguments: [lineOf21 + 3, lineOf21 + 14],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import * as vscode from "vscode";
|
||||
import { VerticalDiffCodeLens } from "../../../diff/verticalPerLine/manager";
|
||||
import { getAltOrOption, getMetaKeyLabel } from "../../../util/util";
|
||||
|
||||
export class VerticalPerLineCodeLensProvider
|
||||
implements vscode.CodeLensProvider
|
||||
{
|
||||
private _eventEmitter: vscode.EventEmitter<void> =
|
||||
new vscode.EventEmitter<void>();
|
||||
|
||||
onDidChangeCodeLenses: vscode.Event<void> = this._eventEmitter.event;
|
||||
|
||||
public refresh(): void {
|
||||
this._eventEmitter.fire();
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly editorToVerticalDiffCodeLens: Map<
|
||||
string,
|
||||
VerticalDiffCodeLens[]
|
||||
>,
|
||||
) {}
|
||||
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken,
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const filepath = document.uri.fsPath;
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(filepath);
|
||||
|
||||
if (!blocks) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const isFirstBlockInMultiBlockDocument =
|
||||
codeLenses.length === 0 && blocks.length > 1;
|
||||
|
||||
const block = blocks[i];
|
||||
const start = new vscode.Position(block.start, 0);
|
||||
const range = new vscode.Range(
|
||||
start,
|
||||
start.translate(block.numGreen + block.numRed),
|
||||
);
|
||||
|
||||
if (isFirstBlockInMultiBlockDocument) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Accept All (${getMetaKeyLabel()}⇧↩)`,
|
||||
command: "continue.acceptDiff",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Reject All (${getMetaKeyLabel()}⇧⌫)`,
|
||||
command: "continue.rejectDiff",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Accept${
|
||||
codeLenses.length === 2
|
||||
? ` (${getAltOrOption()}${getMetaKeyLabel()}Y)`
|
||||
: ""
|
||||
}`,
|
||||
command: "continue.acceptVerticalDiffBlock",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: `Reject${
|
||||
codeLenses.length === 2
|
||||
? ` (${getAltOrOption()}${getMetaKeyLabel()}N)`
|
||||
: ""
|
||||
}`,
|
||||
command: "continue.rejectVerticalDiffBlock",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
);
|
||||
|
||||
if (codeLenses.length === 4) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `${getMetaKeyLabel()}I to add instructions`,
|
||||
command: "",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export { ConfigPyCodeLensProvider } from "./ConfigPyCodeLensProvider";
|
||||
export { DiffViewerCodeLensProvider } from "./DiffViewerCodeLensProvider";
|
||||
export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider";
|
||||
export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider";
|
||||
export { TutorialCodeLensProvider } from "./TutorialCodeLensProvider";
|
||||
export { VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider";
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
import { ContinueConfig } from "core";
|
||||
import * as vscode from "vscode";
|
||||
import { VerticalDiffCodeLens } from "../../diff/verticalPerLine/manager";
|
||||
import { DiffManager } from "../../diff/horizontal";
|
||||
import * as providers from "./providers";
|
||||
import {
|
||||
getQuickActionsConfig,
|
||||
quickActionsEnabledStatus,
|
||||
subscribeToVSCodeQuickActionsSettings,
|
||||
} from "./providers/QuickActionsCodeLensProvider";
|
||||
|
||||
const { registerCodeLensProvider } = vscode.languages;
|
||||
|
||||
export let verticalPerLineCodeLensProvider: vscode.Disposable | undefined =
|
||||
undefined;
|
||||
let diffsCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let quickActionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
|
||||
/**
|
||||
* Registers the Quick Actions CodeLens provider if Quick Actions are enabled.
|
||||
*
|
||||
* This function checks if Quick Actions are enabled in the VSCode workspace settings,
|
||||
* and if so, it registers a new QuickActionsCodeLensProvider. If the user has custom
|
||||
* actions defined in their config, it initiaizes the provider with these actions.
|
||||
*
|
||||
* If a previous provider was registered, it is disposed of before the new one is created.
|
||||
*
|
||||
* @param config - The Continue configuration object
|
||||
* @param context - The VS Code extension context
|
||||
*/
|
||||
function registerQuickActionsProvider(
|
||||
config: ContinueConfig,
|
||||
context: vscode.ExtensionContext,
|
||||
) {
|
||||
if (quickActionsCodeLensDisposable) {
|
||||
quickActionsCodeLensDisposable.dispose();
|
||||
}
|
||||
|
||||
if (quickActionsEnabledStatus()) {
|
||||
const quickActionsConfig = getQuickActionsConfig(config);
|
||||
|
||||
quickActionsCodeLensDisposable = registerCodeLensProvider(
|
||||
"*",
|
||||
new providers.QuickActionsCodeLensProvider(quickActionsConfig),
|
||||
);
|
||||
|
||||
context.subscriptions.push(quickActionsCodeLensDisposable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers all CodeLens providers for the Continue extension.
|
||||
*
|
||||
* This function disposes of any existing CodeLens providers and registers new ones for:
|
||||
* - Vertical per-line diffs
|
||||
* - Suggestions
|
||||
* - Diff viewer
|
||||
* - Config.py
|
||||
* - Tutorial
|
||||
* - Quick Actions
|
||||
*
|
||||
* It also sets up a subscription to VS Code Quick Actions settings changes.
|
||||
*
|
||||
* @param context - The VS Code extension context
|
||||
* @param diffManager - The DiffManager instance for managing diffs
|
||||
* @param editorToVerticalDiffCodeLens - A Map of editor IDs to VerticalDiffCodeLens arrays
|
||||
* @param config - The Continue configuration object
|
||||
*
|
||||
* @returns An object containing the verticalDiffCodeLens provider
|
||||
*/
|
||||
export function registerAllCodeLensProviders(
|
||||
context: vscode.ExtensionContext,
|
||||
diffManager: DiffManager,
|
||||
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]>,
|
||||
config: ContinueConfig,
|
||||
) {
|
||||
if (verticalPerLineCodeLensProvider) {
|
||||
verticalPerLineCodeLensProvider.dispose();
|
||||
}
|
||||
|
||||
if (suggestionsCodeLensDisposable) {
|
||||
suggestionsCodeLensDisposable.dispose();
|
||||
}
|
||||
|
||||
if (diffsCodeLensDisposable) {
|
||||
diffsCodeLensDisposable.dispose();
|
||||
}
|
||||
|
||||
if (configPyCodeLensDisposable) {
|
||||
configPyCodeLensDisposable.dispose();
|
||||
}
|
||||
|
||||
if (tutorialCodeLensDisposable) {
|
||||
tutorialCodeLensDisposable.dispose();
|
||||
}
|
||||
|
||||
const verticalDiffCodeLens = new providers.VerticalPerLineCodeLensProvider(
|
||||
editorToVerticalDiffCodeLens,
|
||||
);
|
||||
|
||||
verticalPerLineCodeLensProvider = registerCodeLensProvider(
|
||||
"*",
|
||||
verticalDiffCodeLens,
|
||||
);
|
||||
|
||||
suggestionsCodeLensDisposable = registerCodeLensProvider(
|
||||
"*",
|
||||
new providers.SuggestionsCodeLensProvider(),
|
||||
);
|
||||
|
||||
diffsCodeLensDisposable = registerCodeLensProvider(
|
||||
"*",
|
||||
new providers.DiffViewerCodeLensProvider(diffManager),
|
||||
);
|
||||
|
||||
configPyCodeLensDisposable = registerCodeLensProvider(
|
||||
"*",
|
||||
new providers.ConfigPyCodeLensProvider(),
|
||||
);
|
||||
|
||||
tutorialCodeLensDisposable = registerCodeLensProvider(
|
||||
"*",
|
||||
new providers.TutorialCodeLensProvider(),
|
||||
);
|
||||
|
||||
registerQuickActionsProvider(config, context);
|
||||
|
||||
subscribeToVSCodeQuickActionsSettings(() =>
|
||||
registerQuickActionsProvider(config, context),
|
||||
);
|
||||
|
||||
context.subscriptions.push(verticalPerLineCodeLensProvider);
|
||||
context.subscriptions.push(suggestionsCodeLensDisposable);
|
||||
context.subscriptions.push(diffsCodeLensDisposable);
|
||||
context.subscriptions.push(configPyCodeLensDisposable);
|
||||
context.subscriptions.push(tutorialCodeLensDisposable);
|
||||
|
||||
return { verticalDiffCodeLens };
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { IDE } from "core";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import { fetchwithRequestOptions } from "core/util/fetchWithOptions";
|
||||
import * as vscode from "vscode";
|
||||
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
|
||||
|
|
@ -17,7 +17,7 @@ interface QuickEditFlowStuff {
|
|||
export class QuickEdit {
|
||||
constructor(
|
||||
private readonly verticalDiffManager: VerticalPerLineDiffManager,
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly configHandler: IConfigHandler,
|
||||
private readonly webviewProtocol: VsCodeWebviewProtocol,
|
||||
private readonly ide: IDE,
|
||||
private readonly context: vscode.ExtensionContext,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
} from "core/util/paths";
|
||||
import * as fs from "fs";
|
||||
import * as vscode from "vscode";
|
||||
import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig";
|
||||
|
||||
export class RemoteConfigSync {
|
||||
private userToken: string | null;
|
||||
|
|
@ -28,7 +29,7 @@ export class RemoteConfigSync {
|
|||
|
||||
// Listen for changes to VS Code settings, then trigger a refresh
|
||||
vscode.workspace.onDidChangeConfiguration(async (event) => {
|
||||
if (event.affectsConfiguration("continue")) {
|
||||
if (event.affectsConfiguration(CONTINUE_WORKSPACE_KEY)) {
|
||||
const { userToken, remoteConfigServerUrl, remoteConfigSyncPeriod } =
|
||||
await this.loadVsCodeSettings();
|
||||
if (
|
||||
|
|
@ -92,13 +93,12 @@ export class RemoteConfigSync {
|
|||
if (this.syncInterval !== undefined) {
|
||||
clearInterval(this.syncInterval);
|
||||
}
|
||||
this.syncInterval = setInterval(
|
||||
() => {
|
||||
if (!this.userToken || !this.remoteConfigServerUrl) return;
|
||||
this.sync(this.userToken, this.remoteConfigServerUrl);
|
||||
},
|
||||
this.remoteConfigSyncPeriod * 1000 * 60,
|
||||
);
|
||||
this.syncInterval = setInterval(() => {
|
||||
if (!this.userToken || !this.remoteConfigServerUrl) {
|
||||
return;
|
||||
}
|
||||
this.sync(this.userToken, this.remoteConfigServerUrl);
|
||||
}, this.remoteConfigSyncPeriod * 1000 * 60);
|
||||
}
|
||||
|
||||
async sync(userToken: string, remoteConfigServerUrl: string) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { ILLM } from "core";
|
||||
import type { ConfigHandler } from "core/config/handler";
|
||||
import { IConfigHandler } from "core/config/IConfigHandler";
|
||||
import Ollama from "core/llm/llms/Ollama";
|
||||
import { GlobalContext } from "core/util/GlobalContext";
|
||||
import * as vscode from "vscode";
|
||||
|
|
@ -13,9 +13,9 @@ export class TabAutocompleteModel {
|
|||
private shownOllamaWarning = false;
|
||||
private shownDeepseekWarning = false;
|
||||
|
||||
private configHandler: ConfigHandler;
|
||||
private configHandler: IConfigHandler;
|
||||
|
||||
constructor(configHandler: ConfigHandler) {
|
||||
constructor(configHandler: IConfigHandler) {
|
||||
this.configHandler = configHandler;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,12 @@ const os = require("node:os");
|
|||
import * as vscode from "vscode";
|
||||
|
||||
function charIsEscapedAtIndex(index: number, str: string): boolean {
|
||||
if (index === 0) return false;
|
||||
if (str[index - 1] !== "\\") return false;
|
||||
if (index === 0) {
|
||||
return false;
|
||||
}
|
||||
if (str[index - 1] !== "\\") {
|
||||
return false;
|
||||
}
|
||||
return !charIsEscapedAtIndex(index - 1, str);
|
||||
}
|
||||
|
||||
|
|
|
|||
7
extensions/vscode/src/util/workspaceConfig.ts
Normal file
7
extensions/vscode/src/util/workspaceConfig.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { workspace } from "vscode";
|
||||
|
||||
export const CONTINUE_WORKSPACE_KEY = "continue";
|
||||
|
||||
export function getContinueWorkspaceConfig() {
|
||||
return workspace.getConfiguration(CONTINUE_WORKSPACE_KEY);
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue