chore: merge main

This commit is contained in:
Dallin Romney 2025-07-24 23:45:10 +07:00
commit 067d085358
140 changed files with 5983 additions and 1289 deletions

View file

@ -0,0 +1,6 @@
---
globs: "**/*.{ts,tsx}"
alwaysApply: false
---
Use enums instead of simple string unions when possible in TypeScript code

View file

@ -8,9 +8,9 @@
- [] The relevant docs, if any, have been updated or created
- [] The relevant tests, if any, have been updated or created
## Screenshots
## Screen recording or screenshot
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
[ When applicable, please include a short screen recording or screenshot - this makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example. ]
## Tests

View file

@ -63,7 +63,6 @@ jobs:
- name: Bump version in gradle.properties
run: |
cd extensions/intellij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
@ -224,10 +223,6 @@ jobs:
# apple-product-id: dev.continue.continue-binary
# options: --options runtime --entitlements entitlements.xml
# Build plugin
- name: Build plugin
run: ./gradlew buildPlugin
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
@ -237,7 +232,7 @@ jobs:
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: eap
run: ./gradlew publishPlugin
run: ./gradlew publishPlugin --info --stacktrace
- name: Publish Stable Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
@ -247,7 +242,7 @@ jobs:
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: default
run: ./gradlew publishPlugin
run: ./gradlew publishPlugin --info --stacktrace
# Prepare plugin archive content for creating artifact
- name: Prepare Plugin Artifact

View file

@ -192,6 +192,7 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
- **For new features**: Include a short screen recording or screenshot demonstrating the new functionality. This makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example
- Open a PR against the `main` branch. Make sure to fill in the PR template
### Formatting

View file

@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
import { shouldPrefilter } from "./prefiltering/index.js";
import { getAllSnippets } from "./snippets/index.js";
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
import { renderPrompt } from "./templating/index.js";
import { GetLspDefinitionsFunction } from "./types.js";
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
@ -121,6 +121,12 @@ export class CompletionProvider {
...config?.tabAutocompleteOptions,
...llm.autocompleteOptions,
};
// Enable static contextualization if defined.
if (config?.experimental?.enableStaticContextualization) {
options.experimental_enableStaticContextualization = true;
}
return options;
}
@ -171,7 +177,7 @@ export class CompletionProvider {
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
getAllSnippetsWithoutRace({
helper,
ide: this.ide,
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@ -258,6 +264,10 @@ export class CompletionProvider {
...helper.options,
};
if (options.experimental_enableStaticContextualization) {
outcome.enabledStaticContextualization = true;
}
//////////
// Save to cache

View file

@ -2,16 +2,19 @@ import { IDE } from "../..";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { getSymbolsForSnippet } from "./ranking";
import { RootPathContextService } from "./root-path-context/RootPathContextService";
import { StaticContextService } from "./static-context/StaticContextService";
export class ContextRetrievalService {
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private staticContextService: StaticContextService;
constructor(private readonly ide: IDE) {
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
@ -19,6 +22,7 @@ export class ContextRetrievalService {
this.importDefinitionsService,
this.ide,
);
this.staticContextService = new StaticContextService(this.ide);
}
public async getSnippetsFromImportDefinitions(
@ -71,6 +75,12 @@ export class ContextRetrievalService {
);
}
public async getStaticContextSnippets(
helper: HelperVars,
): Promise<AutocompleteStaticSnippet[]> {
return this.staticContextService.getContext(helper);
}
/**
* Initialize the import definitions cache for a file.
* This is normally done automatically when the active text editor changes,

View file

@ -0,0 +1,888 @@
import * as fs from "fs/promises";
import path from "path";
import { pathToFileURL } from "url";
import Parser from "web-tree-sitter";
import { IDE, Position } from "../../..";
import { localPathOrUriToPath } from "../../../util/pathToUri";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import {
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../../snippets/types";
import { getAst } from "../../util/ast";
import { HelperVars } from "../../util/HelperVars";
import {
extractFunctionTypeFromDecl,
extractTopLevelDecls,
findEnclosingTypeDeclaration,
unwrapToBaseType,
} from "./tree-sitter-utils";
import {
HoleContext,
RelevantHeaders,
RelevantTypes,
StaticContext,
TypeSpanAndSourceFile,
TypeSpanAndSourceFileAndAst,
} from "./types";
export class StaticContextService {
private readonly ide: IDE;
constructor(ide: IDE) {
this.ide = ide;
}
public logAutocompleteStaticSnippet(
ctx: StaticContext,
label = "Static Snippet",
) {
console.log(`=== ${label} ===`);
console.log("Hole Type:", ctx.holeType);
console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`);
ctx.relevantTypes.forEach((types, filepath) => {
console.log(` 📁 ${filepath}`);
types.forEach((type) => console.log(` • ${type}`));
});
console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`);
ctx.relevantHeaders.forEach((headers, filepath) => {
console.log(` 📁 ${filepath}`);
headers.forEach((header) => console.log(` • ${header}`));
});
}
public static formatAutocompleteStaticSnippet(ctx: StaticContext): string {
let output = `AutocompleteStaticSnippet:\n`;
output += ` holeType: ${ctx.holeType}\n`;
output += ` relevantTypes:\n`;
if (ctx.relevantTypes.size === 0) {
output += ` (none)\n`;
} else {
ctx.relevantTypes.forEach((types, filepath) => {
output += ` ${filepath}: [${types.join(", ")}]\n`;
});
}
output += ` relevantHeaders:\n`;
if (ctx.relevantHeaders.size === 0) {
output += ` (none)\n`;
} else {
ctx.relevantHeaders.forEach((headers, filepath) => {
output += ` ${filepath}: [${headers.join(", ")}]\n`;
});
}
return output;
}
public async getContext(
helper: HelperVars,
): Promise<AutocompleteStaticSnippet[]> {
const start = Date.now();
const tsFiles = await this.getTypeScriptFilesFromWorkspaces(
helper.workspaceUris,
);
// Get the three contexts holeContext, relevantTypes, relevantHeaders.
const holeContext = await this.getHoleContext(
helper.fileContents,
helper.filepath,
helper.pos,
);
const relevantTypes = await this.extractRelevantTypes(
holeContext.fullHoverResult,
holeContext.functionName,
holeContext.range.start.line,
holeContext.source,
new Map<string, string>(),
);
// if (this.language === "typescript") {
// repo = getAllTSFiles(this.repoPath);
// } else if (this.language === "ocaml") {
// repo = getAllOCamlFiles(this.repoPath);
// }
//
const relevantHeaders = await this.extractRelevantHeaders(
tsFiles,
relevantTypes,
holeContext.functionTypeSpan,
helper.pos,
holeContext.returnTypeIsAny,
);
const relevantTypesToReturn: Map<string, string[]> = new Map<
string,
string[]
>();
relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => {
if (relevantTypesToReturn.has(src)) {
const updated = relevantTypesToReturn.get(src)!;
updated.push(v);
relevantTypesToReturn.set(src, updated);
} else {
relevantTypesToReturn.set(src, [v]);
}
});
const relevantHeadersToReturn: Map<string, string[]> = new Map<
string,
string[]
>();
relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => {
if (relevantHeadersToReturn.has(src)) {
const updated = relevantHeadersToReturn.get(src)!;
if (!updated.includes(v)) {
updated.push(v);
}
relevantHeadersToReturn.set(src, updated);
} else {
relevantHeadersToReturn.set(src, [v]);
}
});
const ctx = {
holeType: holeContext.functionTypeSpan,
relevantTypes: relevantTypesToReturn,
relevantHeaders: relevantHeadersToReturn,
};
const end = Date.now();
this.logAutocompleteStaticSnippet(ctx);
// console.log(end - start);
const snippets: AutocompleteStaticSnippet[] = [];
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(holeContext.source)).toString(),
content: holeContext.fullHoverResult,
});
for (const [filepath, typs] of ctx.relevantTypes.entries()) {
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(filepath)).toString(),
content: typs.join("\n"),
});
}
for (const [filepath, headers] of ctx.relevantHeaders.entries()) {
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(filepath)).toString(),
content: headers.join("\n"),
});
}
return snippets;
}
private async getHoleContext(
sketchFileContent: string,
sketchFilePath: string,
cursorPosition: Position,
): Promise<HoleContext> {
// We need to inject the hole @ to trigger a treesitter error node.
sketchFilePath = localPathOrUriToPath(sketchFilePath);
// const sketchFileContent = await fs.readFile(sketchFilePath, "utf8");
const injectedContent = this.insertAtPosition(
sketchFileContent,
cursorPosition,
"@;",
);
// The hole's position is cursorPosition.
// Use treesitter to parse.
const ast = await getAst(sketchFilePath, injectedContent);
if (!ast) {
throw new Error("failed to get ast");
}
const language = getFullLanguageName(sketchFilePath);
const query = await getQueryForFile(
sketchFilePath,
`static-context-queries/hole-queries/${language}.scm`,
);
if (!query) {
throw new Error(
`getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`,
);
}
const captures = query.captures(ast.rootNode);
const res: HoleContext = {
fullHoverResult: "",
functionName: "",
functionTypeSpan: "",
returnTypeIsAny: false,
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
source: `file://${sketchFilePath}`,
};
let paramsTypes = "";
for (const c of captures) {
const { name, node } = c;
// console.log(`${name} →`, node.text, node.startPosition, node.endPosition);
switch (name) {
case "function.decl": {
res.fullHoverResult = node.text;
break;
}
case "function.name": {
res.functionName = node.text;
break;
}
case "function.params": {
paramsTypes = node.text;
res.range = {
start: {
line: node.startPosition.row,
character: node.startPosition.column,
},
end: {
line: node.endPosition.row,
character: node.endPosition.column,
},
};
break;
}
case "function.type": {
res.functionTypeSpan = node.text;
res.range = {
start: {
line: node.startPosition.row,
character: node.startPosition.column,
},
end: {
line: node.endPosition.row,
character: node.endPosition.column,
},
};
break;
}
}
}
if (res.functionTypeSpan === "") {
res.functionTypeSpan = `${paramsTypes} => any`;
res.returnTypeIsAny = true;
}
return res;
}
private async extractRelevantTypes(
declText: string,
typeName: string,
startLine: number,
currentFile: string,
foundContents: Map<string, string>, // uri -> contents
): Promise<RelevantTypes> {
const foundSoFar = new Map<string, TypeSpanAndSourceFileAndAst>(); // identifier -> [full hover result, source]
await this.extractRelevantTypesHelper(
declText,
typeName,
startLine,
foundSoFar,
currentFile,
foundContents,
);
return foundSoFar;
}
private async extractRelevantTypesHelper(
declText: string,
typeName: string,
startLine: number,
foundSoFar: Map<string, TypeSpanAndSourceFileAndAst>, // identifier -> [full hover result, source]
currentFile: string,
foundContents: Map<string, string>, // uri -> contents
) {
if (!foundSoFar.has(typeName)) {
const ast = await getAst(currentFile, declText);
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
foundSoFar.set(typeName, {
typeSpan: declText,
sourceFile: currentFile.slice(7),
ast: ast,
});
const language = getFullLanguageName(currentFile);
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
const identifiers = query.captures(ast.rootNode);
for (const { name, node } of identifiers) {
if (foundSoFar.has(node.text)) continue;
try {
const typeDefinitionResult = await this.ide.gotoTypeDefinition({
filepath: currentFile,
position: {
character: node.startPosition.column,
line: startLine + node.startPosition.row,
},
});
if (typeDefinitionResult.length > 0) {
const tdLocation = typeDefinitionResult[0];
let content = "";
if (foundContents.has(tdLocation.filepath)) {
content = foundContents.get(tdLocation.filepath)!;
} else {
content = await fs.readFile(
localPathOrUriToPath(tdLocation.filepath),
"utf8",
);
foundContents.set(tdLocation.filepath, content);
}
const ast = await getAst(tdLocation.filepath, content);
if (!ast) {
throw new Error(
`failed to get ast for file ${tdLocation.filepath}`,
);
}
const decl = findEnclosingTypeDeclaration(
content,
tdLocation.range.start.line,
tdLocation.range.start.character,
ast,
);
if (!decl) {
// throw new Error(`failed to get decl for file ${tdLocation.uri}`);
console.error(
`failed to get decl for file ${tdLocation.filepath}`,
);
}
if (decl) {
await this.extractRelevantTypesHelper(
decl.fullText,
node.text,
tdLocation.range.start.line,
foundSoFar,
tdLocation.filepath,
foundContents,
);
} else {
// console.log("decl not found");
}
} else {
// console.log("td not found");
}
} catch (err) {
console.log(err);
}
}
}
}
private async extractRelevantHeaders(
sources: string[],
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
holeType: string,
cursorPosition: Position,
returnTypeIsAny: boolean,
): Promise<RelevantHeaders> {
const relevantContext = new Set<TypeSpanAndSourceFile>();
if (returnTypeIsAny) return relevantContext;
// NOTE: This is necessary because TypeScript sucks.
// There is no way to compare objects by value,
// so sets of objects starts to accumulate tons of duplicates.
const relevantContextMap = new Map<string, TypeSpanAndSourceFile>();
const foundNormalForms = new Map<string, string>();
const targetTypes = await this.generateTargetTypes(relevantTypes, holeType);
for (const source of sources) {
const topLevelDecls = await extractTopLevelDecls(source);
for (const tld of topLevelDecls) {
// pattern 0 is let/const, 1 is var, 2 is fun
// if (!seenDecls.has(JSON.stringify()) {
const originalDeclText =
tld.pattern === 2
? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text
: tld.captures.find((d) => d.name === "top.var.decl")!.node.text;
if (tld.pattern === 2) {
// build a type span
// TODO: this fails sometimes with Cannot read properties of undefined (reading 'text')
// most likely due to my scm query and how I'm not attaching param name along with param type
let funcType = "";
try {
funcType = extractFunctionTypeFromDecl(tld);
} catch (err) {
// Most likely is the case that there is no explicit return type annotation.
const sigHelp = await this.ide.getSignatureHelp({
filepath: source,
position: cursorPosition,
});
if (!sigHelp) continue;
funcType = sigHelp.signatures[0].label;
// TODO: This only works for TypeScript.
function convertToArrowType(signature: string): string {
// Handle various function declaration formats.
const patterns = [
// Standard: functionName(params): returnType.
/^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
// With generics: functionName<T>(params): returnType.
/^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/,
// With modifiers: export function functionName(params): returnType.
/^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
];
for (const pattern of patterns) {
const match = signature.match(pattern);
if (match) {
const [, , parameters, returnType] = match;
return `(${parameters}) => ${returnType}`;
}
}
return signature;
}
funcType = convertToArrowType(funcType);
}
const wrapped = `type __TMP = ${funcType};`;
const ast = await getAst("file.ts", wrapped);
if (!ast) {
throw new Error(`failed to generate ast for ${wrapped}`);
}
// console.log(ast.rootNode);
const alias = ast.rootNode.namedChild(0);
// console.log(alias);
if (!alias || alias.type !== "type_alias_declaration") {
throw new Error(
"extractRelevantHeaders: Failed to parse type alias",
);
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
await this.extractRelevantHeadersHelper(
originalDeclText,
baseNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
} else {
const varTypNode = tld.captures.find(
(d) => d.name === "top.var.type",
)!.node;
await this.extractRelevantHeadersHelper(
originalDeclText,
varTypNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
}
}
for (const v of relevantContextMap.values()) {
relevantContext.add(v);
}
return relevantContext;
}
private async extractRelevantHeadersHelper(
originalDeclText: string,
node: Parser.SyntaxNode,
targetTypes: Set<Parser.SyntaxNode>,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
relevantContext: Set<TypeSpanAndSourceFile>,
relevantContextMap: Map<string, TypeSpanAndSourceFile>,
foundNormalForms: Map<string, string>,
source: string,
) {
for (const typ of targetTypes) {
if (
await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms)
) {
const ctx = { typeSpan: originalDeclText, sourceFile: source };
relevantContextMap.set(JSON.stringify(ctx), ctx);
}
if (node.type === "function_type") {
const retTypeNode = node.namedChildren.find(
(c) => c && c.type === "return_type",
);
if (retTypeNode) {
await this.extractRelevantHeadersHelper(
originalDeclText,
retTypeNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
} else if (node.type === "tuple_type") {
for (const c of node.namedChildren) {
await this.extractRelevantHeadersHelper(
originalDeclText,
c!,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
}
}
}
private async generateTargetTypes(
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
holeType: string,
) {
const targetTypes = new Set<Parser.SyntaxNode>();
// const ast = relevantTypes.get(holeIdentifier)!.ast;
const ast = await getAst("file.ts", `type T = ${holeType};`);
if (!ast) {
throw new Error(`failed to generate ast for ${holeType}`);
}
const alias = ast.rootNode.namedChild(0);
if (!alias || alias.type !== "type_alias_declaration") {
throw new Error("generateTargetTypes: Failed to parse type alias");
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
targetTypes.add(baseNode);
await this.generateTargetTypesHelper(
relevantTypes,
holeType,
targetTypes,
baseNode,
);
return targetTypes;
}
private async generateTargetTypesHelper(
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
currType: string,
targetTypes: Set<Parser.SyntaxNode>,
node: Parser.SyntaxNode | null,
): Promise<void> {
if (!node) return;
if (node.type === "function_type") {
const returnType = node.childForFieldName("return_type");
if (returnType) {
targetTypes.add(returnType);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
returnType,
);
}
}
if (node.type === "tuple_type") {
for (const child of node.namedChildren) {
if (child) {
targetTypes.add(child);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
child,
);
}
}
}
if (relevantTypes.has(node.text)) {
// const ast = relevantTypes.get(node.text)!.ast;
const typeSpan = relevantTypes.get(node.text)?.typeSpan;
// const ast = await getAst("file.ts", `type T = ${typeSpan}`);
const ast = await getAst("file.ts", typeSpan!);
if (!ast) {
throw new Error(`failed to generate ast for ${typeSpan}`);
}
const alias = ast.rootNode.namedChild(0);
if (!alias || alias.type !== "type_alias_declaration") {
console.error("generateTargetTypesHelper: Failed to parse type alias");
return;
// throw new Error(
// "generateTargetTypesHelper: Failed to parse type alias",
// );
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
baseNode,
);
}
// if (node.type === "type_identifier" || node.type === "predefined_type") {
// return [node.text];
// }
return;
}
private async isTypeEquivalent(
node: Parser.SyntaxNode,
typ: Parser.SyntaxNode,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
foundNormalForms: Map<string, string>,
): Promise<boolean> {
if (!node || !typ) {
return false;
}
let normT1 = "";
let normT2 = "";
if (foundNormalForms.has(node.text)) {
// console.log("found t1", true)
normT1 = foundNormalForms.get(node.text)!;
} else {
// console.log("not found t1", false)
normT1 = await this.normalize(node, relevantTypes);
foundNormalForms.set(node.text, normT1);
}
if (foundNormalForms.has(typ.text)) {
// console.log("found t2", true)
normT2 = foundNormalForms.get(typ.text)!;
} else {
// console.log("not found t2", false)
normT2 = await this.normalize(typ, relevantTypes);
foundNormalForms.set(typ.text, normT2);
}
// const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes);
// const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes);
// console.log(`normal forms: ${normT1} {}{} ${normT2}`)
return normT1 === normT2;
}
private async normalize(
node: Parser.SyntaxNode,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
): Promise<string> {
if (!node) return "";
switch (node.type) {
case "function_type": {
const params = node.child(0); // formal_parameters
const returnType =
node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return
const paramTypes =
params?.namedChildren
.map((param) =>
this.normalize(
param!.childForFieldName("type")! ||
param!.namedChildren.at(-1),
relevantTypes,
),
)
.join(", ") || "";
const ret = this.normalize(returnType!, relevantTypes);
return `(${paramTypes}) => ${ret}`;
}
case "tuple_type": {
const elements = node.namedChildren.map((c) =>
this.normalize(c!, relevantTypes),
);
return `[${elements.join(", ")}]`;
}
case "union_type": {
const parts = node.namedChildren.map((c) =>
this.normalize(c!, relevantTypes),
);
return parts.join(" | ");
}
case "type_identifier": {
const alias = relevantTypes.get(node.text);
if (!alias) return node.text;
// Parse the alias's type span
const wrapped = `type __TMP = ${alias};`;
const tree = await getAst("file.ts", wrapped);
const valueNode = tree!.rootNode
.descendantsOfType("type_alias_declaration")[0]
?.childForFieldName("value");
return this.normalize(valueNode!, relevantTypes);
}
case "predefined_type":
case "number":
case "string":
return node.text;
default:
// Fallback for types like array, etc.
return node.text;
}
}
private insertAtPosition = (
contents: string,
cursorPosition: { line: number; character: number },
insertText: string,
): string => {
const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings
const { line, character } = cursorPosition;
if (line < 0 || line >= lines.length) {
throw new Error("Invalid line number");
}
const targetLine = lines[line];
if (character < 0 || character > targetLine.length) {
throw new Error("Invalid character index");
}
// Insert the text
lines[line] =
targetLine.slice(0, character) + insertText + targetLine.slice(character);
return lines.join("\n"); // Reconstruct the file
};
private async getTypeScriptFilesFromWorkspaces(
workspaceUris: string[],
): Promise<string[]> {
const tsExtensions = [".ts"];
const allTsFiles: string[] = [];
for (const workspaceUri of workspaceUris) {
try {
// Convert URI to file path
const folderPath = workspaceUri.startsWith("file://")
? new URL(workspaceUri).pathname
: workspaceUri;
const tsFiles = await this.scanDirectoryForTypeScriptFiles(
folderPath,
tsExtensions,
);
allTsFiles.push(...tsFiles);
} catch (error) {
console.error(`Error scanning workspace ${workspaceUri}:`, error);
}
}
return allTsFiles;
}
private async scanDirectoryForTypeScriptFiles(
dirPath: string,
tsExtensions: string[],
): Promise<string[]> {
const tsFiles: string[] = [];
const shouldSkipDirectory = (dirName: string): boolean => {
const skipDirs = [
"node_modules",
".git",
".vscode",
"dist",
"build",
"out",
".next",
"coverage",
".nyc_output",
"tmp",
"temp",
".cache",
];
return skipDirs.includes(dirName) || dirName.startsWith(".");
};
async function scanRecursively(currentPath: string): Promise<void> {
try {
const entries = await fs.readdir(currentPath, {
withFileTypes: true,
});
for (const entry of entries) {
const fullPath = localPathOrUriToPath(
path.join(currentPath, entry.name),
);
if (entry.isDirectory()) {
// Skip common directories that typically don't contain source files
if (!shouldSkipDirectory(entry.name)) {
await scanRecursively(fullPath);
}
} else if (entry.isFile()) {
const extension = path.extname(entry.name).toLowerCase();
if (tsExtensions.includes(extension)) {
tsFiles.push(fullPath);
}
}
}
} catch (error) {
console.error(`Error reading directory ${currentPath}:`, error);
}
}
await scanRecursively(dirPath);
return tsFiles;
}
}

View file

@ -0,0 +1,222 @@
import * as fs from "fs/promises";
import Parser from "web-tree-sitter";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import { getAst } from "../../util/ast";
export interface TypeDeclarationResult {
name: string;
fullText: string;
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
kind: string;
}
export function findEnclosingTypeDeclaration(
sourceCode: string,
cursorLine: number,
cursorColumn: number,
ast: Parser.Tree,
): TypeDeclarationResult | null {
const point = { row: cursorLine, column: cursorColumn };
let node = ast.rootNode.descendantForPosition(point);
while (
node &&
![
"type_alias_declaration",
"interface_declaration",
"enum_declaration",
].includes(node.type)
) {
if (!node.parent) return null;
node = node.parent;
}
if (!node) return null;
const nameNode = node.childForFieldName("name");
const name = nameNode?.text ?? "<anonymous>";
const fullText = sourceCode.slice(node.startIndex, node.endIndex);
return {
name,
fullText,
startLine: node.startPosition.row,
startColumn: node.startPosition.column,
endLine: node.endPosition.row,
endColumn: node.endPosition.column,
kind: node.type,
};
}
export async function extractTopLevelDecls(
currentFile: string,
givenParser?: Parser,
) {
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
let language;
if (givenParser) {
language = givenParser.getLanguage();
} else {
language = getFullLanguageName(currentFile);
}
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
return query.matches(ast.rootNode);
}
export async function extractTopLevelDeclsWithFormatting(
currentFile: string,
givenParser?: Parser,
) {
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
let language;
if (givenParser) {
language = givenParser.getLanguage();
} else {
language = getFullLanguageName(currentFile);
}
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
const matches = query.matches(ast.rootNode);
const results = [];
for (const match of matches) {
const item: {
declaration: string;
nodeType: string;
name: string;
declaredType: string;
returnType?: string;
} = {
declaration: "",
nodeType: "",
name: "",
declaredType: "",
};
for (const { name, node } of match.captures) {
if (name === "top.var.decl") {
item.nodeType = "variable";
item.declaration = node.text;
// Attempt to get the declared type (e.g., const x: string = ...)
const typeNode = node.descendantsOfType("type_annotation")[0];
if (typeNode) {
item.declaredType = typeNode.text.replace(/^:\s*/, "");
}
} else if (name === "top.var.name" || name === "top.fn.name") {
item.name = node.text;
} else if (name === "top.fn.decl") {
item.nodeType = "function";
item.declaration = node.text;
// Get the return type (e.g., function foo(): string)
const returnTypeNode = node.childForFieldName("return_type");
if (returnTypeNode) {
item.returnType = returnTypeNode.text.replace(/^:\s*/, "");
}
// Get declaredType if needed (TypeScript style)
const nameNode = node.childForFieldName("name");
if (nameNode && nameNode.nextSibling?.type === "type_annotation") {
item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, "");
}
}
}
if (item.name && item.declaration) {
results.push(item);
}
}
return results;
}
export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string {
let paramsNode: Parser.SyntaxNode | undefined = undefined;
let returnNode: Parser.SyntaxNode | undefined = undefined;
for (const capture of match.captures) {
if (capture.name === "top.fn.param.type") {
paramsNode = capture.node;
} else if (capture.name === "top.fn.type") {
returnNode = capture.node;
}
}
if (!paramsNode) {
console.error(
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
);
throw new Error(
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
);
}
if (!returnNode) {
console.error(
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
);
throw new Error(
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
);
}
return `(${paramsNode!.text}) => ${returnNode!.text}`;
}
export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode {
if (
[
"function_type",
"tuple_type",
"type_identifier",
"predefined_type",
].includes(node.type)
) {
return node;
}
for (const child of node.namedChildren) {
const unwrapped = unwrapToBaseType(child!);
if (
unwrapped !== child ||
[
"function_type",
"tuple_type",
"type_identifier",
"predefined_type",
].includes(unwrapped.type)
) {
return unwrapped;
}
}
return node;
}

View file

@ -0,0 +1,33 @@
import { Tree } from "web-tree-sitter";
import { Range } from "../../..";
export interface TypeSpanAndSourceFile {
typeSpan: string;
sourceFile: string;
}
export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
ast: Tree;
}
export interface HoleContext {
fullHoverResult: string;
functionName: string;
functionTypeSpan: string;
returnTypeIsAny: boolean;
range: Range;
source: string;
}
export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
export type RelevantHeaders = Set<TypeSpanAndSourceFile>;
export type Filepath = string;
export type RelevantType = string;
export type RelevantHeader = string;
export interface StaticContext {
holeType: string;
relevantTypes: Map<Filepath, RelevantType[]>;
relevantHeaders: Map<Filepath, RelevantHeader[]>;
}

View file

@ -0,0 +1,146 @@
import { LineStream } from "../../../diff/util";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import {
processBlockNesting,
shouldStopAtMarkdownBlock,
} from "../../../utils/streamMarkdownUtils";
import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream";
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
* Now includes markdown-aware processing to handle nested markdown blocks properly.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @param {string} filepath - Optional filepath to determine if this is a markdown file.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. For markdown files, applies nested markdown block logic to avoid premature termination.
* 3. For mixed content, uses simplified processing to avoid premature termination.
* 4. For traditional code blocks, uses original logic.
* 5. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(
rawLines: LineStream,
filepath?: string,
): LineStream {
// Collect all lines for analysis
const allLines = await collectAllLines(rawLines);
// Check if it has nested markdown blocks (like ```markdown or ```md)
const firstLine = allLines[0] || "";
const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath);
// TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks)
// But exclude cases where we have nested markdown blocks
const hasMarkdownHeaders = allLines.some(
(line) => line.trim().startsWith("#") && !line.trim().startsWith("```"),
);
const hasCodeBlocks = allLines.some(
(line) => line.trim().startsWith("```") && line.trim().length >= 3,
);
const isMixedContent =
hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown;
// If this is mixed content, use simplified processing
if (isMixedContent) {
for (let i = 0; i < allLines.length; i++) {
const line = allLines[i];
// Skip initial wrapper lines if they exist
if (i === 0 && shouldRemoveLineBeforeStart(line)) {
continue;
}
yield line;
}
return;
}
// Original logic for non-mixed content
let seenFirstFence = false;
let nestCount = 0;
// Create optimized state tracker for markdown block analysis if needed
let markdownStateTracker: MarkdownBlockStateTracker | undefined;
if (hasNestedMarkdown) {
markdownStateTracker = new MarkdownBlockStateTracker(allLines);
}
for (let i = 0; i < allLines.length; i++) {
const line = allLines[i];
// Process block nesting logic for the first fence
const nesting = processBlockNesting(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
if (nesting.shouldSkip) {
continue; // Filter out starting ``` or START block
}
if (!seenFirstFence && nesting.newSeenFirstFence) {
seenFirstFence = true;
nestCount = 1;
}
if (nestCount > 0) {
// Inside a block including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
// For markdown files with nested markdown blocks, apply special logic
if (
hasNestedMarkdown &&
line.trim() === "```" &&
markdownStateTracker
) {
if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) {
return; // Stop without yielding the final closing ```
} else {
// This is an inner block delimiter, yield it as content
yield line;
continue;
}
}
// Original logic for non-markdown files or simple cases
nestCount--;
if (nestCount === 0) {
// We've closed the outer wrapper - stop without yielding the closing ```
return;
} else {
// This is a nested block closing, yield it as content
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// Otherwise just yield the line as content
yield line;
}
}
}
}
function shouldRemoveLineBeforeStart(line: string): boolean {
return (
line.trimStart().startsWith("```") ||
line.trim() === "[CODE]" ||
line.trim() === "<COMPLETION>" ||
line.trim() === "<START EDITING HERE>" ||
line.trim() === "{{FILL_HERE}}"
);
}

View file

@ -0,0 +1,452 @@
// eslint-disable-next-line max-lines-per-function
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import * as lineStream from "./lineStream";
describe("filterCodeBlock", () => {
let mockFullStop: Mock;
async function getLineGenerator(lines: any) {
return (async function* () {
for (const line of lines) {
yield line;
}
})();
}
async function getFilteredLines(results: any) {
const output = [];
for await (const line of results) {
output.push(line);
}
return output;
}
beforeEach(() => {
mockFullStop = vi.fn();
});
it("should handle unfenced code", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle unfenced code with a code block", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should handle unfenced code with a complex code block", async () => {
const linesGenerator = await getLineGenerator([
"# Manual Testing Sandbox",
"",
"## Project Structure",
"",
"```",
"manual-testing-sandbox/",
"├── readme.md # Project documentation",
"├── package.json # Node.js dependencies and scripts",
"├── tsconfig.json # TypeScript configuration",
"├── jest.config.js # Jest testing configuration",
"├── requirements.txt # Python dependencies",
"├── Dockerfile # Docker container configuration",
"├── data.json # Sample JSON data",
"├── example.ipynb # Jupyter notebook example",
"│",
"├── src/ # Source code directory",
"│ ├── example.ts # TypeScript example",
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
"│",
"├── react-calculator/ # React calculator application",
"├── calculator_test/ # Java calculator implementation",
"│ ├── Calculator.java # Calculator class",
"│ └── Main.java # Main application entry",
"│",
"├── nested-folder/ # Nested project example",
"│ ├── helloNested.py # Python script",
"│ ├── package.json # Nested package configuration",
"│ └── rules.md # Documentation",
"│",
"├── coverage/ # Test coverage reports",
"├── logs/ # Application logs",
"│",
"└── Test Files # Various language examples",
" ├── AdvancedPage.tsx # React TypeScript component",
" ├── Calculator.java # Java calculator",
" ├── program.cs # C# program",
" ├── query.sql # SQL query example",
" ├── test.css # CSS styles",
" ├── test.html # HTML page",
" ├── test.js # JavaScript code",
" ├── test.kt # Kotlin example",
" ├── test.php # PHP script",
" ├── test.py # Python script",
" ├── test.rb # Ruby script",
" ├── test.rs # Rust code",
" ├── test.sh # Shell script",
" └── test.ts # TypeScript code",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"# Manual Testing Sandbox",
"",
"## Project Structure",
"",
"```",
"manual-testing-sandbox/",
"├── readme.md # Project documentation",
"├── package.json # Node.js dependencies and scripts",
"├── tsconfig.json # TypeScript configuration",
"├── jest.config.js # Jest testing configuration",
"├── requirements.txt # Python dependencies",
"├── Dockerfile # Docker container configuration",
"├── data.json # Sample JSON data",
"├── example.ipynb # Jupyter notebook example",
"│",
"├── src/ # Source code directory",
"│ ├── example.ts # TypeScript example",
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
"│",
"├── react-calculator/ # React calculator application",
"├── calculator_test/ # Java calculator implementation",
"│ ├── Calculator.java # Calculator class",
"│ └── Main.java # Main application entry",
"│",
"├── nested-folder/ # Nested project example",
"│ ├── helloNested.py # Python script",
"│ ├── package.json # Nested package configuration",
"│ └── rules.md # Documentation",
"│",
"├── coverage/ # Test coverage reports",
"├── logs/ # Application logs",
"│",
"└── Test Files # Various language examples",
" ├── AdvancedPage.tsx # React TypeScript component",
" ├── Calculator.java # Java calculator",
" ├── program.cs # C# program",
" ├── query.sql # SQL query example",
" ├── test.css # CSS styles",
" ├── test.html # HTML page",
" ├── test.js # JavaScript code",
" ├── test.kt # Kotlin example",
" ├── test.php # PHP script",
" ├── test.py # Python script",
" ├── test.rb # Ruby script",
" ├── test.rs # Rust code",
" ├── test.sh # Shell script",
" └── test.ts # TypeScript code",
"```",
]);
});
it("should handle unfenced code with two code blocks", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
});
it("should remove lines before the first valid line", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should remove outer blocks", async () => {
const linesGenerator = await getLineGenerator([
"```ts",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should leave inner blocks intact", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should ignore ticks inside of code blocks such as tests", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"echo ```test```",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"echo ```test```",
"```",
]);
});
it("should leave single inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should leave double inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
]);
});
it("should leave inner blocks intact but not return trailing or leading text", async () => {
const linesGenerator = await getLineGenerator([
"[CODE]",
"const x = 5;",
"```bash",
"ls -al",
"```",
"[/CODE]",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is included", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
it("should handle non-markdown files normally with filepath parameter", async () => {
const linesGenerator = await getLineGenerator([
"```",
"function test() {",
" return 'hello';",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"function test() {",
" return 'hello';",
"}",
]);
});
it("should handle simple markdown code blocks", async () => {
const linesGenerator = await getLineGenerator([
"```",
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
const filteredLines = await getFilteredLines(result);
// Should remove the outer markdown wrapper, and return just the inner content.
// The lack of an end tag should cause it to return all remaining lines.
expect(filteredLines).toEqual([
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
});
});

View file

@ -3,6 +3,11 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils";
import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils";
export { filterCodeBlockLines } from "./filterCodeBlock";
export type LineFilter = (args: {
lines: LineStream;
fullStop: () => void;
@ -50,13 +55,72 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
);
}
function shouldChangeLineAndStop(line: string): string | undefined {
/**
* Shared utility for validating patterns in lines to avoid code duplication.
* Checks if a pattern appears in a valid context (not inside quotes or identifiers).
*/
export function validatePatternInLine(
line: string,
pattern: string,
): {
isValid: boolean;
patternIndex: number;
beforePattern: string;
} {
const patternIndex = line.indexOf(pattern);
if (patternIndex === -1) {
return { isValid: false, patternIndex: -1, beforePattern: "" };
}
// Check if pattern is preceded by a non-whitespace character
// If so, it might be part of an identifier, so don't handle it
if (patternIndex > 0) {
const charBefore = line[patternIndex - 1];
if (charBefore && !charBefore.match(/\s/)) {
return { isValid: false, patternIndex, beforePattern: "" };
}
}
// Check if pattern appears to be inside quotes
// Simple heuristic: count unmatched quotes before the pattern
const beforePattern = line.substring(0, patternIndex);
const singleQuotes = (beforePattern.match(/'/g) || []).length;
const doubleQuotes = (beforePattern.match(/"/g) || []).length;
// If there's an odd number of quotes before pattern, we're likely inside quotes
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
return { isValid: false, patternIndex, beforePattern };
}
return { isValid: true, patternIndex, beforePattern };
}
export function shouldChangeLineAndStop(line: string): string | undefined {
if (line.trimStart() === "```") {
return line;
}
// Check if [/CODE] appears in the line
if (line.includes(CODE_STOP_BLOCK)) {
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
const validation = validatePatternInLine(line, CODE_STOP_BLOCK);
if (!validation.isValid) {
return undefined;
}
// Get the trimmed line to check if [/CODE] is at logical start
const trimmedLine = line.trimStart();
if (trimmedLine.startsWith(CODE_STOP_BLOCK)) {
// [/CODE] is at the logical start (after whitespace only)
if (trimmedLine === CODE_STOP_BLOCK) {
return line; // Return the whole line including leading whitespace
}
}
// [/CODE] appears after some content (separated by whitespace) - return part before
return validation.beforePattern.trimEnd();
}
return undefined;
@ -71,6 +135,32 @@ function isUselessLine(line: string): boolean {
return hasUselessLine || trimmed.startsWith("// end");
}
/**
* Determines if the code block has nested markdown blocks.
*/
export function hasNestedMarkdownBlocks(
firstLine: string,
filepath?: string,
): boolean {
return (
(firstLine.startsWith("```") &&
headerIsMarkdown(firstLine.replace(/`/g, ""))) ||
Boolean(filepath && isMarkdownFile(filepath))
);
}
// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function
export function processBlockNesting(
line: string,
seenFirstFence: boolean,
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
return processBlockNestingUtil(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
}
export const USELESS_LINES = [""];
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_STOP_BLOCK = "[/CODE]";
@ -138,7 +228,7 @@ export async function* avoidPathLine(
// Sometimes the model with copy this pattern, which is unwanted
for await (const line of stream) {
if (line.startsWith(`${comment} Path: `)) {
continue;
continue; // continue in the Continue codebase! How meta!
}
yield line;
}
@ -261,7 +351,40 @@ export async function* stopAtLines(
linesToStopAt: string[] = LINES_TO_STOP_AT,
): LineStream {
for await (const line of stream) {
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
let shouldStop = false;
// Check each stop phrase
for (const stopAt of linesToStopAt) {
if (line.includes(stopAt)) {
const validation = validatePatternInLine(line, stopAt);
if (!validation.isValid) {
continue;
}
// Get the trimmed line to check if stop phrase is at logical start
const trimmedLine = line.trimStart();
if (trimmedLine.startsWith(stopAt)) {
// Stop phrase is at the logical start (after whitespace only) - should stop
shouldStop = true;
break;
} else {
// Stop phrase appears after some content - check if it's separated by whitespace
const contentBeforeStopPhrase = validation.beforePattern.trimEnd();
if (
contentBeforeStopPhrase.length < validation.beforePattern.length
) {
// There's whitespace before the stop phrase, so it's properly separated
shouldStop = true;
break;
}
// If no whitespace separation, it's part of larger text, so continue
}
}
}
if (shouldStop) {
fullStop();
break;
}
@ -329,64 +452,6 @@ export async function* removeTrailingWhitespace(
}
}
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. Filters out ending code block markers (```) unless they are the last line.
* 3. Handles special cases where lines should be changed and the stream should stop.
* 4. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let seenFirstFence = false;
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
let nestCount = 0;
for await (const line of rawLines) {
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
// Filter out starting ``` or START block
continue;
}
// Regardless of a fence or START block start tracking the nesting level
seenFirstFence = true;
nestCount = 1;
}
if (nestCount > 0) {
// Inside a block including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
nestCount--;
if (nestCount === 0) {
// if we are closing the outer block then exit early
// only exit early if the outer block was started with a block
// it it was text, we will never exit early
return;
} else {
// otherwise just yield the line
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// otherwise just yield the line
yield line;
}
}
}
}
/**
* Filters out English explanations at the start of a code block.
*

View file

@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils";
import * as lineStream from "./lineStream";
// eslint-disable-next-line max-lines-per-function
@ -174,6 +179,93 @@ describe("lineStream", () => {
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should stop at lines with leading whitespace", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
` ${lineStream.LINES_TO_STOP_AT[0]}`,
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should NOT stop when stop phrase is inside quotes", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
'console.log("# End of file. not really");',
"let y = 10;",
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
// Should not stop, should yield all lines
expect(filteredLines).toEqual([
"const x = 5;",
'console.log("# End of file. not really");',
"let y = 10;",
"const z = 15;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should NOT stop when stop phrase is inside single quotes", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"const message = '# End of file. not really';",
"let y = 10;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"const message = '# End of file. not really';",
"let y = 10;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should NOT stop when stop phrase is part of larger text", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"// This function stops<STOP EDITING HERE>after processing",
"let y = 10;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"// This function stops<STOP EDITING HERE>after processing",
"let y = 10;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should stop when stop phrase appears properly at start of content", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
"# End of file. Done here",
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
describe("skipPrefixes", () => {
@ -301,6 +393,37 @@ describe("lineStream", () => {
]);
});
it("should ignore ticks inside of code blocks such as tests", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator([
"```md",
@ -395,6 +518,119 @@ describe("lineStream", () => {
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is included", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
it("should handle non-markdown files normally with filepath parameter", async () => {
const linesGenerator = await getLineGenerator([
"```",
"function test() {",
" return 'hello';",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"function test() {",
" return 'hello';",
"}",
]);
});
it("should handle simple markdown code blocks", async () => {
const linesGenerator = await getLineGenerator([
"```",
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
// Should remove the outer markdown wrapper, and return just the inner content.
// The lack of an end tag should cause it to return all remaining lines.
expect(filteredLines).toEqual([
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
});
});
describe("filterEnglishLinesAtStart", () => {
@ -613,4 +849,453 @@ describe("lineStream", () => {
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
// Tests for new helper functions
describe("hasNestedMarkdownBlocks", () => {
it("should detect nested markdown blocks from first line", () => {
expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe(
true,
);
expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true);
expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe(
true,
);
});
it("should detect nested markdown blocks from filepath", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"),
).toBe(true);
expect(
lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"),
).toBe(true);
});
it("should return false for non-markdown scenarios", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"),
).toBe(false);
expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe(
false,
);
expect(
lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined),
).toBe(false);
});
it("should handle complex first line scenarios", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined),
).toBe(true);
expect(
lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined),
).toBe(true);
});
});
describe("collectAllLines", () => {
it("should collect all lines from a stream", async () => {
const linesGenerator = await getLineGenerator([
"line1",
"line2",
"line3",
]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual(["line1", "line2", "line3"]);
});
it("should handle empty stream", async () => {
const linesGenerator = await getLineGenerator([]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual([]);
});
it("should handle stream with empty lines", async () => {
const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual(["", "line2", "", "line4"]);
});
});
describe("shouldStopAtMarkdownBlock", () => {
it("should return false when current line is not closing backticks", () => {
const allLines = ["```markdown", "content", "more content"];
const state = new MarkdownBlockStateTracker(allLines);
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
});
it("should handle simple nested markdown case", () => {
const allLines = ["```markdown", "# Title", "```"];
const state = new MarkdownBlockStateTracker(allLines);
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true);
});
it("should handle complex nested markdown with inner code blocks", () => {
const allLines = [
"```markdown",
"# Title",
"```javascript",
"console.log('hello');",
"```",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// At index 4 (first inner closing), should not stop
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false);
// At index 5 (outer closing), should stop
expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true);
});
it("should handle multiple bare backticks scenario", () => {
const allLines = [
"```markdown",
"Content with ```inline code```",
"```",
"More content",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// At index 2, should not stop (not the last bare backticks)
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
// At index 4, should stop (last bare backticks)
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true);
});
});
describe("shouldChangeLineAndStop", () => {
it("should handle [/CODE] at start of line", () => {
const result = lineStream.shouldChangeLineAndStop("[/CODE]");
expect(result).toBe("[/CODE]");
});
it("should handle [/CODE] with leading whitespace", () => {
const result = lineStream.shouldChangeLineAndStop(" [/CODE]");
expect(result).toBe(" [/CODE]");
});
it("should return partial line before [/CODE] when at start/after whitespace", () => {
const result = lineStream.shouldChangeLineAndStop(
"some code [/CODE] more text",
);
expect(result).toBe("some code");
});
it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => {
// This test demonstrates the current bug - it WILL fail initially
const result = lineStream.shouldChangeLineAndStop(
'console.log("test [/CODE] end");',
);
expect(result).toBeUndefined(); // Should not trigger stopping
});
it("should NOT trigger on [/CODE] in middle of identifier", () => {
// Another case that shows the bug
const result = lineStream.shouldChangeLineAndStop(
'const var[/CODE]Name = "test";',
);
expect(result).toBeUndefined(); // Should not trigger stopping
});
it("should handle ``` with trimStart correctly", () => {
const result = lineStream.shouldChangeLineAndStop(" ```");
expect(result).toBe(" ```");
});
it("should NOT handle ``` in middle of line", () => {
const result = lineStream.shouldChangeLineAndStop(
'console.log("test ``` end");',
);
expect(result).toBeUndefined();
});
});
describe("MarkdownBlockState", () => {
it("should initialize with correct state", () => {
const allLines = ["```markdown", "content", "```", "more content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// Test basic initialization - we can't directly test private properties,
// but we can test the behavior through shouldStopAtPosition
expect(state).toBeDefined();
});
it("should correctly identify bare backticks positions", () => {
const allLines = ["```markdown", "```", "content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// At position 1 (first bare backticks), should not stop
expect(state.shouldStopAtPosition(1)).toBe(false);
// At position 3 (last bare backticks), should stop
expect(state.shouldStopAtPosition(3)).toBe(true);
});
it("should maintain state across multiple calls", () => {
const allLines = [
"```markdown",
"# Title",
"```javascript",
"console.log('test');",
"```",
"More content",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// Process positions incrementally
expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block
expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block
expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block
});
it("should handle complex nesting scenarios efficiently", () => {
const allLines = [
"```markdown",
"# Documentation",
"```typescript",
"interface Config {",
" name: string;",
"}",
"```",
"",
"```bash",
"npm install",
"```",
"",
"Final notes",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// Test multiple positions in sequence
expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block
expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block
expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block
});
it("should handle non-backtick lines correctly", () => {
const allLines = ["```markdown", "regular content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// Position 1 is not backticks, should return false
expect(state.shouldStopAtPosition(1)).toBe(false);
});
it("should handle empty lines and edge cases", () => {
const allLines = ["```markdown", "", "```"];
const state = new MarkdownBlockStateTracker(allLines);
expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line
expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks
});
it("should reset nest count when reaching final bare backticks", () => {
const allLines = ["```markdown", "content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// First call should stop and reset count
expect(state.shouldStopAtPosition(2)).toBe(true);
// If we had more content, it should start fresh
// (This tests the internal state management)
});
});
describe("shouldStopAtMarkdownBlock optimization", () => {
it("should maintain performance benefits with state reuse", () => {
const allLines = Array.from({ length: 100 }, (_, i) => {
if (i === 0) return "```markdown";
if (i === 99) return "```";
if (i % 10 === 0) return "```javascript";
if (i % 10 === 5) return "```";
return `line ${i}`;
});
const state = new MarkdownBlockStateTracker(allLines);
// Test that we can call multiple times without recomputing everything
const start = performance.now();
// Test several positions in sequence
for (let i = 10; i < 90; i += 10) {
if (allLines[i].trim() === "```") {
shouldStopAtMarkdownBlock(state, i);
}
}
const duration = performance.now() - start;
expect(duration).toBeLessThan(10); // Should be very fast due to state caching
});
});
describe("filterCodeBlockLines with optimized MarkdownBlockState", () => {
it("should use optimized state tracker for markdown files", async () => {
const linesGenerator = await getLineGenerator([
"```markdown",
"# Documentation",
"```typescript",
"const config = { name: 'test' };",
"```",
"Final notes",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"# Documentation",
"```typescript",
"const config = { name: 'test' };",
"```",
"Final notes",
]);
});
it("should fall back to legacy behavior when no markdown nesting detected", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"script.ts",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle mixed markdown and code scenarios with optimization", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"## API Reference",
"",
"```javascript",
"async function fetchData() {",
" return await fetch('/api/data');",
"}",
"```",
"",
"Usage notes and more documentation.",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"## API Reference",
"",
"```javascript",
"async function fetchData() {",
" return await fetch('/api/data');",
"}",
"```",
"",
"Usage notes and more documentation.",
]);
});
});
describe("validatePatternInLine", () => {
it("should return false when pattern is not found", () => {
const result = lineStream.validatePatternInLine(
"const x = 5;",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(-1);
expect(result.beforePattern).toBe("");
});
it("should return false when pattern is preceded by non-whitespace", () => {
const result = lineStream.validatePatternInLine(
'const var[/CODE]Name = "test";',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(9);
});
it("should return false when pattern is inside double quotes", () => {
const result = lineStream.validatePatternInLine(
'console.log("test [/CODE] end");',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(18);
});
it("should return false when pattern is inside single quotes", () => {
const result = lineStream.validatePatternInLine(
"const message = 'test [/CODE] end';",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(22);
});
it("should return true when pattern is properly separated by whitespace", () => {
const result = lineStream.validatePatternInLine(
"some code [/CODE] more text",
"[/CODE]",
);
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(10);
expect(result.beforePattern).toBe("some code ");
});
it("should return true when pattern is at start of line", () => {
const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(0);
expect(result.beforePattern).toBe("");
});
it("should return true when pattern has only whitespace before it", () => {
const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(4);
expect(result.beforePattern).toBe(" ");
});
it("should handle complex quote scenarios correctly", () => {
// Unmatched quote should make it invalid
const result1 = lineStream.validatePatternInLine(
'const x = "unclosed quote [/CODE]',
"[/CODE]",
);
expect(result1.isValid).toBe(false);
// Matched quotes should make it valid
const result2 = lineStream.validatePatternInLine(
'const x = "closed"; [/CODE]',
"[/CODE]",
);
expect(result2.isValid).toBe(true);
});
it("should work with different patterns", () => {
const result1 = lineStream.validatePatternInLine(
"# End of file. Done",
"# End of file.",
);
expect(result1.isValid).toBe(true);
const result2 = lineStream.validatePatternInLine(" ```", "```");
expect(result2.isValid).toBe(true);
});
});
});

View file

@ -11,6 +11,7 @@ import {
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "./types";
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
@ -24,6 +25,7 @@ export interface SnippetPayload {
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
staticSnippet: AutocompleteStaticSnippet[];
}
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
@ -185,6 +187,7 @@ export const getAllSnippets = async ({
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
staticSnippet,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
@ -196,6 +199,9 @@ export const getAllSnippets = async ({
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
racePromise(getClipboardSnippets(ide)),
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
helper.options.experimental_enableStaticContextualization
? racePromise(contextRetrievalService.getStaticContextSnippets(helper))
: [],
]);
return {
@ -207,6 +213,7 @@ export const getAllSnippets = async ({
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
staticSnippet,
};
};
@ -231,6 +238,7 @@ export const getAllSnippetsWithoutRace = async ({
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
staticSnippet,
] = await Promise.all([
contextRetrievalService.getRootPathSnippets(helper),
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
@ -240,6 +248,9 @@ export const getAllSnippetsWithoutRace = async ({
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
getClipboardSnippets(ide),
getSnippetsFromRecentlyOpenedFiles(helper, ide),
helper.options.experimental_enableStaticContextualization
? contextRetrievalService.getStaticContextSnippets(helper)
: [],
]);
return {
@ -251,5 +262,6 @@ export const getAllSnippetsWithoutRace = async ({
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
staticSnippet,
};
};

View file

@ -2,6 +2,7 @@ export enum AutocompleteSnippetType {
Code = "code",
Diff = "diff",
Clipboard = "clipboard",
Static = "static",
}
interface BaseAutocompleteSnippet {
@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {
copiedAt: string;
}
export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet {
type: AutocompleteSnippetType.Static;
filepath: string;
}
export type AutocompleteSnippet =
| AutocompleteCodeSnippet
| AutocompleteDiffSnippet
| AutocompleteClipboardSnippet;
| AutocompleteClipboardSnippet
| AutocompleteStaticSnippet;

View file

@ -4,6 +4,7 @@ import {
AutocompleteCodeSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
@ -32,9 +33,9 @@ const shuffleArray = <T>(array: T[]): T[] => {
};
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteCodeSnippet[],
snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[],
caretWindow: string,
): AutocompleteCodeSnippet[] {
): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] {
return snippets.filter(
(s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
);
@ -52,7 +53,11 @@ export const getSnippets = (
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
base: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
[
...payload.rootPathSnippets,
...payload.importDefinitionSnippets,
...payload.staticSnippet,
],
helper.prunedCaretWindow,
),
),
@ -107,7 +112,11 @@ export const getSnippets = (
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
[
...payload.rootPathSnippets,
...payload.importDefinitionSnippets,
...payload.staticSnippet,
],
helper.prunedCaretWindow,
),
),

View file

@ -5,6 +5,7 @@ import {
AutocompleteDiffSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
@ -51,6 +52,12 @@ const formatDiffSnippet = (
return snippet;
};
const formatStaticSnippet = (
snippet: AutocompleteStaticSnippet,
): AutocompleteStaticSnippet => {
return snippet;
};
const commentifySnippet = (
helper: HelperVars,
snippet: AutocompleteSnippet,
@ -81,6 +88,8 @@ export const formatSnippets = (
return formatDiffSnippet(snippet);
case AutocompleteSnippetType.Clipboard:
return formatClipboardSnippet(snippet, workspaceDirs);
case AutocompleteSnippetType.Static:
return formatStaticSnippet(snippet);
}
})
.map((item) => {

View file

@ -105,24 +105,27 @@ export class AutocompleteLoggingService {
});
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
{
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
},
true,
);
const toLog = {
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
};
outcome.enabledStaticContextualization
? void Telemetry.capture("autocomplete", {
...toLog,
enabledStaticContextualization: true,
})
: void Telemetry.capture("autocomplete", toLog);
}
}

View file

@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
completionId: string;
uniqueId: string;
timestamp: string;
enabledStaticContextualization?: boolean;
}

View file

@ -11,5 +11,6 @@ export function convertCustomCommandToSlashCommand(
description: customCommand.description ?? "",
prompt: customCommand.prompt,
source: "json-custom-command",
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
};
}

View file

@ -9,5 +9,6 @@ export function convertPromptBlockToSlashCommand(
description: prompt.description ?? "",
prompt: prompt.prompt,
source: "yaml-prompt-block",
promptFile: prompt.sourceFile, // Align with the sourceFile property
};
}

View file

@ -522,7 +522,10 @@ export class ConfigHandler {
return config;
}
async openConfigProfile(profileId?: string) {
async openConfigProfile(
profileId?: string,
element?: { sourceFile?: string },
) {
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
if (!openProfileId) {
return;
@ -530,8 +533,10 @@ export class ConfigHandler {
const profile = this.currentOrg.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
await this.ide.openFile(profile.profileDescription.uri);
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);

View file

@ -652,6 +652,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
sourceFile: llm.sourceFile,
};
}

View file

@ -22,6 +22,7 @@ export const sharedConfigSchema = z
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
enableStaticContextualization: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -188,6 +189,10 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.codebaseToolCallingOnly =
sharedConfig.codebaseToolCallingOnly;
}
if (sharedConfig.enableStaticContextualization !== undefined) {
configCopy.experimental.enableStaticContextualization =
sharedConfig.enableStaticContextualization;
}
return configCopy;
}

View file

@ -225,8 +225,8 @@ async function configYamlToContinueConfig(options: {
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
maxDepth: doc.maxDepth,
useLocalCrawling: doc.useLocalCrawling,
sourceFile: doc.sourceFile,
}));
config.mcpServers?.forEach((mcpServer) => {
@ -419,6 +419,7 @@ async function configYamlToContinueConfig(options: {
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],

View file

@ -13,6 +13,7 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
rule: rule.rule,
globs: rule.globs,
name: rule.name,
ruleFile: rule.sourceFile,
};
}
}

View file

@ -349,7 +349,10 @@ export class Core {
});
on("config/openProfile", async (msg) => {
await this.configHandler.openConfigProfile(msg.data.profileId);
await this.configHandler.openConfigProfile(
msg.data.profileId,
msg.data?.element,
);
});
on("config/reload", async (msg) => {

View file

@ -1,8 +1,5 @@
import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream";
import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";
@ -90,11 +87,18 @@ export async function* getReplacementWithLlm(
{ role: "assistant", content: assistantPrompt },
],
abortController.signal,
{
raw: true,
prediction: undefined,
reasoning: false,
},
);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);
lines = stopAtLines(lines, () => {}, ["```"]);
// We want to retrive everything from the llm
// then let the filterCodeBlocks function clean up for any trailing text.
// if we stop here early, we run the risk of loosing inner markdown content.
for await (const line of lines) {
yield line;

View file

@ -0,0 +1,459 @@
import { streamLazyApply } from "./streamLazyApply";
// Mock LLM for testing
class MockLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for markdown file with nested blocks
const lines = [
"# Project Structure",
"",
"```markdown README.md",
"# Project Structure",
"",
"```",
".",
"├── src/",
"│ └── main.js",
"└── package.json",
"```",
"```",
];
// Yield each line separately (more realistic streaming)
for (const line of lines) {
yield line;
}
}
}
class MockJavaScriptLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for JavaScript file
const lines = [
"function calculateSum(a, b) {",
" return a + b;",
"}",
"",
"function calculateProduct(a, b) {",
" return a * b;",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockPythonLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for Python file
const lines = [
"def calculate_sum(a, b):",
" return a + b",
"",
"def calculate_product(a, b):",
" return a * b",
];
for (const line of lines) {
yield line;
}
}
}
class MockWithUnchangedCodeLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response with UNCHANGED_CODE markers
const lines = [
"function newFunction() {",
" return 'new';",
"}",
"",
"// ... unchanged code ...",
"",
"function anotherFunction() {",
" return 'updated';",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockTypeScriptLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
const lines = [
"interface User {",
" id: number;",
" name: string;",
"}",
"",
"function getUser(id: number): User {",
" return { id, name: 'Test User' };",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockEmptyLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Empty response
return;
}
}
class MockSimpleLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
const lines = ["function test() {", " return true;", "}"];
for (const line of lines) {
yield line;
}
}
}
class MockRegularMarkdownLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate regular markdown with simple code block
const lines = [
"# Debug Test Folder",
"The sole purpose of this folder is to open it when debugging.",
"",
"## File Structure",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"├── Dockerfile",
"└── test.ts",
"```",
];
for (const line of lines) {
yield line;
}
}
}
describe("streamLazyApply", () => {
test("should handle markdown files with nested blocks without stopping early", async () => {
const oldCode = "# Project\n\nBasic readme content.";
const newCode = `# Project Structure
\`\`\`markdown README.md
# Project Structure
\`\`\`
.
├── src/
│ └── main.js
└── package.json
\`\`\`
\`\`\``;
const filename = "README.md";
const llm = new MockLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines (not empty)
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the nested markdown content
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("```markdown README.md");
expect(allContent).toContain("└── package.json");
// Should not have been truncated at the first ```
expect(allContent).toContain("src/");
});
test("should handle JavaScript files correctly", async () => {
const oldCode = "function calculateSum(a, b) {\n return a + b;\n}";
const newCode = `function calculateSum(a, b) {
return a + b;
}
function calculateProduct(a, b) {
return a * b;
}`;
const filename = "calculator.js";
const llm = new MockJavaScriptLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the JavaScript functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("calculateSum");
expect(allContent).toContain("calculateProduct");
});
test("should handle Python files correctly", async () => {
const oldCode = "def calculate_sum(a, b):\n return a + b";
const newCode = `def calculate_sum(a, b):
return a + b
def calculate_product(a, b):
return a * b`;
const filename = "calculator.py";
const llm = new MockPythonLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the Python functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("calculate_sum");
expect(allContent).toContain("calculate_product");
});
test("should handle UNCHANGED_CODE markers in responses", async () => {
const oldCode = `function oldFunction() {
return 'old';
}
function existingFunction() {
return 'existing';
}`;
const newCode = `function newFunction() {
return 'new';
}
function existingFunction() {
return 'existing';
}
function anotherFunction() {
return 'updated';
}`;
const filename = "example.js";
const llm = new MockWithUnchangedCodeLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain new and updated functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("newFunction");
expect(allContent).toContain("anotherFunction");
});
test("should handle TypeScript files correctly", async () => {
const oldCode = "interface User {\n id: number;\n}";
const newCode = `interface User {
id: number;
name: string;
}
function getUser(id: number): User {
return { id, name: 'Test User' };
}`;
const filename = "user.ts";
const llm = new MockTypeScriptLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain TypeScript interface and function
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("interface User");
expect(allContent).toContain("getUser");
expect(allContent).toContain("name: string");
});
test("should work with empty LLM responses", async () => {
const oldCode = "function test() { return 1; }";
const newCode = "function test() { return 2; }";
const filename = "test.js";
const llm = new MockEmptyLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should handle empty response gracefully
expect(diffLines).toBeDefined();
});
test("should correctly identify markdown vs non-markdown files", async () => {
// Test that our isMarkdownFile logic works
const markdownFiles = ["README.md", "docs.markdown", "example.gfm"];
const nonMarkdownFiles = [
"script.js",
"code.py",
"style.css",
"component.tsx",
];
// This is more of a unit test, but verifies our file detection logic
// We can test this indirectly by checking that different file types
// are processed through different code paths
const oldCode = "function test() { return false; }";
const newCode = "function test() { return true; }";
const llm = new MockSimpleLLM() as any;
// Test each file type
for (const filename of [...markdownFiles, ...nonMarkdownFiles]) {
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should work for all file types
expect(diffLines.length).toBeGreaterThan(0);
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("test");
}
});
test("should handle regular markdown files with simple code blocks", async () => {
const oldCode = "# Old Content";
const newCode = `# Debug Test Folder
The sole purpose of this folder is to open it when debugging.
## File Structure
\`\`\`
debug-test-folder/
├── AdvancedPage.tsx
├── Calculator.java
├── Dockerfile
└── test.ts
\`\`\``;
const filename = "README.md";
const llm = new MockRegularMarkdownLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines (not empty)
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the full file structure
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("Debug Test Folder");
expect(allContent).toContain("File Structure");
expect(allContent).toContain("debug-test-folder/");
expect(allContent).toContain("├── AdvancedPage.tsx");
expect(allContent).toContain("└── test.ts");
// Should not have been truncated at the opening ```
expect(allContent).toContain("Calculator.java");
expect(allContent).toContain("Dockerfile");
});
});

View file

@ -2,11 +2,11 @@ import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
removeTrailingWhitespace,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";
import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js";
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
@ -44,9 +44,12 @@ export async function* streamLazyApply(
}
let lazyCompletionLines = streamLines(lazyCompletion, true);
// Process line output
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = stopAtLinesWithMarkdownSupport(
lazyCompletionLines,
filename,
);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines);
@ -92,7 +95,6 @@ async function* streamFillUnchangedCode(
newLines.push(replacementLine);
replacement += replacementLine + "\n";
}
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;

View file

@ -63,7 +63,8 @@ export async function* recursiveStream(
}
} else {
const generator = llm.streamChat(prompt, abortController.signal, {
prediction,
raw: true,
prediction: undefined,
reasoning: false,
});

View file

@ -55,11 +55,7 @@ export async function* addIndentation(
}
function modelIsInept(model: string): boolean {
return !(
model.includes("gpt") ||
model.includes("claude") ||
model.includes("nova")
);
return !(model.includes("gpt") || model.includes("claude"));
}
export async function* streamDiffLines({

78
core/index.d.ts vendored
View file

@ -237,6 +237,7 @@ export interface SiteIndexingConfig {
maxDepth?: number;
faviconUrl?: string;
useLocalCrawling?: boolean;
sourceFile?: string;
}
export interface DocsIndexingDetails {
@ -660,6 +661,8 @@ export interface LLMOptions {
deploymentId?: string;
env?: Record<string, string | number | boolean>;
sourceFile?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@ -871,6 +874,8 @@ export interface IDE {
// LSP
gotoDefinition(location: Location): Promise<RangeInFile[]>;
gotoTypeDefinition(location: Location): Promise<RangeInFile[]>; // TODO: add to jetbrains
getSignatureHelp(location: Location): Promise<SignatureHelp | null>; // TODO: add to jetbrains
// Callbacks
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void;
@ -1035,6 +1040,7 @@ export interface CustomCommand {
name: string;
prompt: string;
description?: string;
sourceFile?: string;
}
export interface Prediction {
@ -1152,6 +1158,8 @@ export interface ModelDescription {
capabilities?: ModelCapability;
roles?: ModelRole[];
configurationStatus?: LLMConfigurationStatuses;
sourceFile?: string;
}
export interface JSONEmbedOptions {
@ -1209,6 +1217,7 @@ export interface TabAutocompleteOptions {
experimental_includeRecentlyVisitedRanges: boolean | number;
experimental_includeRecentlyEditedRanges: boolean | number;
experimental_includeDiff: boolean | number;
experimental_enableStaticContextualization: boolean;
}
export interface StdioOptions {
@ -1306,6 +1315,7 @@ export interface MCPServerStatus extends MCPOptions {
tools: MCPTool[];
resources: MCPResource[];
resourceTemplates: MCPResourceTemplate[];
sourceFile?: string;
}
export interface ContinueUIConfig {
@ -1408,6 +1418,68 @@ export interface RangeInFileWithNextEditInfo {
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
/**
* Signature help represents the signature of something
* callable. There can be multiple signatures but only one
* active and only one active parameter.
*/
export class SignatureHelp {
/**
* One or more signatures.
*/
signatures: SignatureInformation[];
/**
* The active signature.
*/
activeSignature: number;
/**
* The active parameter of the active signature.
*/
activeParameter: number;
}
/**
* Represents the signature of something callable. A signature
* can have a label, like a function-name, a doc-comment, and
* a set of parameters.
*/
export class SignatureInformation {
/**
* The label of this signature. Will be shown in
* the UI.
*/
label: string;
/**
* The parameters of this signature.
*/
parameters: ParameterInformation[];
/**
* The index of the active parameter.
*
* If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}.
*/
activeParameter?: number;
}
/**
* Represents a parameter of a callable-signature. A parameter can
* have a label and a doc-comment.
*/
export class ParameterInformation {
/**
* The label of this signature.
*
* Either a string or inclusive start and exclusive end offsets within its containing
* {@link SignatureInformation.label signature label}. *Note*: A label of type string must be
* a substring of its containing signature information's {@link SignatureInformation.label label}.
*/
label: string | [number, number];
}
/**
* 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.
@ -1478,6 +1550,12 @@ export interface ExperimentalConfig {
* instead of embeddings, FTS, recently edited files, etc.
*/
codebaseToolCallingOnly?: boolean;
/**
* If enabled, static contextualization will be used to
* gather context for the model where necessary.
*/
enableStaticContextualization?: boolean;
}
export interface AnalyticsConfig {

View file

@ -187,6 +187,9 @@ export abstract class BaseLLM implements ILLM {
maxEmbeddingChunkSize: number;
maxEmbeddingBatchSize: number;
//URI to local block defining this LLM
sourceFile?: string;
private _llmOptions: LLMOptions;
protected openaiAdapter?: BaseLlmApi;
@ -290,6 +293,7 @@ export abstract class BaseLLM implements ILLM {
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
this.autocompleteOptions = options.autocompleteOptions;
this.sourceFile = options.sourceFile;
}
getConfigurationStatus() {

View file

@ -102,7 +102,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
),
void,
];
"config/openProfile": [{ profileId: string | undefined }, void];
"config/openProfile": [
{ profileId: string | undefined; element?: { sourceFile?: string } },
void,
];
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
"config/updateSelectedModel": [
{

View file

@ -10,6 +10,7 @@ import type {
Problem,
Range,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
} from "../";
@ -82,6 +83,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getFileStats: [{ files: string[] }, FileStatsMap];
gotoDefinition: [{ location: Location }, RangeInFile[]];
gotoTypeDefinition: [{ location: Location }, RangeInFile[]];
getSignatureHelp: [{ location: Location }, SignatureHelp | null];
getControlPlaneSessionInfo: [
{ silent: boolean; useOnboarding: boolean },

View file

@ -13,6 +13,7 @@ import type {
Problem,
Range,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
} from "../..";
@ -45,6 +46,14 @@ export class MessageIde implements IDE {
return this.request("gotoDefinition", { location });
}
async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
return this.request("gotoTypeDefinition", { location });
}
async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
return this.request("getSignatureHelp", { location });
}
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
}

View file

@ -16,7 +16,7 @@ export const createRuleBlock: Tool = {
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
parameters: {
type: "object",
required: ["name", "rule", "description"],
required: ["name", "rule"],
properties: {
name: {
type: "string",

View file

@ -16,12 +16,11 @@ export const lsTool: Tool = {
description: "List files and folders in a given directory",
parameters: {
type: "object",
required: ["dirPath", "recursive"],
properties: {
dirPath: {
type: "string",
description:
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
"The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'",
},
recursive: {
type: "boolean",

View file

@ -20,7 +20,7 @@ export function getPreferredShell(): string {
}
}
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`;
export const runTerminalCommandTool: Tool = {
type: "function",

View file

@ -1,22 +1,15 @@
import { ToolImpl } from ".";
import { RangeInFile } from "../..";
import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
import { getStringArg } from "../parseArgs";
export const codebaseToolImpl: ToolImpl = async (args, extras) => {
if (!args.query || args.query.trim() === "") {
return [
{
name: "Error",
description: "Codebase search error",
content: "Query parameter is required and cannot be empty.",
},
];
}
const query = getStringArg(args, "query");
try {
const contextExtras = {
config: extras.config,
fullInput: args.query,
fullInput: query,
embeddingsProvider: extras.config.selectedModelByRole.embed,
reranker: extras.config.selectedModelByRole.rerank,
llm: extras.llm,
@ -39,7 +32,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => {
{
name: "No Results",
description: "Codebase search",
content: `No relevant code found for query: "${args.query}". This could mean:
content: `No relevant code found for query: "${query}". This could mean:
- The codebase hasn't been indexed yet
- No code matches the search criteria
- Embeddings provider is not configured

View file

@ -2,20 +2,24 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
import { ToolImpl } from ".";
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
import { getStringArg } from "../parseArgs";
export const createNewFileImpl: ToolImpl = async (args, extras) => {
const filepath = getStringArg(args, "filepath");
const contents = getStringArg(args, "contents", true);
const resolvedFileUri = await inferResolvedUriFromRelativePath(
args.filepath,
filepath,
extras.ide,
);
if (resolvedFileUri) {
const exists = await extras.ide.fileExists(resolvedFileUri);
if (exists) {
throw new Error(
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
`File ${filepath} already exists. Use the edit tool to edit this file`,
);
}
await extras.ide.writeFile(resolvedFileUri, args.contents);
await extras.ide.writeFile(resolvedFileUri, contents);
await extras.ide.openFile(resolvedFileUri);
await extras.ide.saveFile(resolvedFileUri);
if (extras.codeBaseIndexer) {

View file

@ -2,6 +2,11 @@ import { createRuleMarkdown } from "@continuedev/config-yaml";
import { ToolImpl } from ".";
import { RuleWithSource } from "../..";
import { createRuleFilePath } from "../../config/markdown/utils";
import {
getBooleanArg,
getOptionalStringArg,
getStringArg,
} from "../parseArgs";
export type CreateRuleBlockArgs = Pick<
Required<RuleWithSource>,
@ -9,11 +14,21 @@ export type CreateRuleBlockArgs = Pick<
> &
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
export const createRuleBlockImpl: ToolImpl = async (
{ name, rule, ...otherArgs }: CreateRuleBlockArgs,
extras,
) => {
const fileContent = createRuleMarkdown(name, rule, otherArgs);
export const createRuleBlockImpl: ToolImpl = async (args, extras) => {
const name = getStringArg(args, "name");
const rule = getStringArg(args, "rule");
const description = getOptionalStringArg(args, "description");
const regex = getOptionalStringArg(args, "regex");
const globs = getOptionalStringArg(args, "globs");
const alwaysApply = getBooleanArg(args, "alwaysApply", false);
const fileContent = createRuleMarkdown(name, rule, {
alwaysApply,
description,
globs,
regex,
});
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const ruleFilePath = createRuleFilePath(localContinueDir, name);
@ -24,7 +39,7 @@ export const createRuleBlockImpl: ToolImpl = async (
return [
{
name: "New Rule Block",
description: otherArgs.description || "",
description: description || "",
uri: {
type: "file",
value: ruleFilePath,

View file

@ -1,10 +1,13 @@
import { ToolImpl } from ".";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
import { getStringArg } from "../parseArgs";
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
const contextItems = await getUrlContextItems(args.url, extras.fetch);
const url = getStringArg(args, "url");
const contextItems = await getUrlContextItems(url, extras.fetch);
// Track truncated content
const truncatedUrls: string[] = [];
@ -12,7 +15,7 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
// Check and truncate each context item
const processedItems = contextItems.map((item) => {
if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
truncatedUrls.push(args.url);
truncatedUrls.push(url);
return {
...item,
content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),

View file

@ -1,10 +1,13 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { getStringArg } from "../parseArgs";
const MAX_AGENT_GLOB_RESULTS = 100;
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
const pattern = getStringArg(args, "pattern");
const results = await extras.ide.getFileResults(
args.pattern,
pattern,
MAX_AGENT_GLOB_RESULTS,
);
const contextItems: ContextItem[] = [

View file

@ -1,6 +1,7 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { formatGrepSearchResults } from "../../util/grepSearch";
import { getStringArg } from "../parseArgs";
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
@ -41,8 +42,10 @@ function splitGrepResultsByFile(content: string): ContextItem[] {
}
export const grepSearchImpl: ToolImpl = async (args, extras) => {
const query = getStringArg(args, "query");
const results = await extras.ide.getSearchResults(
args.query,
query,
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
);
const { formatted, numResults, truncated } = formatGrepSearchResults(
@ -63,7 +66,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
let contextItems: ContextItem[] = [];
const splitByFile: boolean = args.splitByFile || false;
const splitByFile: boolean = args?.splitByFile || false;
if (splitByFile) {
contextItems = splitGrepResultsByFile(formatted);
} else {

View file

@ -2,28 +2,28 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
import { getStringArg } from "../parseArgs";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readFileImpl: ToolImpl = async (args, extras) => {
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
extras.ide,
);
const filepath = getStringArg(args, "filepath");
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
if (!firstUriMatch) {
throw new Error(`Could not find file ${args.filepath}`);
throw new Error(`Could not find file ${filepath}`);
}
const content = await extras.ide.readFile(firstUriMatch);
await throwIfFileExceedsHalfOfContext(
args.filepath,
filepath,
content,
extras.config.selectedModelByRole.chat,
);
return [
{
name: getUriPathBasename(args.filepath),
description: args.filepath,
name: getUriPathBasename(firstUriMatch),
description: filepath,
content,
uri: {
type: "file",

View file

@ -1,13 +1,14 @@
import { ToolImpl } from ".";
import { getStringArg } from "../parseArgs";
export const requestRuleImpl: ToolImpl = async (args, extras) => {
const name = getStringArg(args, "name");
// Find the rule by name in the config
const rule = extras.config.rules.find((r) => r.name === args.name);
const rule = extras.config.rules.find((r) => r.name === name);
if (!rule || !rule.ruleFile) {
throw new Error(
`Rule with name "${args.name}" not found or has no file path`,
);
throw new Error(`Rule with name "${name}" not found or has no file path`);
}
return [

View file

@ -24,6 +24,7 @@ import {
isProcessBackgrounded,
removeBackgroundedProcess,
} from "../../util/processTerminalBackgroundStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
const asyncExec = util.promisify(childProcess.exec);
@ -50,8 +51,11 @@ const ENABLED_FOR_REMOTES = [
];
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const command = getStringArg(args, "command");
// Default to waiting for completion if not specified
const waitForCompletion = args.waitForCompletion !== false;
const waitForCompletion =
getBooleanArg(args, "waitForCompletion", false) ?? true;
const ideInfo = await extras.ide.getIdeInfo();
const toolCallId = extras.toolCallId || "";
@ -84,7 +88,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
// Use spawn with color environment
const childProc = childProcess.spawn(args.command, {
const childProc = childProcess.spawn(command, {
cwd,
shell: true,
env: getColorEnv(), // Add enhanced environment for colors
@ -229,7 +233,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Standard execution, waiting for completion
try {
// Use color environment for exec as well
const output = await asyncExec(args.command, {
const output = await asyncExec(command, {
cwd,
env: getColorEnv(),
});
@ -258,7 +262,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// but don't attach any listeners other than error
try {
// Use spawn with color environment
const childProc = childProcess.spawn(args.command, {
const childProc = childProcess.spawn(command, {
cwd,
shell: true,
env: getColorEnv(), // Add color environment
@ -309,7 +313,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// For remote environments, just run the command
// Note: waitForCompletion is not supported in remote environments yet
await extras.ide.runCommand(args.command);
await extras.ide.runCommand(command);
return [
{
name: "Terminal",

View file

@ -1,10 +1,13 @@
import { ToolImpl } from ".";
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
import { getStringArg } from "../parseArgs";
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
export const searchWebImpl: ToolImpl = async (args, extras) => {
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
const query = getStringArg(args, "query");
const webResults = await fetchSearchResults(query, 5, extras.fetch);
// Track truncated results
const truncatedResults: string[] = [];

View file

@ -2,9 +2,11 @@ import generateRepoMap from "../../util/generateRepoMap";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { ToolImpl } from ".";
import { getStringArg } from "../parseArgs";
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
const { directory_path } = args;
const directory_path = getStringArg(args, "directory_path");
const uri = await resolveRelativePathInDir(directory_path, extras.ide);
if (!uri) {

View file

@ -12,3 +12,52 @@ export function safeParseToolCallArgs(
return {};
}
}
export function getStringArg(
args: any,
argName: string,
allowEmpty = false,
): string {
if (!args || !(argName in args) || typeof args[argName] !== "string") {
throw new Error(
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`,
);
}
if (!allowEmpty && !args[argName].trim()) {
throw new Error(`Argument ${argName} must not be empty`);
}
return args[argName];
}
export function getOptionalStringArg(
args: any,
argName: string,
allowEmpty = false,
) {
if (typeof args?.[argName] === "undefined") {
return undefined;
}
return getStringArg(args, argName, allowEmpty);
}
export function getBooleanArg(args: any, argName: string, required = false) {
if (!args || !(argName in args)) {
if (required) {
throw new Error(`Argument \`${argName}\` is required (type boolean)`);
} else {
return undefined;
}
}
if (typeof args[argName] === "string") {
if (args[argName].toLowerCase() === "false") {
return false;
}
if (args[argName].toLowerCase() === "true") {
return true;
}
}
if (typeof args[argName] !== "boolean") {
throw new Error(`Argument \`${argName}\` must be a boolean true or false`);
}
return args[argName];
}

View file

@ -0,0 +1,248 @@
import { describe, expect, it } from "vitest";
import { ToolCallDelta } from "..";
import {
getBooleanArg,
getOptionalStringArg,
getStringArg,
safeParseToolCallArgs,
} from "./parseArgs";
describe("safeParseToolCallArgs", () => {
it("should parse valid JSON arguments", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: '{"name": "test", "value": 123}',
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({ name: "test", value: 123 });
});
it("should parse valid JSON arguments with whitespace", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: ' {"name": "test", "value": 123} ',
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({ name: "test", value: 123 });
});
it("should return empty object for invalid JSON", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: '{"name": "test", value: 123', // Invalid JSON
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({});
});
it("should return empty object when arguments is empty", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: "",
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({});
});
it("should return empty object when arguments is null or undefined", () => {
const toolCall1: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: null as any,
},
};
const toolCall2: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: undefined,
},
};
expect(safeParseToolCallArgs(toolCall1)).toEqual({});
expect(safeParseToolCallArgs(toolCall2)).toEqual({});
});
it("should handle case when function is undefined", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: undefined,
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({});
});
});
describe("getStringArg", () => {
it("should return string argument when valid", () => {
const args = { name: "test" };
const result = getStringArg(args, "name");
expect(result).toBe("test");
});
it("should throw error when argument is missing", () => {
const args = { otherArg: "test" };
expect(() => getStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
it("should throw error when argument is not a string", () => {
const args = { name: 123 };
expect(() => getStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
it("should throw error when argument is empty and empty not allowed", () => {
const args = { name: "" };
expect(() => getStringArg(args, "name")).toThrowError(
"Argument name must not be empty",
);
const argsWithSpace = { name: " " };
expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
"Argument name must not be empty",
);
});
it("should accept empty string when allowEmpty is true", () => {
const args = { name: "" };
const result = getStringArg(args, "name", true);
expect(result).toBe("");
const argsWithSpace = { name: " " };
const resultWithSpace = getStringArg(argsWithSpace, "name", true);
expect(resultWithSpace).toBe(" ");
});
it("should handle null or undefined args", () => {
expect(() => getStringArg(null, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
expect(() => getStringArg(undefined, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
});
describe("getOptionalStringArg", () => {
it("should return undefined when argument is not provided", () => {
const args = { otherArg: "test" };
const result = getOptionalStringArg(args, "name");
expect(result).toBeUndefined();
});
it("should return string argument when valid", () => {
const args = { name: "test" };
const result = getOptionalStringArg(args, "name");
expect(result).toBe("test");
});
it("should throw error when argument is not a string", () => {
const args = { name: 123 };
expect(() => getOptionalStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
it("should throw error when argument is empty and empty not allowed", () => {
const args = { name: "" };
expect(() => getOptionalStringArg(args, "name")).toThrowError(
"Argument name must not be empty",
);
});
it("should accept empty string when allowEmpty is true", () => {
const args = { name: "" };
const result = getOptionalStringArg(args, "name", true);
expect(result).toBe("");
});
it("should handle null or undefined args", () => {
expect(getOptionalStringArg(null, "name")).toBeUndefined();
expect(getOptionalStringArg(undefined, "name")).toBeUndefined();
});
});
describe("getBooleanArg", () => {
it("should return boolean argument when valid", () => {
const argsTrue = { flag: true };
const argsFalse = { flag: false };
expect(getBooleanArg(argsTrue, "flag")).toBe(true);
expect(getBooleanArg(argsFalse, "flag")).toBe(false);
});
it("should return undefined when argument is not provided and not required", () => {
const args = { otherArg: true };
const result = getBooleanArg(args, "flag");
expect(result).toBeUndefined();
});
it("should throw error when argument is not provided and required", () => {
const args = { otherArg: true };
expect(() => getBooleanArg(args, "flag", true)).toThrowError(
"Argument `flag` is required (type boolean)",
);
});
it('should handle string "true" and "false" values', () => {
const argsStringTrue = { flag: "true" };
const argsStringFalse = { flag: "false" };
const argsStringTrueUppercase = { flag: "TRUE" };
const argsStringFalseUppercase = { flag: "FALSE" };
expect(getBooleanArg(argsStringTrue, "flag")).toBe(true);
expect(getBooleanArg(argsStringFalse, "flag")).toBe(false);
expect(getBooleanArg(argsStringTrueUppercase, "flag")).toBe(true);
expect(getBooleanArg(argsStringFalseUppercase, "flag")).toBe(false);
});
it("should throw error when argument is not a boolean or valid boolean string", () => {
const argsNumber = { flag: 1 };
const argsInvalidString = { flag: "yes" };
const argsObject = { flag: {} };
expect(() => getBooleanArg(argsNumber, "flag")).toThrowError(
"Argument `flag` must be a boolean true or false",
);
expect(() => getBooleanArg(argsInvalidString, "flag")).toThrowError(
"Argument `flag` must be a boolean true or false",
);
expect(() => getBooleanArg(argsObject, "flag")).toThrowError(
"Argument `flag` must be a boolean true or false",
);
});
it("should handle null or undefined args", () => {
expect(getBooleanArg(null, "flag")).toBeUndefined();
expect(getBooleanArg(undefined, "flag")).toBeUndefined();
expect(() => getBooleanArg(null, "flag", true)).toThrowError(
"Argument `flag` is required (type boolean)",
);
expect(() => getBooleanArg(undefined, "flag", true)).toThrowError(
"Argument `flag` is required (type boolean)",
);
});
});

View file

@ -13,6 +13,7 @@ import {
Problem,
Range,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
ToastType,
@ -44,6 +45,14 @@ class FileSystemIde implements IDE {
return Promise.resolve([]);
}
gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
return Promise.resolve([]);
}
getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
return Promise.resolve(null);
}
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
return;
}

View file

@ -24,6 +24,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
experimental_includeRecentlyVisitedRanges: true,
experimental_includeRecentlyEditedRanges: true,
experimental_includeDiff: true,
experimental_enableStaticContextualization: false,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

136
core/utils/markdownUtils.ts Normal file
View file

@ -0,0 +1,136 @@
/**
* Utility functions for working with markdown files and code blocks
*/
/**
* Determines if a code block header indicates markdown content
*/
export function headerIsMarkdown(header: string): boolean {
return (
header === "md" ||
header === "markdown" ||
header === "gfm" ||
header === "github-markdown" ||
header.includes(" md") ||
header.includes(" markdown") ||
header.includes(" gfm") ||
header.includes(" github-markdown") ||
header.split(" ")[0]?.split(".").pop() === "md" ||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
header.split(" ")[0]?.split(".").pop() === "gfm"
);
}
/**
* Determines if a file is a markdown file based on its filepath.
*/
export function isMarkdownFile(filepath?: string): boolean {
if (!filepath) {
return false;
}
const ext = filepath.split(".").pop()?.toLowerCase() || "";
return ["md", "markdown", "gfm"].includes(ext);
}
/**
* State tracker for markdown block analysis to avoid recomputing on each call.
* Optimized to handle nested markdown code blocks.
*/
export class MarkdownBlockStateTracker {
protected trimmedLines: string[];
protected bareBacktickPositions: number[];
private markdownNestCount: number = 0;
private lastProcessedIndex: number = -1;
constructor(allLines: string[]) {
this.trimmedLines = allLines.map((l) => l.trim());
// Pre-compute positions of all bare backtick lines for faster lookup
this.bareBacktickPositions = [];
for (let i = 0; i < this.trimmedLines.length; i++) {
if (this.trimmedLines[i].match(/^`+$/)) {
this.bareBacktickPositions.push(i);
}
}
}
/**
* Determines if we should stop at the given markdown block position.
* Maintains state across calls to avoid redundant computation.
*/
shouldStopAtPosition(currentIndex: number): boolean {
if (this.trimmedLines[currentIndex] !== "```") {
return false;
}
// Process any lines we haven't seen yet up to currentIndex
for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) {
const currentLine = this.trimmedLines[j];
if (this.markdownNestCount > 0) {
// Inside a markdown block
if (currentLine.match(/^`+$/)) {
// Found bare backticks - check if this is the last one
if (j === currentIndex) {
const remainingBareBackticks =
this.getRemainingBareBackticksAfter(j);
if (remainingBareBackticks === 0) {
this.markdownNestCount = 0;
this.lastProcessedIndex = j;
return true;
}
}
} else if (currentLine.startsWith("```")) {
// Going into a nested codeblock
this.markdownNestCount++;
}
} else {
// Not inside a markdown block yet
if (currentLine.startsWith("```")) {
const header = currentLine.replaceAll("`", "");
if (headerIsMarkdown(header)) {
this.markdownNestCount = 1;
}
}
}
}
this.lastProcessedIndex = currentIndex;
return false;
}
/**
* Efficiently determines if there are remaining bare backticks after the given position.
*/
getRemainingBareBackticksAfter(currentIndex: number): number {
return this.bareBacktickPositions.filter((pos) => pos > currentIndex)
.length;
}
/**
* Checks if the line at the given index is a bare backtick line.
*/
isBareBacktickLine(index: number): boolean {
return this.bareBacktickPositions.includes(index);
}
/**
* Gets the trimmed lines array.
*/
getTrimmedLines(): string[] {
return this.trimmedLines;
}
}
/**
* Collects all lines from a LineStream into an array for analysis.
*/
export async function collectAllLines<T>(
stream: AsyncGenerator<T>,
): Promise<T[]> {
const allLines: T[] = [];
for await (const line of stream) {
allLines.push(line);
}
return allLines;
}

View file

@ -0,0 +1,306 @@
import { describe, expect, it } from "vitest";
import {
collectAllLines,
headerIsMarkdown,
isMarkdownFile,
MarkdownBlockStateTracker,
} from "./markdownUtils";
describe("headerIsMarkdown", () => {
// Test exact match with common Markdown identifiers
it("should identify exact matches with common Markdown identifiers", () => {
expect(headerIsMarkdown("md")).toBe(true);
expect(headerIsMarkdown("markdown")).toBe(true);
expect(headerIsMarkdown("gfm")).toBe(true);
expect(headerIsMarkdown("github-markdown")).toBe(true);
});
// Test identifiers preceded by a space
it("should identify identifiers preceded by a space", () => {
expect(headerIsMarkdown("lang md")).toBe(true);
expect(headerIsMarkdown("something markdown")).toBe(true);
expect(headerIsMarkdown("language gfm")).toBe(true);
expect(headerIsMarkdown("spec github-markdown")).toBe(true);
});
// Test file extensions
it("should identify file names with markdown extensions", () => {
expect(headerIsMarkdown("example.md")).toBe(true);
expect(headerIsMarkdown("document.markdown")).toBe(true);
expect(headerIsMarkdown("readme.gfm")).toBe(true);
});
// Test more complex cases with extensions
it("should identify file names with markdown extensions followed by other text", () => {
expect(headerIsMarkdown("example.md additional text")).toBe(true);
expect(headerIsMarkdown("document.markdown with some description")).toBe(
true,
);
expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
});
// Test non-markdown cases
it("should not identify non-markdown headers", () => {
expect(headerIsMarkdown("javascript")).toBe(false);
expect(headerIsMarkdown("typescript")).toBe(false);
expect(headerIsMarkdown("plain")).toBe(false);
expect(headerIsMarkdown("python")).toBe(false);
});
// Test edge cases
it("should handle edge cases correctly", () => {
expect(headerIsMarkdown("")).toBe(false);
expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
expect(headerIsMarkdown("readme md")).toBe(true);
expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
});
// Test case sensitivity
it("should respect case sensitivity", () => {
expect(headerIsMarkdown("MD")).toBe(false);
expect(headerIsMarkdown("MARKDOWN")).toBe(false);
expect(headerIsMarkdown("example.MD")).toBe(false);
expect(headerIsMarkdown("lang MD")).toBe(false);
});
// Test with special characters and spacing
it("should handle special characters and spacing correctly", () => {
expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
});
});
describe("isMarkdownFile", () => {
it("should identify markdown files by .md extension", () => {
expect(isMarkdownFile("README.md")).toBe(true);
expect(isMarkdownFile("docs/guide.md")).toBe(true);
expect(isMarkdownFile("/path/to/file.md")).toBe(true);
});
it("should identify markdown files by .markdown extension", () => {
expect(isMarkdownFile("README.markdown")).toBe(true);
expect(isMarkdownFile("docs/guide.markdown")).toBe(true);
expect(isMarkdownFile("/path/to/file.markdown")).toBe(true);
});
it("should identify markdown files by .gfm extension", () => {
expect(isMarkdownFile("README.gfm")).toBe(true);
expect(isMarkdownFile("docs/guide.gfm")).toBe(true);
expect(isMarkdownFile("/path/to/file.gfm")).toBe(true);
});
it("should handle case insensitive extensions", () => {
expect(isMarkdownFile("README.MD")).toBe(true);
expect(isMarkdownFile("guide.MARKDOWN")).toBe(true);
expect(isMarkdownFile("file.GFM")).toBe(true);
});
it("should return false for non-markdown files", () => {
expect(isMarkdownFile("script.js")).toBe(false);
expect(isMarkdownFile("style.css")).toBe(false);
expect(isMarkdownFile("data.json")).toBe(false);
expect(isMarkdownFile("document.txt")).toBe(false);
});
it("should return false for undefined or empty filepath", () => {
expect(isMarkdownFile(undefined)).toBe(false);
expect(isMarkdownFile("")).toBe(false);
});
it("should return false for files without extensions", () => {
expect(isMarkdownFile("README")).toBe(false);
expect(isMarkdownFile("Dockerfile")).toBe(false);
});
it("should handle files with multiple dots", () => {
expect(isMarkdownFile("file.backup.md")).toBe(true);
expect(isMarkdownFile("config.test.js")).toBe(false);
});
});
describe("MarkdownBlockStateTracker", () => {
it("should initialize correctly with empty lines", () => {
const tracker = new MarkdownBlockStateTracker([]);
expect(tracker.shouldStopAtPosition(0)).toBe(false);
});
it("should initialize correctly with non-markdown lines", () => {
const tracker = new MarkdownBlockStateTracker([
"const x = 5;",
"console.log(x);",
]);
expect(tracker.shouldStopAtPosition(0)).toBe(false);
expect(tracker.shouldStopAtPosition(1)).toBe(false);
});
it("should detect simple markdown blocks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"# Title",
"```",
]);
expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content
expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing
});
it("should handle nested code blocks within markdown", () => {
const tracker = new MarkdownBlockStateTracker([
"```md",
"Here's some code:",
"```javascript",
"console.log('hello');",
"```",
"More content",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
});
it("should handle multiple bare backticks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"Content with ```inline``` code",
"```",
"More content",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks
expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks
});
it("should handle non-markdown code blocks", () => {
const tracker = new MarkdownBlockStateTracker([
"```javascript",
"console.log('hello');",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block
});
it("should handle mixed markdown types", () => {
const tracker = new MarkdownBlockStateTracker([
"```gfm",
"# GitHub Flavored Markdown",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(true);
});
it("should handle state persistence across multiple calls", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"# Documentation",
"```typescript",
"interface Config {}",
"```",
"Final notes",
"```",
]);
// Process incrementally
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
});
it("should handle lines that are not closing backticks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"Regular content line",
"```",
]);
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks
});
it("should provide access to trimmed lines", () => {
const tracker = new MarkdownBlockStateTracker([
" ```markdown ",
" # Title ",
" ``` ",
]);
const trimmedLines = tracker.getTrimmedLines();
expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]);
});
it("should identify bare backtick lines correctly", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"```",
"content",
"```",
]);
expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language
expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks
expect(tracker.isBareBacktickLine(2)).toBe(false); // Content
expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks
});
it("should count remaining bare backticks correctly", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"```",
"content",
"```",
"more content",
"```",
]);
expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening
expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare
expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare
expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare
});
});
describe("collectAllLines", () => {
async function* createAsyncGenerator<T>(items: T[]): AsyncGenerator<T> {
for (const item of items) {
yield item;
}
}
it("should collect all lines from a stream", async () => {
const stream = createAsyncGenerator(["line1", "line2", "line3"]);
const result = await collectAllLines(stream);
expect(result).toEqual(["line1", "line2", "line3"]);
});
it("should handle empty streams", async () => {
const stream = createAsyncGenerator([]);
const result = await collectAllLines(stream);
expect(result).toEqual([]);
});
it("should handle streams with mixed types", async () => {
const stream = createAsyncGenerator([1, "text", null, true]);
const result = await collectAllLines(stream);
expect(result).toEqual([1, "text", null, true]);
});
it("should handle streams with empty strings", async () => {
const stream = createAsyncGenerator(["", "line2", "", "line4"]);
const result = await collectAllLines(stream);
expect(result).toEqual(["", "line2", "", "line4"]);
});
it("should handle large streams", async () => {
const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`);
const stream = createAsyncGenerator(largeArray);
const result = await collectAllLines(stream);
expect(result).toEqual(largeArray);
});
it("should handle object streams", async () => {
const objects = [
{ type: "new", line: "const x = 5;" },
{ type: "old", line: "let y = 10;" },
];
const stream = createAsyncGenerator(objects);
const result = await collectAllLines(stream);
expect(result).toEqual(objects);
});
});

View file

@ -0,0 +1,98 @@
import { LineStream } from "../diff/util";
import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils";
/**
* Determines if we should stop at a markdown block based on nested markdown logic.
* This handles the complex case where markdown blocks contain other markdown blocks.
* Uses optimized state tracking to avoid redundant computation.
*/
export function shouldStopAtMarkdownBlock(
stateTracker: MarkdownBlockStateTracker,
currentIndex: number,
): boolean {
return stateTracker.shouldStopAtPosition(currentIndex);
}
/**
* Processes block nesting logic and returns updated state.
*/
export function processBlockNesting(
line: string,
seenFirstFence: boolean,
shouldRemoveLineBeforeStart: (line: string) => boolean,
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) {
return { newSeenFirstFence: false, shouldSkip: true };
}
if (!seenFirstFence) {
return { newSeenFirstFence: true, shouldSkip: false };
}
return { newSeenFirstFence: seenFirstFence, shouldSkip: false };
}
/**
* Stream transformation that stops when encountering a markdown code block ending.
* Handles nested markdown blocks in markdown files.
*/
export async function* stopAtLinesWithMarkdownSupport(
lines: LineStream,
filename: string,
): LineStream {
if (!isMarkdownFile(filename)) {
for await (const line of lines) {
if (line.trim() === "```") {
return;
}
yield line;
}
return;
}
const allLines: string[] = [];
for await (const line of lines) {
allLines.push(line);
}
const source = allLines.join("\n");
if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) {
// No nested markdown blocks detected, check for simple ``` stopping condition
let foundStandaloneBackticks = false;
for (let i = 0; i < allLines.length; i++) {
if (allLines[i].trim() === "```") {
// Found standalone backticks, yield lines up to this point
for (let j = 0; j < i; j++) {
yield allLines[j];
}
foundStandaloneBackticks = true;
return;
}
}
// No standalone backticks found, yield all lines
if (!foundStandaloneBackticks) {
for (const line of allLines) {
yield line;
}
}
return;
}
// Use optimized state tracker for markdown block analysis
const stateTracker = new MarkdownBlockStateTracker(allLines);
for (let i = 0; i < allLines.length; i++) {
if (stateTracker.shouldStopAtPosition(i)) {
for (let j = 0; j < i; j++) {
yield allLines[j];
}
return;
}
}
// If we get here, yield all lines
for (const line of allLines) {
yield line;
}
}

View file

@ -0,0 +1,102 @@
import { expect, test } from "vitest";
import { LineStream } from "../diff/util";
import {
processBlockNesting,
stopAtLinesWithMarkdownSupport,
} from "./streamMarkdownUtils";
test("processBlockNesting correctly handles starting blocks", () => {
// Mock function to determine which lines should be removed
const shouldRemoveLineBeforeStart = (line: string) =>
line === "[CODE]" || line === "```";
// Test not seeing first fence yet
const result1 = processBlockNesting(
"[CODE]",
false,
shouldRemoveLineBeforeStart,
);
expect(result1.newSeenFirstFence).toBe(false);
expect(result1.shouldSkip).toBe(true);
// Test not seeing first fence but line shouldn't be removed
const result2 = processBlockNesting(
"normal code",
false,
shouldRemoveLineBeforeStart,
);
expect(result2.newSeenFirstFence).toBe(true);
expect(result2.shouldSkip).toBe(false);
// Test already seen first fence
const result3 = processBlockNesting(
"more code",
true,
shouldRemoveLineBeforeStart,
);
expect(result3.newSeenFirstFence).toBe(true);
expect(result3.shouldSkip).toBe(false);
});
test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => {
// Create a mock line stream
const mockLines = ["line 1", "line 2", "```", "line 4"];
const lineStream: LineStream = (async function* () {
for (const line of mockLines) {
yield line;
}
})();
// Test with a non-markdown file
const filename = "test.js";
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
// Should only yield lines up to the backticks
const collected = [];
for await (const line of result) {
collected.push(line);
}
expect(collected).toEqual(["line 1", "line 2"]);
});
test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => {
// Create a mock line stream with markdown content - but NOT nested markdown blocks
const mockLines = [
"Some markdown text",
"",
"```javascript",
"function test() {",
" return true;",
"}",
"```",
"More text",
];
const lineStream: LineStream = (async function* () {
for (const line of mockLines) {
yield line;
}
})();
// Test with a markdown file
const filename = "test.md";
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
// Should yield everything since there's no nested markdown blocks
const collected = [];
for await (const line of result) {
collected.push(line);
}
// The function should stop at the standalone ``` line (not yield it or lines after)
// This is the correct behavior - it stops when it encounters standalone backticks
expect(collected).toEqual([
"Some markdown text",
"",
"```javascript",
"function test() {",
" return true;",
"}",
]);
});

View file

@ -94,4 +94,4 @@ If you need to force a refresh of the index, reload the VS Code window with <kbd
## Repository map
Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../custom-providers.mdx#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../custom-providers#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.

View file

@ -54,7 +54,7 @@ The `@Docs` context provider works by
### Hub `docs` Blocks
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
@Docs uses [`docs` blocks](../../hub/blocks/block-types#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
### Through the `@Docs` Context Provider
@ -354,7 +354,6 @@ The following configuration example includes:
- title: My Private Docs
startUrl: http://10.2.1.2/docs
faviconUrl: http://10.2.1.2/docs/assets/favicon.ico
maxDepth: 4
useLocalCrawling: true
```
</Tab>

View file

@ -143,7 +143,10 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to
config.yaml
```
context: - provider: open params: onlyPinned: true
context:
- provider: open
params:
onlyPinned: true
```
config.json
@ -164,7 +167,10 @@ Optionally, set `n` to limit the number of results returned (default 6).
config.yaml
```
context: - provider: web params: n: 5
context:
- provider: web
params:
n: 5
```
config.json
@ -183,7 +189,8 @@ Reference the most relevant snippets from your codebase.
config.yaml
```
context: - provider: codebase
context:
- provider: codebase
```
config.json
@ -223,7 +230,10 @@ Reference the results of codebase search, just like the results you would get fr
config.yaml
```
context: - provider: search params: maxResults: 100 # optional, defaults to 200
context:
- provider: search
params:
maxResults: 100 # optional, defaults to 200
```
config.json
@ -244,7 +254,8 @@ Reference the markdown converted contents of a given URL.
config.yaml
```
context: - provider: url
context:
- provider: url
```
config.json
@ -263,7 +274,8 @@ Reference recent clipboard items
config.yaml
```
context: - provider: clipboard
context:
- provider: clipboard
```
config.json
@ -282,7 +294,8 @@ Reference the structure of your current workspace.
config.yaml
```
context: - provider: tree
context:
- provider: tree
```
config.json
@ -301,7 +314,8 @@ Get Problems from the current file.
config.yaml
```
context: - provider: problems
context:
- provider: problems
```
config.json
@ -320,7 +334,10 @@ Reference the contents of the local variables in the debugger. Currently only av
config.yaml
```
context: - provider: debugger params: stackDepth: 3
context:
- provider: debugger
params:
stackDepth: 3
```
config.json
@ -343,7 +360,10 @@ Reference the outline of your codebase. By default, signatures are included alon
config.yaml
```
context: - provider: repo-map params: includeSignatures: false # default true
context:
- provider: repo-map
params:
includeSignatures: false # default true
```
config.json
@ -368,7 +388,8 @@ Reference the architecture and platform of your current operating system.
config.yaml
```
context: - provider: os
context:
- provider: os
```
config.json
@ -387,7 +408,13 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
config.yaml
```
mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
```
config.json
@ -420,7 +447,13 @@ Reference the conversation in a GitHub issue.
config.yaml
```
context: - provider: issue params: repos: - owner: continuedev repo: continue githubToken: ghp_xxx
context:
- provider: issue
params:
repos:
- owner: continuedev
repo: continue
githubToken: ghp_xxx
```
config.json
@ -451,7 +484,29 @@ Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
config.yaml
```
context: - provider: database params: connections: - name: examplePostgres connection_type: postgres connection: user: username host: localhost database: exampleDB password: yourPassword port: 5432 - name: exampleMssql connection_type: mssql connection: user: username server: localhost database: exampleDB password: yourPassword - name: exampleSqlite connection_type: sqlite connection: filename: /path/to/your/sqlite/database.db
context:
- provider: database
params:
connections:
- name: examplePostgres
connection_type: postgres
connection:
user: username
host: localhost
database: exampleDB
password: yourPassword
port: 5432
- name: exampleMssql
connection_type: mssql
connection:
user: username
server: localhost
database: exampleDB
password: yourPassword
- name: exampleSqlite
connection_type: sqlite
connection:
filename: /path/to/your/sqlite/database.db
```
config.json
@ -514,7 +569,16 @@ Reference the schema of a table, and some sample rows
config.yaml
```
context: - provider: postgres params: host: localhost port: 5436 user: myuser password: catsarecool database: animals schema: public sampleRows: 3
context:
- provider: postgres
params:
host: localhost
port: 5436
user: myuser
password: catsarecool
database: animals
schema: public
sampleRows: 3
```
config.json
@ -554,7 +618,10 @@ Reference the results of a Google search.
config.yaml
```
context: - provider: google params: serperApiKey: <YOUR_SERPER.DEV_API_KEY>
context:
- provider: google
params:
serperApiKey: <YOUR_SERPER.DEV_API_KEY>
```
config.json
@ -584,7 +651,10 @@ Reference an open MR for this branch on GitLab.
config.yaml
```
context: - provider: gitlab-mr params: token: "..."
context:
- provider: gitlab-mr
params:
token: "..."
```
config.json
@ -605,7 +675,11 @@ You can specify the domain to communicate with by setting the `domain` parameter
config.yaml
```
context: - provider: gitlab-mr params: token: "..." domain: "gitlab.example.com"
context:
- provider: gitlab-mr
params:
token: "..."
domain: "gitlab.example.com"
```
config.json
@ -635,7 +709,11 @@ Reference the conversation in a Jira issue.
config.yaml
```
context: - provider: jira params: domain: company.atlassian.net token: ATATT...
context:
- provider: jira
params:
domain: company.atlassian.net
token: ATATT...
```
config.json
@ -663,7 +741,10 @@ This context provider supports both Jira API version 2 and 3. It will use versio
config.yaml
```
context: - provider: jira params: apiVersion: "2"
context:
- provider: jira
params:
apiVersion: "2"
```
config.json
@ -696,7 +777,16 @@ Reference the messages in a Discord channel.
config.yaml
```
context: - provider: discord params: discordKey: "bot token" guildId: "1234567890" channels: - id: "123456" name: "example-channel" - id: "678901" name: "example-channel-2"
context:
- provider: discord
params:
discordKey: "bot token"
guildId: "1234567890"
channels:
- id: "123456"
name: "example-channel"
- id: "678901"
name: "example-channel-2"
```
config.json
@ -731,7 +821,10 @@ The HttpContextProvider makes a POST request to the url passed in the configurat
config.yaml
```
context: - provider: http params: url: "https://api.example.com/v1/users"
context:
- provider: http
params:
url: "https://api.example.com/v1/users"
```
config.json
@ -770,7 +863,11 @@ Reference specific git commit metadata and diff or all of the recent commits.
config.yaml
```
context: - provider: commit params: Depth: 50 LastXCommitsDepth: 10
context:
- provider: commit
params:
Depth: 50
LastXCommitsDepth: 10
```
config.json
@ -795,7 +892,11 @@ Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
config.yaml
```
context: - provider: greptile params: greptileToken: "..." githubToken: "..."
context:
- provider: greptile
params:
greptileToken: "..."
githubToken: "..."
```
config.json

View file

@ -15,7 +15,7 @@ Slash commands can be combined with additional instructions, including [context
### Assistant prompt blocks
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
### Prompt files

View file

@ -48,7 +48,13 @@ We recommend configuring **GPT-4o** as your chat model.
## Autocomplete model
We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral:
We recommend configuring **Codestral** as your autocomplete model.
<Info>
**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint.
</Info>
If you use Azure Machine Learning Studio to deploy Codestral:
<Tabs>
<Tab title="YAML">

View file

@ -21,7 +21,7 @@ You can add `embed` to a model's `roles` to specify that it can be used to embed
If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models.
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.mdx#embeddings-model).
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama#embeddings-model).
### Voyage AI
@ -57,7 +57,7 @@ After obtaining an API key from [here](https://www.voyageai.com/), you can confi
### Ollama
See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instructions on how to use Ollama for embeddings.
See [here](../model-providers/top-level/ollama#embeddings-model) for instructions on how to use Ollama for embeddings.
### Transformers.js (currently VS Code only)
@ -118,36 +118,36 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc
### OpenAI
See [here](../model-providers/top-level/openai.mdx#embeddings-model) for instructions on how to use OpenAI for embeddings.
See [here](../model-providers/top-level/openai#embeddings-model) for instructions on how to use OpenAI for embeddings.
### Cohere
See [here](../model-providers/more/cohere.mdx#embeddings-model) for instructions on how to use Cohere for embeddings.
See [here](../model-providers/more/cohere#embeddings-model) for instructions on how to use Cohere for embeddings.
### Gemini
See [here](../model-providers/top-level/gemini.mdx#embeddings-model) for instructions on how to use Gemini for embeddings.
See [here](../model-providers/top-level/gemini#embeddings-model) for instructions on how to use Gemini for embeddings.
### Vertex
See [here](../model-providers/top-level/vertexai.mdx#embeddings-model) for instructions on how to use Vertex for embeddings.
See [here](../model-providers/top-level/vertexai#embeddings-model) for instructions on how to use Vertex for embeddings.
### Mistral
See [here](../model-providers/top-level/mistral.mdx#embeddings-model) for instructions on how to use Mistral for embeddings.
See [here](../model-providers/top-level/mistral#embeddings-model) for instructions on how to use Mistral for embeddings.
### NVIDIA
See [here](../model-providers/more/nvidia.mdx#embeddings-model) for instructions on how to use NVIDIA for embeddings.
See [here](../model-providers/more/nvidia#embeddings-model) for instructions on how to use NVIDIA for embeddings.
### Bedrock
See [here](../model-providers/top-level/bedrock.mdx#embeddings-model) for instructions on how to use Bedrock for embeddings.
See [here](../model-providers/top-level/bedrock#embeddings-model) for instructions on how to use Bedrock for embeddings.
### WatsonX
See [here](../model-providers/more/watsonx.mdx#embeddings-model) for instructions on how to use WatsonX for embeddings.
See [here](../model-providers/more/watsonx#embeddings-model) for instructions on how to use WatsonX for embeddings.
### LMStudio
See [here](../model-providers/more/lmstudio.mdx#embeddings-model) for instructions on how to use LMStudio for embeddings.
See [here](../model-providers/more/lmstudio#embeddings-model) for instructions on how to use LMStudio for embeddings.

View file

@ -25,6 +25,13 @@ These models have varying tool calling and reasoning capabilities.
3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
1. Get your API key from [Together AI](https://api.together.ai)
2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
[o3](https://hub.continue.dev/openai/o3) from OpenAI
1. Get your API key from [OpenAI](https://platform.openai.com)
@ -46,10 +53,10 @@ These models have varying tool calling and reasoning capabilities.
3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
[DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) from DeepSeek
1. Get your API key from [TogetherAI](https://api.together.ai)
2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
1. Get your API key from [Together AI](https://api.together.ai)
2. Add [DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) to your assistant on Continue Hub
3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
@ -59,6 +66,18 @@ These models can be run on your computer if you have enough VRAM.
Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode.
[Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b)
1. Add [Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b) to your assistant on Continue Hub
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
3. Click `Reload config` in the assistant selector in the Continue IDE extension
[Devstral Small 27B](https://hub.continue.dev/ollama/devstral)
1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to your assistant on Continue Hub
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
3. Click `Reload config` in the assistant selector in the Continue IDE extension
[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen
1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to your assistant on Continue Hub
@ -71,10 +90,4 @@ Their limited tool calling and reasoning capabilities will make it challenging t
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
3. Click `Reload config` in the assistant selector in the Continue IDE extension
[Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) from Meta
1. Add [Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) to your assistant on Continue Hub
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
3. Click `Reload config` in the assistant selector in the Continue IDE extension
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model)

View file

@ -4,8 +4,4 @@ The input you provide is included in the prompt.
## Code to Edit
The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
## Context Providers
In VS Code Edit mode, you can use `@` to add context using [Context Providers](/customize/custom-providers), similar to [Chat](/features/chat/context-selection). Some context providers may be disabled in Edit mode.
The **entire contents** of the current file are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.

View file

@ -6,4 +6,6 @@ You can configure particular models from your Assistant to be used for Edit and
2. Click the cube icon to expand the "Models" section
3. Use the dropdowns to select models for Edit and Apply
![Edit model selection](/images/edit-model.png)
Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply).

View file

@ -14,7 +14,7 @@ Edit is recommended for small, targeted changes, such as
## Highlight code and activate
Highlight the block of code you would like to modify and press `cmd/ctrl` + `i` to active Edit mode. You can also enter Edit mode by pressing `cmd/ctrl` + `i` with no code highlighted, which will default to editing the current file.
Highlight the block of code you would like to modify and press `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to activate Edit mode. You can also press `Cmd/Ctrl+I` with no code highlighted, which will default to inserting code at the current cursor location.
## Describe code changes
@ -24,23 +24,12 @@ Describe the changes you would like the model to make to your highlighted code.
Proposed changes appear as inline diffs within your highlighted text.
You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl` + `opt` + `y` (to accept) or `cmd/ctrl` + `opt` + `n` (to reject).
You can navigate through each proposed change, accepting or rejecting them using `Cmd+Opt+Y` (Mac) or `Ctrl+Alt+Y` (Windows/Linux) to accept, or `Cmd+Opt+N` (Mac) or `Ctrl+Alt+N` (Windows/Linux) to reject.
You can also accept or reject all changes at once using `cmd/ctrl` + `shift` + `enter` (to accept) or `cmd/ctrl` + `shift` + `delete/backspace` (to reject).
You can also accept or reject all changes at once using `Cmd+Shift+Enter` (Mac) or `Ctrl+Shift+Enter` (Windows/Linux) to accept, or `Cmd+Shift+Delete` (Mac) or `Ctrl+Shift+Backspace` (Windows/Linux) to reject.
If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl` + `i` to re-prompt the model.
If you want to request a new suggestion for the same highlighted code section, you can use `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to re-prompt the model.
## VS Code
In VS Code, Edit is implemented in the extension sidebar with a similar interface to [Chat](/features/chat/how-it-works), and you can also enter Edit mode by using the Mode Selector below the main Chat input to select `Edit`.
![edit mode selected](/images/features/edit/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png)
You can also reject and accept diffs using the `Reject All` and `Accept All` buttons that show up in the Chat when diffs are present (see examples below).
### Adding Code to Edit
Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor.
## Jetbrains

View file

@ -27,7 +27,7 @@ description: "To quickly understand what you can do with Continue, check out eac
<Tab title="Edit">
[Edit](/features/edit/quick-start) is a convenient way to modify code without leaving your current file
![edit](/images/edit-d522442f88e715924b4c9f4c83900e3a.gif)
![edit](/images/edit.gif)
<Info>
Learn more about [Edit](/features/edit/quick-start)

View file

@ -79,7 +79,13 @@ After you've set up your server, you can configure Continue to use it by adding
config.yaml
```
context: - provider: http params: url: https://myserver.com/retrieve name: http description: Custom HTTP Context Provider displayTitle: My Custom Context
context:
- provider: http
params:
url: https://myserver.com/retrieve
name: http
description: Custom HTTP Context Provider
displayTitle: My Custom Context
```
config.json

View file

@ -25,7 +25,11 @@ Basic authentication can be done with any provider using the `apiKey` field:
config.yaml
```
models: - name: Ollama provider: ollama model: llama2-7b apiKey: <YOUR_CUSTOM_OLLAMA_SERVER_API_KEY>
models:
- name: Ollama
provider: ollama
model: llama2-7b
apiKey: <YOUR_CUSTOM_OLLAMA_SERVER_API_KEY>
```
config.json
@ -53,7 +57,13 @@ If you need to send custom headers for authentication, you may use the `requestO
config.yaml
```
models: - name: Ollama provider: ollama model: llama2-7b requestOptions: headers: X-Auth-Token: xxx
models:
- name: Ollama
provider: ollama
model: llama2-7b
requestOptions:
headers:
X-Auth-Token: xxx
```
config.json
@ -79,7 +89,15 @@ Similarly if your model requires a Certificate for authentication, you may use t
config.yaml
```
models: - name: Ollama provider: ollama model: llama2-7b requestOptions: clientCertificate: cert: C:\tempollama.pem key: C:\tempollama.key passphrase: c0nt!nu3
models:
- name: Ollama
provider: ollama
model: llama2-7b
requestOptions:
clientCertificate:
cert: C:\tempollama.pem
key: C:\tempollama.key
passphrase: c0nt!nu3
```
config.json

View file

@ -21,7 +21,10 @@ Ollama is the fastest way to get up and running with local language models. We r
config.yaml
```
models: - name: Llama 3.1 8b provider: ollama model: llama3.1-8b
models:
- name: Llama 3.1 8b
provider: ollama
model: llama3.1-8b
```
config.json
@ -53,7 +56,11 @@ Groq provides the fastest available inference for open-source language models, i
config.yaml
```
models: - name: Llama 3.3 70b Versatile provider: groq model: llama-3.3-70b-versatile apiKey: <YOUR_GROQ_API_KEY>
models:
- name: Llama 3.3 70b Versatile
provider: groq
model: llama-3.3-70b-versatile
apiKey: <YOUR_GROQ_API_KEY>
```
config.json
@ -85,7 +92,11 @@ Together AI provides fast and reliable inference of open-source models. You'll b
config.yaml
```
models: - name: Llama 3.1 405b provider: together model: llama3.1-405b apiKey: <YOUR_TOGETHER_API_KEY>
models:
- name: Llama 3.1 405b
provider: together
model: llama3.1-405b
apiKey: <YOUR_TOGETHER_API_KEY>
```
config.json
@ -116,7 +127,11 @@ Replicate makes it easy to host and run open-source AI with an API.
config.yaml
```
models: - name: Llama 3.1 405b provider: replicate model: llama3.1-405b apiKey: <YOUR_REPLICATE_API_KEY>
models:
- name: Llama 3.1 405b
provider: replicate
model: llama3.1-405b
apiKey: <YOUR_REPLICATE_API_KEY>
```
config.json
@ -148,7 +163,11 @@ SambaNova Cloud provides world record Llama3.1 70B/405B serving.
config.yaml
```
models: - name: SambaNova Llama 3.1 405B provider: sambanova model: llama3.1-405b apiKey: <YOUR_SAMBA_API_KEY>
models:
- name: SambaNova Llama 3.1 405B
provider: sambanova
model: llama3.1-405b
apiKey: <YOUR_SAMBA_API_KEY>
```
config.json
@ -180,7 +199,11 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L
config.yaml
```
models: - name: Cerebras Llama 3.1 70B provider: cerebras model: llama3.1-70b apiKey: <YOUR_CEREBRAS_API_KEY>
models:
- name: Cerebras Llama 3.1 70B
provider: cerebras
model: llama3.1-70b
apiKey: <YOUR_CEREBRAS_API_KEY>
```
config.json

View file

@ -19,7 +19,14 @@ Before getting started, ensure your system meets these requirements:
Choose the installation method for your operating system:
```
# macOSbrew install ollama# Linuxcurl -fsSL https://ollama.ai/install.sh | sh# Windows# Download from ollama.ai
# macOS
brew install ollama
# Linux
curl -fsSL https://ollama.ai/install.sh | sh
# Windows
# Download from ollama.ai
```
### Step 2: Download Models
@ -27,7 +34,10 @@ Choose the installation method for your operating system:
After installing Ollama, download the models you want to use. Here are some popular options:
```
# Popular models for developmentollama pull llama2ollama pull codellamaollama pull mistral
# Popular models for development
ollama pull llama2
ollama pull codellama
ollama pull mistral
```
## Configuration

View file

@ -18,7 +18,15 @@ title: "How to Set Up Codestral"
config.yaml
```
models: - name: Codestral provider: mistral model: codestral-latest apiKey: <YOUR_CODESTRAL_API_KEY> apiBase: https://codestral.mistral.ai/v1 roles: - chat - autocomplete
models:
- name: Codestral
provider: mistral
model: codestral-latest
apiKey: <YOUR_CODESTRAL_API_KEY>
apiBase: https://codestral.mistral.ai/v1
roles:
- chat
- autocomplete
```
config.json

BIN
docs/images/edit-model.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6 MiB

After

Width:  |  Height:  |  Size: 3.6 MiB

View file

@ -61,7 +61,7 @@ Blocks:
- `.continue/models` - for models
- `.continue/prompts` - for prompts
- `.continue/context` - for context providers
- `.continue/docs` - for docs~~~~
- `.continue/docs` - for docs
- `.continue/data` - for data
- `.continue/mcpServers` - for MCP Servers
@ -357,8 +357,6 @@ List of documentation sites to index.
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
- `maxDepth`: Maximum link depth for crawling. Default `4`
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler.
@ -507,7 +505,6 @@ context:
params:
startUrl: https://docs.example.com/introduction
rootUrl: https://docs.example.com
maxDepth: 3
mcpServers:
- name: DevServer
command: npm

View file

@ -4,54 +4,25 @@ description: Set up an MCP server to search Continue documentation
keywords: [mcp, documentation, search, mintlify, reference]
---
The continue-docs MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation.
The Continue Documentation MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations.
## Installation
## Set up
### Step 1: Install the MCP Server
Run the following command to install the continue-docs MCP server:
```bash
npx mint-mcp add docs.continue.dev
```
When prompted, select "All" from the selection menu:
![mintlify cli selection tree](/images/mintlify-cli-selection-tree.png)
This command will:
- Download and install the MCP server locally
- Set up the search tool for Continue documentation
- Create the necessary configuration files
<Info>
Take note of the installation path displayed after running the command above. You'll need to replace in the configuration below with your actual installation path.
It will look like this: `/path/to/user/.mcp/docs.continue.dev/src/index.js`
</Info>
### Step 2: Configure Continue
### Configure Continue
1. Create a folder called `.continue/mcpServers` at the top level of your workspace
2. Add a file called `continue-docs-mcp.yaml` to this folder
3. Write the following contents and save:
````yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
```yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
name: Continue Documentation MCP
version: 0.0.1
schema: v1
mcpServers:
- name: Continue Docs Search
command: node
args:
- "/path/to/user/.mcp/docs.continue.dev/src/index.js"
````
- uses: continuedev/continue-docs-mcp
```
### Step 3: Enable Agent Mode
### Enable Agent Mode
MCP servers only work in agent mode. Make sure to switch to agent mode in Continue before testing.
@ -62,77 +33,28 @@ Once configured, you can use the MCP server to search Continue documentation:
### Model Configuration Help
```
Search for model setup instructions in the Continue docs
How do I add Claude 4 Sonnet as a model from Bedrock in Continue?
```
### Context Providers
```
Find documentation about context providers and how to configure them
What context providers are available in Continue?
```
### Autocomplete Setup
### Customization
```
How do I configure autocomplete in Continue?
How do I add custom rules to my assistant in Continue?
```
### Slash Commands
```
Search for information about custom slash commands
```
### Troubleshooting
```
Find troubleshooting information for Continue extension issues
```
## Test Plan
Use this test plan to verify your MCP server is working correctly:
### Prerequisites
- Continue extension is installed and running
- Agent mode is enabled
- MCP server configuration file exists in `.continue/mcpServers/`
### Test Cases
#### 1. Basic Documentation Search
- **Query**: "Search the Continue docs for information about model setup"
- **Expected**: Returns structured information about configuring models
- **Pass/Fail**: ☐
#### 2. Context Provider Documentation
- **Query**: "Find documentation about context providers in Continue"
- **Expected**: Returns information about available context providers
- **Pass/Fail**: ☐
#### 3. Feature-Specific Search
- **Query**: "How do I configure autocomplete in Continue?"
- **Expected**: Returns autocomplete setup instructions
- **Pass/Fail**: ☐
#### 4. MCP Documentation Search
- **Query**: "Search for MCP server setup instructions"
- **Expected**: Returns MCP configuration information
- **Pass/Fail**: ☐
## Troubleshooting
### MCP Server Not Loading
1. **Check configuration**: Ensure your YAML configuration uses the npx command approach
2. **Verify installation**: Run `npx mint-mcp add continue-docs` to confirm the server can be accessed
3. **Check agent mode**: MCP servers only work in agent mode
4. **Restart Continue**: Try restarting the Continue extension
1. **Check configuration**: Ensure your YAML configuration uses the correct `uses` field with `continuedev/continue-docs-mcp`
2. **Check agent mode**: MCP servers only work in agent mode
3. **Restart Continue**: Try restarting the Continue extension
### No Search Results
@ -140,20 +62,6 @@ Use this test plan to verify your MCP server is working correctly:
2. **Check query format**: Try rephrasing your search query
3. **Test with known topics**: Search for well-documented features like "model configuration"
### Permission Issues
If you encounter permission errors, ensure npx has proper permissions:
```bash
npm config get prefix
```
## Advanced Configuration
### Using Environment Variables
You can configure the MCP server with environment variables:
## Related Documentation
- [MCP Overview](/customize/deep-dives/mcp)

View file

@ -88,7 +88,48 @@ config.json
config.yaml
```
models: - name: GPT-4 provider: openai model: gpt-4 apiKey: <YOUR_OPENAI_KEY> defaultCompletionOptions: temperature: 0.5 maxTokens: 2000 roles: - chat - edit - name: My Voyage Reranker provider: voyage apiKey: <YOUR_VOYAGE_KEY> roles: - rerank - name: My Starcoder provider: ollama model: starcoder2:3b roles: - autocomplete - name: My Ada Embedder provider: openai apiKey: <YOUR_ADA_API_KEY> roles: - embed embedOptions: - maxChunkSize: 256 - maxBatchSize: 5 - name: Ollama Autodetect provider: ollama model: AUTODETECT - name: My Open AI Compatible Model - Apply provider: openai model: my-openai-compatible-model apiBase: http://3.3.3.3/v1 requestOptions: headers: X-Auth-Token: <MY_API_KEY> roles: - chat - apply
models:
- name: GPT-4
provider: openai
model: gpt-4
apiKey: <YOUR_OPENAI_KEY>
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000
roles:
- chat
- edit
- name: My Voyage Reranker
provider: voyage
apiKey: <YOUR_VOYAGE_KEY>
roles:
- rerank
- name: My Starcoder
provider: ollama
model: starcoder2:3b
roles:
- autocomplete
- name: My Ada Embedder
provider: openai
apiKey: <YOUR_ADA_API_KEY>
roles:
- embed
embedOptions:
- maxChunkSize: 256
- maxBatchSize: 5
- name: Ollama Autodetect
provider: ollama
model: AUTODETECT
- name: My Open AI Compatible Model - Apply
provider: openai
model: my-openai-compatible-model
apiBase: http://3.3.3.3/v1
requestOptions:
headers:
X-Auth-Token: <MY_API_KEY>
roles:
- chat
- apply
```
Note that the `repoMapFileSelection` experimental model role has been deprecated and is only available in `config.json`.
@ -119,7 +160,13 @@ config.json
config.yaml
```
context: - provider: docs - provider: codebase params: nRetrieve: 30 nFinal: 3 - provider: diff
context:
- provider: docs
- provider: codebase
params:
nRetrieve: 30
nFinal: 3
- provider: diff
```
### System Message
@ -139,7 +186,8 @@ config.json
config.yaml
```
rules: - Always give concise responses
rules:
- Always give concise responses
```
### Prompts
@ -167,7 +215,17 @@ config.json
config.yaml
```
prompts: - name: check description: Check for mistakes in my code prompt: | Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: - Syntax errors - Logic errors - Security vulnerabilities - Performance issues - Anything else that looks wrong Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found.
prompts:
- name: check
description: Check for mistakes in my code
prompt: |
Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:
- Syntax errors
- Logic errors
- Security vulnerabilities
- Performance issues
- Anything else that looks wrong
Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found.
```
### Documentation
@ -192,7 +250,11 @@ config.json
config.yaml
```
docs: - name: nest.js startUrl: https://docs.nestjs.com/ - name: My site startUrl: https://mysite.com/docs/
docs:
- name: nest.js
startUrl: https://docs.nestjs.com/
- name: My site
startUrl: https://mysite.com/docs/
```
### MCP Servers
@ -231,7 +293,15 @@ config.json
config.yaml
```
mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db env: KEY: <VALUE>
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
env:
KEY: <VALUE>
```
---

View file

@ -92,7 +92,11 @@ If you're seeing a `fetch failed` error and your network requires custom certifi
config.yaml
```
models: - name: My Model ... requestOptions: caBundlePath: /path/to/cert.pem
models:
- name: My Model
...
requestOptions:
caBundlePath: /path/to/cert.pem
```
config.json

View file

@ -20,7 +20,6 @@
<option value="runIde"/>
</list>
</option>
<option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>

View file

@ -19,7 +19,6 @@
<!-- <option value="runInspections" />-->
<!-- </list>-->
<!-- </option>-->
<!-- <option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>-->
<!-- </ExternalSystemSettings>-->
<!-- <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>-->
<!-- <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>-->

View file

@ -13,7 +13,6 @@
<option value="runIdeForUiTests"/>
</list>
</option>
<option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>

View file

@ -13,7 +13,6 @@
<option value="test" />
</list>
</option>
<option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>

View file

@ -9,6 +9,8 @@ fun Sync.prepareSandbox() {
}
val remoteRobotVersion = "0.11.23"
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
val pluginVersion = properties("pluginVersion").get()
plugins {
id("java")
@ -22,21 +24,14 @@ plugins {
}
group = properties("pluginGroup").get()
version = if (isEap) "$pluginVersion-eap" else pluginVersion
version = properties("pluginVersion").get()
// Configure project's dependencies
repositories {
mavenCentral()
maven { url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") }
}
// Dependencies are managed with Gradle version catalog - read more:
// https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.12.0") {
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")
}
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
implementation("com.posthog.java:posthog:1.+")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
@ -48,22 +43,6 @@ dependencies {
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
// Exclude vulnerable Log4j from all dependencies
configurations.all {
resolutionStrategy {
eachDependency {
if (requested.group == "log4j" && requested.name == "log4j") {
useTarget("org.slf4j:log4j-over-slf4j:1.7.36")
}
}
}
}
// Add Log4j 2.x explicitly
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
testImplementation(kotlin("test"))
}
@ -105,7 +84,7 @@ koverReport { defaults { xml { onCheck = true } } }
tasks {
downloadRobotServerPlugin {
version.set(remoteRobotVersion)
version = remoteRobotVersion
}
prepareSandbox {
@ -120,13 +99,14 @@ tasks {
prepareSandbox()
}
wrapper { gradleVersion = properties("gradleVersion").get() }
wrapper {
gradleVersion = properties("gradleVersion").get()
}
patchPluginXml {
version.set(properties("pluginVersion"))
sinceBuild.set(properties("pluginSinceBuild"))
untilBuild.set(properties("pluginUntilBuild"))
pluginDescription.set(
sinceBuild = properties("pluginSinceBuild")
untilBuild = properties("pluginUntilBuild")
pluginDescription =
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
@ -140,7 +120,6 @@ tasks {
subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
}
}
)
}
// Configure UI tests plugin
@ -167,7 +146,7 @@ tasks {
// See ContinueExtensionSettingsService.kt for more info.
// Currently commented out however since test fail in CI with this version
// intellij {
// version.set("2024.1")
// version = "2024.1"
// }
}
@ -178,17 +157,10 @@ tasks {
}
publishPlugin {
// dependsOn("patchChangelog")
token = environment("PUBLISH_TOKEN")
// The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release
// labels, like 2.1.7-alpha.3
// Specify pre-release label to publish the plugin in a custom Release Channel automatically.
// Read more:
// https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel
channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap")))
// We always hide the stable releases until a few days of EAP have proven them stable
// hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false)
val channel = if (isEap) "eap" else "default"
channels = listOf(channel)
}
runIde {

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.30
pluginVersion=1.0.31
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.auth
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
@ -10,24 +11,22 @@ import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes
import com.intellij.util.io.HttpRequests
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.net.URL
import kotlin.time.Duration.Companion.minutes
@Service
class ContinueAuthService {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private val log = Logger.getInstance(ContinueAuthService::class.java)
companion object {
fun getInstance(): ContinueAuthService = service<ContinueAuthService>()
private const val CREDENTIALS_USER = "ContinueAuthUser"
private const val ACCESS_TOKEN_KEY = "ContinueAccessToken"
private const val REFRESH_TOKEN_KEY = "ContinueRefreshToken"
@ -77,73 +76,47 @@ class ContinueAuthService {
}
private fun updateRefreshToken(token: String) {
// Launch a coroutine to call the suspend function
coroutineScope.launch {
try {
val response = refreshToken(token)
val accessToken = response["accessToken"] as? String
val refreshToken = response["refreshToken"] as? String
val user = response["user"] as? Map<*, *>
val firstName = user?.get("firstName") as? String
val lastName = user?.get("lastName") as? String
val label = "$firstName $lastName"
val id = user?.get("id") as? String
val email = user?.get("email") as? String
try {
val response = refreshToken(token)
val accountLabel = "${response.user.firstName} ${response.user.lastName}"
// Persist the session info
setRefreshToken(refreshToken!!)
val sessionInfo =
ControlPlaneSessionInfo(accessToken!!, ControlPlaneSessionInfo.Account(email!!, label))
setControlPlaneSessionInfo(sessionInfo)
// Persist the session info
setRefreshToken(response.refreshToken)
val account = ControlPlaneSessionInfo.Account(response.user.email, accountLabel)
val sessionInfo = ControlPlaneSessionInfo(response.accessToken, account)
setControlPlaneSessionInfo(sessionInfo)
// Notify listeners
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(sessionInfo)
} catch (e: Exception) {
// Handle any exceptions
println("Exception while refreshing token: ${e.message}")
}
// Notify listeners
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(sessionInfo)
} catch (e: Exception) {
service<ContinueErrorService>().report(e, "Exception while refreshing token ${e.message}")
}
}
private fun setupRefreshTokenInterval() {
// Launch a coroutine to refresh the token every 30 minutes
coroutineScope.launch {
while (true) {
val refreshToken = getRefreshToken()
if (refreshToken != null) {
updateRefreshToken(refreshToken)
}
kotlinx.coroutines.delay(15 * 60 * 1000) // 15 minutes in milliseconds
log.info("Token refreshed, retrying in 15 minutes")
delay(15.minutes)
}
}
}
private suspend fun refreshToken(refreshToken: String) = withContext(Dispatchers.IO) {
val client = OkHttpClient()
val url = URL(getControlPlaneUrl()).toURI().resolve("/auth/refresh").toURL()
val jsonBody = mapOf("refreshToken" to refreshToken)
val jsonString = Gson().toJson(jsonBody)
val requestBody = jsonString.toRequestBody("application/json".toMediaType())
val request = Request.Builder()
.url(url)
.post(requestBody)
.header("Content-Type", "application/json")
.build()
val response = client.newCall(request).execute()
val responseBody = response.body?.string()
private fun refreshToken(refreshToken: String): RefreshTokenResponse {
val gson = Gson()
val responseMap = gson.fromJson(responseBody, Map::class.java)
responseMap
val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken))
val url = getControlPlaneUrl() + "/auth/refresh"
val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
.connect { connection -> connection.write(jsonBody.toByteArray()) }
.toString()
return gson.fromJson(response, RefreshTokenResponse::class.java)
}
private fun openSignInPage(project: Project, useOnboarding: Boolean): String? {
var authUrl: String? = null
val coreMessenger = project.service<ContinuePluginService>().coreMessenger
@ -256,6 +229,17 @@ class ContinueAuthService {
setAccountLabel(info.account.label)
}
private data class RefreshTokenResponse(
val accessToken: String,
val refreshToken: String,
val user: User,
) {
data class User(
val firstName: String,
val lastName: String,
val email: String
)
}
}
// Data class to represent the ControlPlaneSessionInfo

View file

@ -7,9 +7,11 @@ import com.github.continuedev.continueintellijextension.`continue`.process.Conti
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.uuid
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
class CoreMessenger(
private val project: Project,
@ -20,6 +22,7 @@ class CoreMessenger(
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
private val process = startContinueProcess()
private val log = Logger.getInstance(CoreMessenger::class.java)
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
@ -38,13 +41,13 @@ class CoreMessenger(
}
private fun handleMessage(json: String) {
val responseMap = gson.fromJson(json, Map::class.java)
val responseMap = tryToParse(json) ?: return
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
val data = responseMap["data"]
// IDE listeners
if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) {
if (messageType in MessageTypes.IDE_MESSAGE_TYPES) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data))
process.write(message)
@ -52,8 +55,9 @@ class CoreMessenger(
}
// Forward to webview
if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
if (messageType in MessageTypes.PASS_THROUGH_TO_WEBVIEW) {
val continuePluginService = project.service<ContinuePluginService>()
// todo: is this a bug below (messageType = ID)? verify
continuePluginService.sendToWebview(messageType, responseMap["data"], messageType)
}
@ -68,6 +72,15 @@ class CoreMessenger(
}
}
// todo: map<*, *> = code smell
private fun tryToParse(json: String): Map<*, *>? =
try {
gson.fromJson(json, Map::class.java)
} catch (_: JsonSyntaxException) {
log.warn("Invalid message JSON: $json") // example: NODE_ENV undefined
null
}
fun killSubProcess() {
process.close()
}

View file

@ -8,12 +8,13 @@ import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.protocol.*
import com.github.continuedev.continueintellijextension.services.*
import com.github.continuedev.continueintellijextension.utils.*
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.github.continuedev.continueintellijextension.utils.uuid
import com.google.gson.Gson
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.fileEditor.FileEditorManager
@ -21,7 +22,10 @@ import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.ToolWindowManager
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
@ -323,7 +327,11 @@ class IdeProtocolClient(
}
"runCommand" -> {
// Running commands not yet supported in JetBrains
val params = Gson().fromJson(
dataElement.toString(),
RunCommandParams::class.java
)
ide.runCommand(params.command, params.options)
respond(null)
}

View file

@ -1,4 +1,3 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
@ -27,12 +26,14 @@ import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightVirtualFile
import kotlinx.coroutines.*
import org.jetbrains.plugins.terminal.ShellTerminalWidget
import org.jetbrains.plugins.terminal.TerminalView
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.io.BufferedReader
@ -54,7 +55,7 @@ class IntelliJIDE(
init {
try {
val os = getOS()
if (os == OS.LINUX || os == OS.MAC) {
val file = File(ripgrep)
if (!file.canExecute()) {
@ -135,7 +136,33 @@ class IntelliJIDE(
}
override suspend fun getTerminalContents(): String {
return ""
return withContext(Dispatchers.EDT) {
try {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal")
val terminalView = TerminalView.getInstance(project)
// Find the first terminal widget selected, whatever its state, running command or not.
val widget = terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>().firstOrNull {
toolWindow?.getContentManager()?.getContent(it)?.isSelected ?: false
}
if (widget != null) {
val textBuffer = widget.terminalTextBuffer
val stringBuilder = StringBuilder()
// Iterate through all lines in the buffer (history + screen)
for (i in 0 until textBuffer.historyLinesCount + textBuffer.screenLinesCount) {
stringBuilder.append(textBuffer.getLine(i).text).append('\n')
}
stringBuilder.toString()
} else {
"" // Return empty if no terminal is available
}
} catch (e: Exception) {
println("Error getting terminal contents: ${e.message}")
e.printStackTrace()
"" // Return empty on error
}
}
}
override suspend fun getDebugLocals(threadIndex: Int): String {
@ -220,8 +247,65 @@ class IntelliJIDE(
}
}
override suspend fun runCommand(command: String) {
throw NotImplementedError("runCommand not implemented in IntelliJ")
override suspend fun runCommand(command: String, options: TerminalOptions?) {
val terminalOptions =
options ?: TerminalOptions(reuseTerminal = true, terminalName = null, waitForCompletion = false)
ApplicationManager.getApplication().invokeLater {
try {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal")
toolWindow?.activate({
try {
val terminalView = TerminalView.getInstance(project)
var widget: ShellTerminalWidget? = null
// 1. Handle reuseTerminal option
if (terminalOptions.reuseTerminal == true && terminalView.getWidgets().isNotEmpty()) {
// 2. Find by terminalName if provided
if (terminalOptions.terminalName != null) {
widget = terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>()
.firstOrNull {
toolWindow.contentManager.getContent(it).tabName == terminalOptions.terminalName
&& !it.hasRunningCommands()
}
} else {
// 3. Find active terminal, or fall back to the first one
widget = terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>()
.firstOrNull { toolWindow.contentManager.getContent(it).isSelected }
?: terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>().firstOrNull {
!it.hasRunningCommands()
}
}
}
// 4. Create a new terminal if needed
if (widget == null) {
widget = terminalView.createLocalShellWidget(
project.basePath,
terminalOptions.terminalName,
true
)
} else {
// Ensure the found widget is visible
val content = toolWindow.contentManager.getContent(widget)
if (content != null) {
toolWindow.contentManager.setSelectedContent(content, true)
}
}
// 5. Show and send text
widget.ttyConnector?.write(command)
} catch (e: Exception) {
println("Error during terminal widget handling: ${e.message}")
e.printStackTrace()
}
}, true)
} catch (e: Exception) {
println("Error activating terminal tool window: ${e.message}")
e.printStackTrace()
}
}
}
override suspend fun saveFile(filepath: String) {
@ -343,7 +427,7 @@ class IntelliJIDE(
}
val command = GeneralCommandLine(commandArgs)
command.setWorkDirectory(project.basePath)
val results = ExecUtil.execAndGetOutput(command).stdout
return results.split("\n")
@ -357,11 +441,12 @@ class IntelliJIDE(
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
}
}
override suspend fun getSearchResults(query: String, maxResults: Int?): String {
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
try {
val commandArgs = mutableListOf(
val commandArgs = mutableListOf(
ripgrep,
"-i",
"--ignore-file",
@ -372,20 +457,20 @@ class IntelliJIDE(
"2",
"--heading"
)
// Conditionally add maxResults flag
if (maxResults != null) {
commandArgs.add("-m")
commandArgs.add(maxResults.toString())
}
// Add the search query and path
commandArgs.add("-e")
commandArgs.add(query)
commandArgs.add(".")
val command = GeneralCommandLine(commandArgs)
command.setWorkDirectory(project.basePath)
return ExecUtil.execAndGetOutput(command).stdout
} catch (exception: Exception) {
@ -594,6 +679,14 @@ class IntelliJIDE(
throw NotImplementedError("gotoDefinition not implemented yet")
}
override suspend fun gotoTypeDefinition(location: Location): List<RangeInFile> {
throw NotImplementedError("gotoTypeDefinition not implemented yet")
}
override suspend fun getSignatureHelp(location: Location): SignatureHelp? {
throw NotImplementedError("getSignatureHelp not implemented yet")
}
override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) {
throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet")
}

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
@ -44,11 +45,8 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
err = err.substring(doneIndex + delimiter.length)
}
}
println("Core process exited with output: $err")
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
service<ContinueErrorService>().reportMessage("Core process exited with output: $err")
service<TelemetryService>().capture("jetbrains_core_exit", mapOf("error" to err))
}
private companion object {
@ -67,6 +65,7 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
elevatePermissions()
}
// todo: consider setting permissions ahead-of-time during build/packaging, not at runtime
private fun elevatePermissions() {
val path = getContinueBinaryPath()
val permissions = setOf(

View file

@ -6,6 +6,7 @@ import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.jcef.JBCefApp
import io.sentry.Hint
import io.sentry.Sentry
@ -26,6 +27,8 @@ class ContinueErrorService {
config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
config.setTag("jcef_supported", JBCefApp.isSupported().toString())
config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version)
config.setTag("system", SystemInfo.OS_NAME)
config.setTag("system_version", SystemInfo.OS_VERSION)
}
}
@ -39,7 +42,14 @@ class ContinueErrorService {
sentryEvent.message = Message().apply { this.message = message }
val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) })
Sentry.captureEvent(sentryEvent, hint)
log.warn("Problem sent to Sentry: $message", throwable)
log.warn("Exception sent to Sentry: $message", throwable)
}
fun reportMessage(
message: String,
) {
Sentry.captureMessage(message)
log.warn("Message sent to Sentry: $message")
}
private companion object {

View file

@ -1,6 +1,7 @@
package com.github.continuedev.continueintellijextension.protocol
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.Range
import com.github.continuedev.continueintellijextension.TerminalOptions
data class GetControlPlaneSessionInfoParams(val silent: Boolean, val useOnboarding: Boolean)
@ -59,4 +60,6 @@ data class GetGitRootPathParams(val dir: String)
data class ListDirParams(val dir: String)
data class GetFileStatsParams(val files: List<String>)
data class GetFileStatsParams(val files: List<String>)
data class RunCommandParams(val command: String, val options: TerminalOptions?)

View file

@ -1,25 +1,25 @@
package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.intellij.execution.target.value.constant
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.io.HttpRequests
import com.intellij.util.messages.Topic
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.io.File
import java.io.IOException
import java.net.URL
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import javax.swing.*
@ -72,11 +72,10 @@ class ContinueSettingsComponent : DumbAware {
}
}
@Serializable
class ContinueRemoteConfigSyncResponse {
var configJson: String? = null
var configJs: String? = null
}
data class ContinueRemoteConfigSyncResponse(
var configJson: String?,
var configJs: String?
)
@State(
name = "com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings",
@ -117,50 +116,23 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
// Sync remote config from server
private fun syncRemoteConfig() {
val state = instance.continueState
if (state.remoteConfigServerUrl != null && state.remoteConfigServerUrl!!.isNotEmpty()) {
// download remote config as json file
val client = OkHttpClient()
val baseUrl = state.remoteConfigServerUrl?.removeSuffix("/")
val requestBuilder = Request.Builder().url("${baseUrl}/sync")
if (state.userToken != null) {
requestBuilder.addHeader("Authorization", "Bearer ${state.userToken}")
}
val request = requestBuilder.build()
var configResponse: ContinueRemoteConfigSyncResponse? = null
val remoteServerUrl = state.remoteConfigServerUrl
val token = state.userToken
if (remoteServerUrl != null && remoteServerUrl.isNotEmpty()) {
val baseUrl = remoteServerUrl.removeSuffix("/")
try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
response.body?.string()?.let { responseBody ->
try {
configResponse =
Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
} catch (e: Exception) {
e.printStackTrace()
return
}
}
}
val url = "$baseUrl/sync"
val responseBody = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
.tuner { connection ->
if (token != null)
connection.addRequestProperty("Authorization", "Bearer $token")
}.readString()
val response = Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
val file = File(getConfigJsonPath(URL(url).host))
response.configJs.let { file.writeText(it!!) }
response.configJson.let { file.writeText(it!!) }
} catch (e: IOException) {
e.printStackTrace()
return
}
if (configResponse?.configJson?.isNotEmpty()!!) {
val file = File(getConfigJsonPath(request.url.host))
file.writeText(configResponse!!.configJson!!)
}
if (configResponse?.configJs?.isNotEmpty()!!) {
val file = File(getConfigJsPath(request.url.host))
file.writeText(configResponse!!.configJs!!)
service<ContinueErrorService>().report(e, "Unexpected exception during remote config sync")
}
}
}
@ -174,7 +146,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
instance.remoteSyncFuture = AppExecutorUtil.getAppScheduledExecutorService()
.scheduleWithFixedDelay(
{ syncRemoteConfig() },
::syncRemoteConfig,
0,
continueState.remoteConfigSyncPeriod.toLong(),
TimeUnit.MINUTES

View file

@ -64,6 +64,68 @@ data class RangeInFileWithContents(
val contents: String
)
/**
* Signature help represents the signature of something
* callable. There can be multiple signatures but only one
* active and only one active parameter.
*/
data class SignatureHelp(
/**
* One or more signatures.
*/
val signatures: List<SignatureInformation>,
/**
* The active signature.
*/
val activeSignature: Int,
/**
* The active parameter of the active signature.
*/
val activeParameter: Int
)
/**
* Represents the signature of something callable. A signature
* can have a label, like a function-name, a doc-comment, and
* a set of parameters.
*/
data class SignatureInformation(
/**
* The label of this signature. Will be shown in
* the UI.
*/
val label: String,
/**
* The parameters of this signature.
*/
val parameters: List<ParameterInformation>,
/**
* The index of the active parameter.
*
* If provided, this is used in place of [SignatureHelp.activeParameter].
*/
val activeParameter: Int? = null
)
/**
* Represents a parameter of a callable-signature. A parameter can
* have a label and a doc-comment.
*/
data class ParameterInformation(
/**
* The label of this signature.
*
* Either a string or inclusive start and exclusive end offsets within its containing
* [SignatureInformation.label] signature label. *Note*: A label of type string must be
* a substring of its containing signature information's [SignatureInformation.label] label.
*/
val label: String // Note: Kotlin doesn't have union types, so this represents the string case
)
data class ControlPlaneSessionInfo(
val accessToken: String,
val account: Account
@ -91,6 +153,11 @@ data class ContinueRcJson(
val mergeBehavior: ConfigMergeType
)
data class TerminalOptions(
val reuseTerminal: Boolean?,
val terminalName: String?,
val waitForCompletion: Boolean?
)
interface IDE {
suspend fun getIdeInfo(): IdeInfo
@ -134,7 +201,7 @@ interface IDE {
suspend fun openUrl(url: String)
suspend fun runCommand(command: String)
suspend fun runCommand(command: String, options: TerminalOptions?)
suspend fun saveFile(filepath: String)
@ -192,6 +259,8 @@ interface IDE {
// LSP
suspend fun gotoDefinition(location: Location): List<RangeInFile>
suspend fun gotoTypeDefinition(location: Location): List<RangeInFile>
suspend fun getSignatureHelp(location: Location): SignatureHelp?
// Callbacks
fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit)
@ -253,4 +322,4 @@ data class ShowFilePayload(
sealed class FimResult {
data class FimEdit(val fimText: String) : FimResult()
object NotFimEdit : FimResult()
}
}

View file

@ -7,6 +7,7 @@
<![CDATA[View the latest release notes on <a href="https://github.com/continuedev/continue/releases">GitHub</a>]]></change-notes>
<depends>com.intellij.modules.platform</depends>
<depends>org.jetbrains.plugins.terminal</depends>
<!-- See here for why this is optional: https://github.com/continuedev/continue/issues/2775#issuecomment-2535620877-->
<depends optional="true" config-file="continueintellijextension-withJSON.xml">

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.66",
"version": "1.1.67",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -6,7 +6,10 @@ import { EXTENSION_NAME } from "core/control-plane/env";
import * as URI from "uri-js";
import * as vscode from "vscode";
import { executeGotoProvider } from "./autocomplete/lsp";
import {
executeGotoProvider,
executeSignatureHelpProvider,
} from "./autocomplete/lsp";
import { Repository } from "./otherExtensions/git";
import { SecretStorage } from "./stubs/SecretStorage";
import { VsCodeIdeUtils } from "./util/ideUtils";
@ -24,6 +27,7 @@ import type {
Location,
Problem,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
} from "core";
@ -87,6 +91,28 @@ class VsCodeIde implements IDE {
return result;
}
async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
const result = await executeGotoProvider({
uri: vscode.Uri.parse(location.filepath),
line: location.position.line,
character: location.position.character,
name: "vscode.executeTypeDefinitionProvider",
});
return result;
}
async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
const result = await executeSignatureHelpProvider({
uri: vscode.Uri.parse(location.filepath),
line: location.position.line,
character: location.position.character,
name: "vscode.executeSignatureHelpProvider",
});
return result;
}
onDidChangeActiveTextEditor(callback: (uri: string) => void): void {
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor) {

View file

@ -13,7 +13,13 @@ import { intersection } from "core/util/ranges";
import * as URI from "uri-js";
import * as vscode from "vscode";
import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core";
import type {
IDE,
Range,
RangeInFile,
RangeInFileWithContents,
SignatureHelp,
} from "core";
import type Parser from "web-tree-sitter";
type GotoProviderName =
@ -23,6 +29,8 @@ type GotoProviderName =
| "vscode.executeImplementationProvider"
| "vscode.executeReferenceProvider";
type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider";
interface GotoInput {
uri: vscode.Uri;
line: number;
@ -33,8 +41,19 @@ function gotoInputKey(input: GotoInput) {
return `${input.name}${input.uri.toString()}${input.line}${input.character}`;
}
interface SignatureHelpInput {
uri: vscode.Uri;
line: number;
character: number;
name: SignatureHelpProviderName;
}
function signatureHelpKey(input: SignatureHelpInput) {
return `${input.name}${input.uri.toString()}${input.line}${input.character}`;
}
const MAX_CACHE_SIZE = 500;
const gotoCache = new Map<string, RangeInFile[]>();
const signatureHelpCache = new Map<string, vscode.SignatureHelp>();
export async function executeGotoProvider(
input: GotoInput,
@ -382,3 +401,36 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async (
return [];
}
};
export async function executeSignatureHelpProvider(
input: SignatureHelpInput,
): Promise<SignatureHelp | null> {
const cacheKey = signatureHelpKey(input);
const cached = signatureHelpCache.get(cacheKey);
if (cached) {
return cached;
}
try {
const definitions = (await vscode.commands.executeCommand(
input.name,
input.uri,
new vscode.Position(input.line, input.character),
)) as SignatureHelp;
// Add to cache
if (signatureHelpCache.size >= MAX_CACHE_SIZE) {
// Remove the oldest item from the cache
const oldestKey = signatureHelpCache.keys().next().value;
if (oldestKey) {
signatureHelpCache.delete(oldestKey);
}
}
signatureHelpCache.set(cacheKey, definitions);
return definitions;
} catch (e) {
console.warn(`Error executing ${input.name}:`, e);
return null;
}
}

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