Merge branch 'main' into session-file

This commit is contained in:
uinstinct 2025-07-17 23:00:29 +05:30
commit a52211f027
171 changed files with 7182 additions and 1976 deletions

View file

@ -1,11 +0,0 @@
name: Continue Documentation MCP
version: 0.0.1
schema: v1
mcpServers:
- name: Continue Docs Search
type: stdio
command: npx
args:
- mint-mcp
- add
- continue-docs

View file

@ -24,7 +24,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
branch: cla-signatures
# Bots and CLAs signed outside of GitHub
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline

48
CLA.md Normal file
View file

@ -0,0 +1,48 @@
# Individual Contributor License Agreement (v1.0, Continue)
_Based on the Apache Software Foundation Individual CLA v 2.2._
By commenting **“I have read the CLA Document and I hereby sign the CLA”**
on a Pull Request, **you (“Contributor”) agree to the following terms** for any
past and future “Contributions” submitted to **Continue (the “Project”)**.
---
## 1. Definitions
- **“Contribution”** – any original work of authorship submitted to the Project
(code, documentation, designs, etc.).
- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
comment.
## 2. Copyright License
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
license to reproduce, prepare derivative works of, publicly display, publicly
perform, sublicense, and distribute Your Contributions and derivative works.
## 3. Patent License
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
license to make, have made, use, sell, offer to sell, import, and otherwise
transfer Your Contributions alone or in combination with the Project.
If any entity brings patent litigation alleging that the Project or a
Contribution infringes a patent, the patent licenses granted by You to that
entity under this CLA terminate.
## 4. Representations
1. You are legally entitled to grant the licenses above.
2. Each Contribution is either Your original creation or You have authority to
submit it under this CLA.
3. Your Contributions are provided **“AS IS”** without warranties of any kind.
4. You will notify the Project if any statement above becomes inaccurate.
## 5. Miscellany
This Agreement is governed by the laws of the **State of California**, USA,
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
the remaining provisions remain in force.

View file

@ -9,9 +9,7 @@
* creating a render of it.
*/
import {
transformerMetaHighlight,
transformerNotationDiff,
transformerNotationFocus,
transformerNotationHighlight,
} from "@shikijs/transformers";
import { JSDOM } from "jsdom";
@ -21,6 +19,7 @@ import {
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { escapeForSVG, kebabOfStr } from "../util/text";
interface CodeRendererOptions {
@ -37,6 +36,10 @@ interface HTMLOptions {
interface ConversionOptions extends HTMLOptions {
transparent?: boolean;
imageType: "svg";
fontSize: number;
fontFamily: string;
dimensions: Dimensions;
lineHeight: number;
}
interface Dimensions {
@ -166,83 +169,102 @@ export class CodeRenderer {
code: string,
language: string = "javascript",
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<string> {
const annotatedCode = code
.split("\n")
.map((line, i) =>
i === currLineOffsetFromTop
? line + " \/\/ \[\!code highlight\]"
: line,
)
.join("\n");
const lines = code.split("\n");
const newDiffLineMap = new Set();
if (newDiffLines) {
newDiffLines.forEach((diffLine) => {
if (diffLine.type === "new") {
newDiffLineMap.add(diffLine.line);
}
});
}
const annotatedLines = [];
// NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line.
// If you are transforming an empty line, make sure that
// the transformation is applied to a non-empty line first.
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Add highlight comment before target line.
if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) {
annotatedLines.push("// [!code highlight:1]");
}
// Handle diff lines
if (newDiffLineMap.has(line)) {
if (line.trim() === "") {
// For empty lines, add the magic comment on a separate line before.
annotatedLines.push("// [!code ++]");
annotatedLines.push(line); // The empty line itself.
} else {
// For non-empty lines, append the magic comment.
annotatedLines.push(line + "// [!code ++]");
}
newDiffLineMap.delete(line);
} else {
annotatedLines.push(line);
}
}
const annotatedCode = annotatedLines.join("\n");
await this.highlighter!.loadLanguage(language as BundledLanguage);
return this.highlighter!.codeToHtml(annotatedCode, {
lang: language,
theme: this.currentTheme,
transformers: [
// transformerColorizedBrackets(),
transformerMetaHighlight(),
transformerNotationHighlight(),
transformerNotationDiff(),
transformerNotationFocus(),
],
transformers: [transformerNotationHighlight(), transformerNotationDiff()],
});
}
async convertToSVG(
code: string,
language: string = "javascript",
fontSize: number,
fontFamily: string,
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<Buffer> {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
code,
language,
currLineOffsetFromTop,
newDiffLines,
);
// console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
fontSize,
fontFamily,
lineHeight,
dimensions,
options,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
--green: rgb(136, 194, 163);
--blue: rgb(107, 166, 205);
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${dimensions.width}" height="${dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
console.log(svg);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
--green: rgb(136, 194, 163);
--blue: rgb(107, 166, 205);
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
// console.log(svg);
return Buffer.from(svg, "utf8");
}
convertShikiHtmlToSvgGut(
shikiHtml: string,
fontSize: number,
fontFamily: string,
lineHeight: number,
dimensions: Dimensions,
options: ConversionOptions,
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
@ -263,6 +285,7 @@ export class CodeRenderer {
if (classes.includes("highlighted")) {
fill = ` fill="${this.editorLineHighlight}"`;
}
const content = el.textContent || "";
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
})
@ -278,8 +301,8 @@ export class CodeRenderer {
// The first step is to add lineHeight / 2 to move the axis down.
// The second step is to add 'dominant-baseline="central"' to vertically center the text.
// Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
const y = index * lineHeight + lineHeight / 2;
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
const y = index * options.lineHeight + options.lineHeight / 2;
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
const lineBackgrounds = lines
@ -287,8 +310,11 @@ export class CodeRenderer {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: this.editorBackground;
const y = index * lineHeight;
: classes.includes("diff add")
? "rgba(255, 255, 0, 0.2)"
: this.editorBackground;
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const radius = 10;
@ -297,24 +323,24 @@ export class CodeRenderer {
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
return isFirst
? `<path d="M ${0} ${y + lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${dimensions.width - radius} ${y}
Q ${dimensions.width} ${y} ${dimensions.width} ${y + radius}
L ${dimensions.width} ${y + lineHeight}
Z"
fill="${bgColor}" />`
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + lineHeight - radius}
Q ${0} ${y + lineHeight} ${radius} ${y + lineHeight}
L ${dimensions.width - radius} ${y + lineHeight}
Q ${dimensions.width} ${y + lineHeight} ${dimensions.width} ${y + lineHeight - 10}
L ${dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" rx="${radius}" ry="${radius}" width="100%" height="${lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
})
.join("\n");
@ -344,12 +370,9 @@ export class CodeRenderer {
async getDataUri(
code: string,
language: string = "javascript",
fontSize: number,
fontFamily: string,
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
@ -366,12 +389,9 @@ export class CodeRenderer {
const svgBuffer = await this.convertToSVG(
code,
language,
fontSize,
fontFamily,
dimensions,
lineHeight,
options,
currLineOffsetFromTop,
newDiffLines,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}

View file

@ -11,12 +11,14 @@ import {
} from "../index.js";
import { GlobalContext } from "../util/GlobalContext.js";
import EventEmitter from "node:events";
import {
AuthType,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import { Telemetry } from "../util/posthog.js";
import {
ASSISTANTS,
getAllDotContinueDefinitionFiles,
@ -44,6 +46,16 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
totalConfigLoads: number = 0;
public isInitialized: Promise<void>;
private initter: EventEmitter;
cascadeAbortController: AbortController;
private abortCascade() {
this.cascadeAbortController.abort();
this.cascadeAbortController = new AbortController();
}
constructor(
private readonly ide: IDE,
@ -53,9 +65,11 @@ export class ConfigHandler {
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
this.ide.getIdeInfo(),
);
// This profile manager will always be available
@ -80,7 +94,13 @@ export class ConfigHandler {
this.currentOrg = personalOrg;
this.organizations = [personalOrg];
void this.cascadeInit();
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
this.initter.on("init", resolve);
});
this.cascadeAbortController = new AbortController();
void this.cascadeInit("Config handler initialization");
}
private workspaceDirs: string[] | null = null;
@ -96,54 +116,71 @@ export class ConfigHandler {
return `${workspaceId}:::${orgId}`;
}
private async cascadeInit() {
private async cascadeInit(reason: string) {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
const orgs = await this.getOrgs();
try {
const orgs = await this.getOrgs();
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
}
if (signal.aborted) {
return; // local only case, no`fetch to throw abort error
}
this.initter.emit("init");
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig(reason);
} catch (e) {
if (e instanceof Error && e.message.includes("AbortError")) {
return;
} else {
this.initter.emit("init"); // Error case counts for initialization
throw e;
}
}
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig();
}
private async getOrgs(): Promise<OrgWithProfiles[]> {
if (await this.controlPlaneClient.isSignedIn()) {
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
);
return [...hubOrgs, personalHubOrg];
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
return orgs;
} else {
return [await this.getLocalOrg()];
}
@ -312,13 +349,14 @@ export class ConfigHandler {
// Should not be used internally
//////////////////
async refreshAll() {
await this.cascadeInit();
await this.cascadeInit("External refresh all");
}
// Ide settings change: refresh session and cascade refresh from the top
async updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
await this.cascadeInit();
this.abortCascade();
await this.cascadeInit("IDE settings update");
}
// Session change: refresh session and cascade refresh from the top
@ -328,8 +366,10 @@ export class ConfigHandler {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
this.ide.getIdeInfo(),
);
await this.cascadeInit();
this.abortCascade();
await this.cascadeInit("Control plane session info update");
}
// Org id: check id validity, save selection, switch and reload
@ -356,7 +396,7 @@ export class ConfigHandler {
await this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig();
await this.reloadConfig("Selected org changed");
}
}
@ -384,14 +424,17 @@ export class ConfigHandler {
});
this.currentProfile = profile;
await this.reloadConfig();
await this.reloadConfig("Selected profile changed");
}
// Bottom level of cascade: refresh the current profile
// IMPORTANT - must always refresh when switching profiles
// Because of e.g. MCP singleton and docs service using things from config
// Could improve this
async reloadConfig() {
async reloadConfig(reason: string) {
const startTime = performance.now();
this.totalConfigLoads += 1;
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
if (!this.currentProfile) {
return {
config: undefined,
@ -415,6 +458,17 @@ export class ConfigHandler {
await this.currentProfile.reloadConfig(this.additionalContextProviders);
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
duration,
reason,
totalConfigLoads: this.totalConfigLoads,
configLoadInterrupted,
});
return { config, errors, configLoadInterrupted };
}
@ -457,6 +511,7 @@ export class ConfigHandler {
configLoadInterrupted: true,
};
}
await this.isInitialized;
const config = await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
@ -487,7 +542,7 @@ export class ConfigHandler {
private additionalContextProviders: IContextProvider[] = [];
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
void this.reloadConfig();
void this.reloadConfig("Custom context provider registered");
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".

View file

@ -32,7 +32,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
}`;
fs.writeFileSync(getConfigTsPath(), configTs);
await new Promise((resolve) => setTimeout(resolve, 1000));
const config = await testConfigHandler.reloadConfig();
const config = await testConfigHandler.reloadConfig("test");
/**
* @ts-ignore is applied because this test is skipped
*/
@ -45,7 +45,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
path.join(TEST_DIR, ".continuerc.json"),
JSON.stringify({ systemMessage: "SYSTEM2" }),
);
const config = await testConfigHandler.reloadConfig();
const config = await testConfigHandler.reloadConfig("test");
/**
* @ts-ignore is applied because this test is skipped
*/

View file

@ -19,7 +19,6 @@ export const sharedConfigSchema = z
readResponseTTS: z.boolean(),
promptPath: z.string(),
useCurrentFileAsContext: z.boolean(),
logEditingData: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
@ -181,9 +180,6 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.useCurrentFileAsContext =
sharedConfig.useCurrentFileAsContext;
}
if (sharedConfig.logEditingData !== undefined) {
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
}
if (sharedConfig.optInNextEditFeature !== undefined) {
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;

View file

@ -235,6 +235,8 @@ async function configYamlToContinueConfig(options: {
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
maxDepth: doc.maxDepth,
useLocalCrawling: doc.useLocalCrawling,
}));
config.mcpServers?.forEach((mcpServer) => {

View file

@ -19,7 +19,7 @@ import { BuiltInToolNames } from "../../../tools/builtIn";
import { callBuiltInTool } from "../../../tools/callTool";
import { globSearchTool } from "../../../tools/definitions/globSearch";
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
import { lsTool } from "../../../tools/definitions/lsTool";
import { lsTool } from "../../../tools/definitions/ls";
import { readFileTool } from "../../../tools/definitions/readFile";
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
@ -60,12 +60,13 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex | null = null;
private lanceDbInitPromise: Promise<void> | null = null;
constructor(protected readonly options: RetrievalPipelineOptions) {
void this.initLanceDb();
}
private async initLanceDb() {
protected async initLanceDb() {
const embedModel = this.options.config.selectedModelByRole.embed;
if (!embedModel) {
@ -77,6 +78,23 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
protected async ensureLanceDbInitialized(): Promise<boolean> {
if (this.lanceDbIndex) {
return true;
}
if (this.lanceDbInitPromise) {
await this.lanceDbInitPromise;
return this.lanceDbIndex !== null;
}
this.lanceDbInitPromise = this.initLanceDb();
await this.lanceDbInitPromise;
this.lanceDbInitPromise = null; // clear after init
return this.lanceDbIndex !== null;
}
private getCleanedTrigrams(
query: RetrievalPipelineRunArguments["query"],
): string[] {
@ -163,7 +181,9 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
input: string,
n: number,
): Promise<Chunk[]> {
if (!this.lanceDbIndex) {
const initialized = await this.ensureLanceDbInitialized();
if (!initialized || !this.lanceDbIndex) {
console.warn(
"LanceDB index not available, skipping embeddings retrieval",
);

View file

@ -10,7 +10,7 @@ import {
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
@ -40,6 +40,7 @@ export class ControlPlaneClient {
ControlPlaneSessionInfo | undefined
>,
private readonly ideSettingsPromise: Promise<IdeSettings>,
private readonly ideInfoPromise: Promise<IdeInfo>,
) {}
async resolveFQSNs(
@ -86,11 +87,17 @@ export class ControlPlaneClient {
const env = await getControlPlaneEnv(this.ideSettingsPromise);
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const ideInfo = await this.ideInfoPromise;
const resp = await fetch(url, {
...init,
headers: {
...init.headers,
Authorization: `Bearer ${accessToken}`,
...{
"x-extension-version": ideInfo.extensionVersion,
"x-is-prerelease": String(ideInfo.isPrerelease),
},
},
});

View file

@ -132,7 +132,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
try {
// Use REG QUERY command to read registry values
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {
@ -145,7 +148,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
try {
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {

View file

@ -73,6 +73,7 @@ import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { getUriPathBasename } from "./util/uri";
import { NextEditProvider } from "./nextEdit/NextEditProvider";
const hasRulesFiles = (uris: string[]): boolean => {
for (const uri of uris) {
@ -88,6 +89,7 @@ export class Core {
configHandler: ConfigHandler;
codeBaseIndexer: CodebaseIndexer;
completionProvider: CompletionProvider;
nextEditProvider: NextEditProvider;
private docsService: DocsService;
private globalContext = new GlobalContext();
llmLogger = new LLMLogger();
@ -150,7 +152,7 @@ export class Core {
);
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("MCP Connections refreshed");
// Refresh @mention dropdown submenu items for MCP providers
const mcpManager = MCPManagerSingleton.getInstance();
@ -233,6 +235,15 @@ export class Core {
(..._) => Promise.resolve([]),
);
this.nextEditProvider = NextEditProvider.initialize(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
"fineTuned",
);
this.registerMessageHandlers(ideSettingsPromise);
}
@ -299,23 +310,31 @@ export class Core {
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model, msg.data.role);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Model added (config/addModel message)",
);
});
on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Model removed (config/deleteModel message)",
);
});
on("config/newPromptFile", async (msg) => {
const { config } = await this.configHandler.loadConfig();
await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Prompt file created (config/newPromptFile message)",
);
});
on("config/addLocalWorkspaceBlock", async (msg) => {
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Local block created (config/addLocalWorkspaceBlock message)",
);
});
on("config/openProfile", async (msg) => {
@ -323,7 +342,9 @@ export class Core {
});
on("config/reload", async (msg) => {
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Force reloaded (config/reload message)",
);
return await this.configHandler.getSerializedConfig();
});
@ -343,7 +364,9 @@ export class Core {
on("config/updateSharedConfig", async (msg) => {
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Shared config update (config/updateSharedConfig message)",
);
return newSharedConfig;
});
@ -353,7 +376,9 @@ export class Core {
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Selected model update (config/updateSelectedModel message)",
);
return newSelectedModels;
});
@ -481,6 +506,18 @@ export class Core {
});
on("llm/listModels", this.handleListModels.bind(this));
on("llm/compileChat", async (msg) => {
const { messages, options } = msg.data;
const model = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!model) {
throw new Error("No chat model selected");
}
return model.compileChatMessages(messages, options);
});
// Provide messenger to utils so they can interact with GUI + state
TTS.messenger = this.messenger;
ChatDescriber.messenger = this.messenger;
@ -516,6 +553,21 @@ export class Core {
this.completionProvider.cancel();
});
// Next Edit
on("nextEdit/predict", async (msg) => {
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
msg.data,
undefined,
);
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
});
on("nextEdit/accept", async (msg) => {
this.nextEditProvider.accept(msg.data.completionId);
});
on("nextEdit/reject", async (msg) => {
this.nextEditProvider.reject(msg.data.completionId);
});
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
@ -630,7 +682,7 @@ export class Core {
void refreshIfNotIgnored(data.uris);
if (hasRulesFiles(data.uris)) {
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig("Rules file created");
}
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
@ -652,7 +704,7 @@ export class Core {
void refreshIfNotIgnored(data.uris);
if (hasRulesFiles(data.uris)) {
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig("Rules file deleted");
}
}
});
@ -928,7 +980,7 @@ export class Core {
],
}),
);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Autocomplete model added");
}
private async handleFilesChanged({
@ -958,7 +1010,9 @@ export class Core {
this.globalContext.update("showConfigUpdateToast", false);
}
}
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Current profile config file updated",
);
continue;
}
@ -974,7 +1028,9 @@ export class Core {
uri.includes(`.continue\\${blockType}`),
)
) {
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Config-related file updated: continuerc, prompt, local block, etc",
);
} else if (
uri.endsWith(".continueignore") ||
uri.endsWith(".gitignore")
@ -1056,7 +1112,7 @@ export class Core {
editConfigFile((c) => c, editConfigYamlCallback);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Onboarding completed");
}
private getContextItems = async (

View file

@ -1,6 +1,6 @@
import { diffLines, type Change } from "diff";
import { diffChars, diffLines, type Change } from "diff";
import { DiffLine } from "..";
import { DiffChar, DiffLine } from "..";
export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
const type: DiffLine["type"] = change.added
@ -55,3 +55,157 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
return ourFormat;
}
export function myersCharDiff(
oldContent: string,
newContent: string,
): DiffChar[] {
// Process the content character by character.
// We will handle newlines separately,
// because diffChars does not have an option to ignore eol newlines.
const theirFormat = diffChars(oldContent, newContent);
// Track indices as we process the diff.
let oldIndex = 0;
let newIndex = 0;
let oldLineIndex = 0;
let newLineIndex = 0;
let oldCharIndexInLine = 0;
let newCharIndexInLine = 0;
const result: DiffChar[] = [];
for (const change of theirFormat) {
// Split the change value by newlines to handle them separately.
if (change.value.includes("\n")) {
const parts = change.value.split(/(\n)/g); // This keeps the newlines as separate entries.
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part === "") continue;
if (part === "\n") {
// Handle newline.
if (change.added) {
result.push({
type: "new",
char: part,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += part.length;
newLineIndex++;
newCharIndexInLine = 0; // Reset when moving to a new line.
} else if (change.removed) {
result.push({
type: "old",
char: part,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += part.length;
oldLineIndex++;
oldCharIndexInLine = 0; // Reset when moving to a new line.
} else {
result.push({
type: "same",
char: part,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += part.length;
newIndex += part.length;
oldLineIndex++;
newLineIndex++;
oldCharIndexInLine = 0;
newCharIndexInLine = 0;
}
} else {
// Handle regular text.
if (change.added) {
result.push({
type: "new",
char: part,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += part.length;
newCharIndexInLine += part.length;
} else if (change.removed) {
result.push({
type: "old",
char: part,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += part.length;
oldCharIndexInLine += part.length;
} else {
result.push({
type: "same",
char: part,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += part.length;
newIndex += part.length;
oldCharIndexInLine += part.length;
newCharIndexInLine += part.length;
}
}
}
} else {
// No newlines, handle as a simple change.
if (change.added) {
result.push({
type: "new",
char: change.value,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += change.value.length;
newCharIndexInLine += change.value.length;
} else if (change.removed) {
result.push({
type: "old",
char: change.value,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += change.value.length;
oldCharIndexInLine += change.value.length;
} else {
result.push({
type: "same",
char: change.value,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += change.value.length;
newIndex += change.value.length;
oldCharIndexInLine += change.value.length;
newCharIndexInLine += change.value.length;
}
}
}
return result;
}

View file

@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import { dedent } from "../util";
import { myersDiff } from "./myers";
import { myersCharDiff, myersDiff } from "./myers";
describe("Test myers diff function", () => {
test("should ...", () => {
@ -56,3 +56,589 @@ describe("Test myers diff function", () => {
]);
});
});
describe("Test myersCharDiff function on the same line", () => {
test("should differentiate character changes", () => {
const oldContent = "hello world";
const newContent = "hello earth";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "hello ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "wo",
oldIndex: 6,
oldCharIndexInLine: 6,
oldLineIndex: 0,
},
{
type: "new",
char: "ea",
newIndex: 6,
newCharIndexInLine: 6,
newLineIndex: 0,
},
{
type: "same",
char: "r",
oldIndex: 8,
newIndex: 8,
oldCharIndexInLine: 8,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "ld",
oldIndex: 9,
oldCharIndexInLine: 9,
oldLineIndex: 0,
},
{
type: "new",
char: "th",
newIndex: 9,
newCharIndexInLine: 9,
newLineIndex: 0,
},
]);
});
test("should handle insertions", () => {
const oldContent = "abc";
const newContent = "abxyzc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "ab",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "xyz",
newIndex: 2,
newCharIndexInLine: 2,
newLineIndex: 0,
},
{
type: "same",
char: "c",
oldIndex: 2,
newIndex: 5,
oldCharIndexInLine: 2,
newCharIndexInLine: 5,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle deletions", () => {
const oldContent = "abxyzc";
const newContent = "abc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "ab",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "xyz",
oldIndex: 2,
oldCharIndexInLine: 2,
oldLineIndex: 0,
},
{
type: "same",
char: "c",
oldIndex: 5,
newIndex: 2,
oldCharIndexInLine: 5,
newCharIndexInLine: 2,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle empty strings", () => {
const oldContent = "";
const newContent = "abc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "new",
char: "abc",
newIndex: 0,
newCharIndexInLine: 0,
newLineIndex: 0,
},
]);
});
test("should handle identical strings", () => {
const content = "no changes here";
const diffChars = myersCharDiff(content, content);
expect(diffChars).toEqual([
{
type: "same",
char: "no changes here",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle whitespace changes", () => {
const oldContent = "hello world";
const newContent = "hello world";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "hello ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: " ",
newIndex: 6,
newCharIndexInLine: 6,
newLineIndex: 0,
},
{
type: "same",
char: "world",
oldIndex: 6,
newIndex: 7,
oldCharIndexInLine: 6,
newCharIndexInLine: 7,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle complex changes", () => {
const oldContent = "The quick brown fox jumps over the lazy dog";
const newContent = "The fast brown fox leaps over the sleeping dog";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "The ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "quick",
oldIndex: 4,
oldCharIndexInLine: 4,
oldLineIndex: 0,
},
{
type: "new",
char: "fast",
newIndex: 4,
newCharIndexInLine: 4,
newLineIndex: 0,
},
{
type: "same",
char: " brown fox ",
oldIndex: 9,
newIndex: 8,
oldCharIndexInLine: 9,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "jum",
oldIndex: 20,
oldCharIndexInLine: 20,
oldLineIndex: 0,
},
{
type: "new",
char: "lea",
newIndex: 19,
newCharIndexInLine: 19,
newLineIndex: 0,
},
{
type: "same",
char: "ps over the ",
oldIndex: 23,
newIndex: 22,
oldCharIndexInLine: 23,
newCharIndexInLine: 22,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "s",
newIndex: 34,
newCharIndexInLine: 34,
newLineIndex: 0,
},
{
type: "same",
char: "l",
oldIndex: 35,
newIndex: 35,
oldCharIndexInLine: 35,
newCharIndexInLine: 35,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "azy",
oldIndex: 36,
oldCharIndexInLine: 36,
oldLineIndex: 0,
},
{
type: "new",
char: "eeping",
newIndex: 36,
newCharIndexInLine: 36,
newLineIndex: 0,
},
{
type: "same",
char: " dog",
oldIndex: 39,
newIndex: 42,
oldCharIndexInLine: 39,
newCharIndexInLine: 42,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
});
describe("Test myersCharDiff function on different lines", () => {
test("should track line indices for multi-line changes", () => {
const oldContent = ["Line one", "Line two", "Line three"].join("\n");
const newContent = ["Line one", "Modified line", "Line three"].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "Line one",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 8,
newIndex: 8,
oldCharIndexInLine: 8,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "L",
oldIndex: 9,
oldCharIndexInLine: 0,
oldLineIndex: 1,
},
{
type: "new",
char: "Mod",
newIndex: 9,
newCharIndexInLine: 0,
newLineIndex: 1,
},
{
char: "i",
newCharIndexInLine: 3,
newIndex: 12,
newLineIndex: 1,
oldCharIndexInLine: 1,
oldIndex: 10,
oldLineIndex: 1,
type: "same",
},
{
char: "n",
oldCharIndexInLine: 2,
oldIndex: 11,
oldLineIndex: 1,
type: "old",
},
{
char: "fi",
newCharIndexInLine: 4,
newIndex: 13,
newLineIndex: 1,
type: "new",
},
{
char: "e",
newCharIndexInLine: 6,
newIndex: 15,
newLineIndex: 1,
oldCharIndexInLine: 3,
oldIndex: 12,
oldLineIndex: 1,
type: "same",
},
{
char: "d",
newCharIndexInLine: 7,
newIndex: 16,
newLineIndex: 1,
type: "new",
},
{
char: " ",
newCharIndexInLine: 8,
newIndex: 17,
newLineIndex: 1,
oldCharIndexInLine: 4,
oldIndex: 13,
oldLineIndex: 1,
type: "same",
},
{
type: "old",
char: "two",
oldCharIndexInLine: 5,
oldIndex: 14,
oldLineIndex: 1,
},
{
type: "new",
char: "line",
newCharIndexInLine: 9,
newIndex: 18,
newLineIndex: 1,
},
{
type: "same",
char: "\n",
oldIndex: 17,
oldCharIndexInLine: 8,
oldLineIndex: 1,
newIndex: 22,
newCharIndexInLine: 13,
newLineIndex: 1,
},
{
type: "same",
char: "Line three",
oldIndex: 18,
newIndex: 23,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 2,
newLineIndex: 2,
},
]);
});
test("should track line indices when adding new lines", () => {
const oldContent = ["First line", "Last line"].join("\n");
const newContent = [
"First line",
"Middle line",
"Another middle",
"Last line",
].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "First line",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 10,
newIndex: 10,
oldCharIndexInLine: 10,
newCharIndexInLine: 10,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "Middle line",
newIndex: 11,
newCharIndexInLine: 0,
newLineIndex: 1,
},
{
type: "new",
char: "\n",
newIndex: 22,
newCharIndexInLine: 11,
newLineIndex: 1,
},
{
type: "new",
char: "Another middle",
newCharIndexInLine: 0,
newIndex: 23,
newLineIndex: 2,
},
{
type: "new",
char: "\n",
newCharIndexInLine: 14,
newIndex: 37,
newLineIndex: 2,
},
{
type: "same",
char: "Last line",
oldIndex: 11,
oldCharIndexInLine: 0,
oldLineIndex: 1,
newIndex: 38,
newCharIndexInLine: 0,
newLineIndex: 3,
},
]);
});
test("should track line indices when removing lines", () => {
const oldContent = [
"Start",
"Line to remove",
"Another to remove",
"End",
].join("\n");
const newContent = ["Start", "End"].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "Start",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 5,
newIndex: 5,
oldCharIndexInLine: 5,
newCharIndexInLine: 5,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "Line to remove",
oldIndex: 6,
oldCharIndexInLine: 0,
oldLineIndex: 1,
},
{
type: "old",
char: "\n",
oldCharIndexInLine: 14,
oldIndex: 20,
oldLineIndex: 1,
},
{
type: "old",
char: "Another to remove",
oldCharIndexInLine: 0,
oldIndex: 21,
oldLineIndex: 2,
},
{
type: "old",
char: "\n",
oldCharIndexInLine: 17,
oldIndex: 38,
oldLineIndex: 2,
},
{
type: "same",
char: "End",
oldIndex: 39,
newIndex: 6,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 3,
newLineIndex: 1,
},
]);
});
});

View file

@ -1,4 +1,4 @@
import { DiffLine, DiffLineType } from "../index.js";
import { DiffLine, DiffType } from "../index.js";
import { LineStream, matchLine } from "./util.js";
@ -33,7 +33,7 @@ export async function* streamDiff(
seenIndentationMistake = true;
}
let type: DiffLineType;
let type: DiffType;
const isNewLine = matchIndex === -1;

View file

@ -6,11 +6,11 @@ import { describe, expect, test } from "vitest";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
import { DiffLine, DiffType } from "../index.js";
import { generateLines } from "./util.js";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
type MyersDiffTypes = Extract<DiffType, "new" | "old"> | "modification";
const UNIFIED_DIFF_SYMBOLS = {
same: "",

67
core/index.d.ts vendored
View file

@ -122,6 +122,7 @@ export interface ILLM
messages: ChatMessage[],
signal: AbortSignal,
options?: LLMFullCompletionOptions,
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog>;
chat(
@ -130,6 +131,11 @@ export interface ILLM
options?: LLMFullCompletionOptions,
): Promise<ChatMessage>;
compileChatMessages(
messages: ChatMessage[],
options: LLMFullCompletionOpeions,
): CompiledChatMessagesReport;
embed(chunks: string[]): Promise<number[][]>;
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
@ -432,12 +438,12 @@ export interface PromptLog {
export type MessageModes = "chat" | "agent" | "plan";
export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";
| "generating" // Tool call arguments are being streamed from the LLM
| "generated" // Tool call is complete and ready for execution (awaiting approval)
| "calling" // Tool is actively being executed
| "errored" // Tool execution failed with an error
| "done" // Tool execution completed successfully
| "canceled"; // Tool call was canceled by user or system
// Will exist only on "assistant" messages with tool calls
interface ToolCallState {
@ -462,7 +468,7 @@ export interface ChatHistoryItem {
editorState?: any;
modifiers?: InputModifiers;
promptLogs?: PromptLog[];
toolCallState?: ToolCallState;
toolCallStates?: ToolCallState[];
isGatheringContext?: boolean;
reasoning?: Reasoning;
appliedRules?: RuleWithSource[];
@ -666,13 +672,26 @@ export type CustomLLM = RequireAtLeastOne<
// IDE
export type DiffLineType = "new" | "old" | "same";
export type DiffType = "new" | "old" | "same";
export interface DiffLine {
type: DiffLineType;
export interface DiffObject {
type: DiffType;
}
export interface DiffLine extends DiffObject {
line: string;
}
interface DiffChar extends DiffObject {
char: string;
oldIndex?: number; // Character index assuming a flattened line string.
newIndex?: number;
oldCharIndexInLine?: number; // Character index assuming new lines reset the character index to 0.
newCharIndexInLine?: number;
oldLineIndex?: number;
newLineIndex?: number;
}
export interface Problem {
filepath: string;
range: Range;
@ -692,6 +711,7 @@ export interface IdeInfo {
version: string;
remoteName: string;
extensionVersion: string;
isPrerelease: boolean;
}
export interface BranchAndDir {
@ -1269,7 +1289,6 @@ export interface ContinueUIConfig {
codeWrap?: boolean;
showSessionTabs?: boolean;
autoAcceptEditToolDiffs?: boolean;
logEditingData?: boolean;
}
export interface ContextMenuConfig {
@ -1422,11 +1441,6 @@ export interface ExperimentalConfig {
*/
useCurrentFileAsContext?: boolean;
/**
* If enabled, will save data on the user's editing processes
*/
logEditingData?: boolean;
/**
* If enabled, will enable next edit in place of autocomplete
*/
@ -1669,3 +1683,24 @@ export interface CompleteOnboardingPayload {
provider?: string;
apiKey?: string;
}
export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned";
export interface CompiledMessagesResult {
compiledChatMessages: ChatMessage[];
pruningStatus: PruningStatus;
}
export interface MessageOption {
precompiled: boolean;
}
export type WarningMessageLevel = "warning" | "fatal";
export type WarningCategory = "exceeded-context-length" | "deleted-last-input";
export interface WarningMessage {
message: string;
level: WarningMessageLevel;
category: WarningCategory;
}

View file

@ -1,3 +1,5 @@
/* eslint-disable max-lines-per-function */
/* lint is not useful for test classes */
import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
@ -14,8 +16,11 @@ import {
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { ConfigResult } from "@continuedev/config-yaml";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
import { ContinueConfig } from "../index.js";
import { localPathToUri } from "../util/pathToUri.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { CodebaseIndexer } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
@ -57,6 +62,17 @@ class TestCodebaseIndexer extends CodebaseIndexer {
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
return [new TestCodebaseIndex()];
}
// Add public methods to test private methods
public testHasCodebaseContextProvider() {
return (this as any).hasCodebaseContextProvider();
}
public async testHandleConfigUpdate(
configResult: ConfigResult<ContinueConfig>,
) {
return (this as any).handleConfigUpdate({ config: configResult.config });
}
}
// Create a mock messenger type that doesn't require actual protocol imports
@ -71,8 +87,6 @@ type MockMessengerType = {
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
const pauseToken = new PauseToken(false);
// Replace mockProgressReporter with mockMessenger
const mockMessenger: MockMessengerType = {
send: jest.fn(),
@ -82,13 +96,8 @@ describe("CodebaseIndexer", () => {
onError: jest.fn(),
};
const codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
const testIndex = new TestCodebaseIndex();
let codebaseIndexer: TestCodebaseIndexer;
let testIndex: TestCodebaseIndex;
beforeAll(async () => {
tearDownTestDir();
@ -99,6 +108,15 @@ describe("CodebaseIndexer", () => {
cwd: TEST_DIR_PATH,
});
execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
await codebaseIndexer.initPromise;
testIndex = new TestCodebaseIndex();
});
afterAll(async () => {
@ -161,6 +179,7 @@ describe("CodebaseIndexer", () => {
}
test("should index test folder without problem", async () => {
walkDirCache.invalidate();
addToTestDir([
["test.ts", TEST_TS],
["py/main.py", TEST_PY],
@ -403,4 +422,270 @@ describe("CodebaseIndexer", () => {
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
});
});
// New describe block for testing handleConfigUpdate functionality
describe("handleConfigUpdate functionality", () => {
let testIndexer: TestCodebaseIndexer;
let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
let mockGetWorkspaceDirs: jest.MockedFunction<any>;
beforeEach(() => {
testIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
// Mock the refreshCodebaseIndex method to avoid actual indexing
mockRefreshCodebaseIndex = jest
.spyOn(testIndexer, "refreshCodebaseIndex")
.mockImplementation(async () => {});
// Mock getWorkspaceDirs to return test directories
mockGetWorkspaceDirs = jest
.spyOn(testIde, "getWorkspaceDirs")
.mockResolvedValue(["/test/workspace"]);
});
afterEach(() => {
jest.clearAllMocks();
});
describe("hasCodebaseContextProvider", () => {
test("should return true when codebase context provider is present", () => {
// Set up config with codebase context provider
(testIndexer as any).config = {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(true);
});
test("should return false when no context providers are configured", () => {
(testIndexer as any).config = {
contextProviders: undefined,
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(false);
});
test("should return false when context providers exist but no codebase provider", () => {
(testIndexer as any).config = {
contextProviders: [
{
description: {
title: "SomeOtherProvider",
},
},
],
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(false);
});
test("should return false when context providers is empty array", () => {
(testIndexer as any).config = {
contextProviders: [],
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(false);
});
});
describe("handleConfigUpdate", () => {
test("should return early when newConfig is null", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: null as any,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should return early when newConfig is undefined", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: undefined as any,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should return early when no codebase context provider is present", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: "SomeOtherProvider",
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should return early when no embed model is configured", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
selectedModelByRole: {
embed: undefined,
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should call refreshCodebaseIndex when all conditions are met", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, and we want them to get called again
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
"/test/workspace",
]);
});
test("should set config property before checking conditions", async () => {
const testConfig = {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig;
const configResult: ConfigResult<ContinueConfig> = {
config: testConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// Verify that the config was set
expect((testIndexer as any).config).toBe(testConfig);
// These get called once on init, and we want them to get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
});
test("should handle multiple context providers correctly", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: "SomeOtherProvider",
},
},
{
description: {
title: CodebaseContextProvider.description.title,
},
},
{
description: {
title: "AnotherProvider",
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, and we want them to get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
"/test/workspace",
]);
});
});
});
});

View file

@ -1,7 +1,12 @@
import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import {
ContinueConfig,
IDE,
IndexingProgressUpdate,
IndexTag,
} from "../index.js";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
@ -9,11 +14,14 @@ import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { Telemetry } from "../util/posthog.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ConfigResult } from "@continuedev/config-yaml";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
import { ContinueServerClient } from "../continueServer/stubs/client";
import { LLMError } from "../llm/index.js";
import { getRootCause } from "../util/errors.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { embedModelsAreEqual } from "./docs/DocsService.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
@ -44,6 +52,10 @@ export class CodebaseIndexer {
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 200;
// We normally allow this to run in the background,
// and only need to `await` it for tests.
public initPromise: Promise<void>;
private config!: ContinueConfig;
private indexingCancellationController: AbortController | undefined;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
@ -83,6 +95,17 @@ export class CodebaseIndexer {
// Initialize pause token
this.pauseToken = new PauseToken(initialPaused);
this.initPromise = this.init(configHandler);
}
// Initialization - load config and attach config listener
private async init(configHandler: ConfigHandler) {
const result = await configHandler.loadConfig();
await this.handleConfigUpdate(result);
configHandler.onConfigUpdate(
this.handleConfigUpdate.bind(this) as (arg: any) => void,
);
}
set paused(value: boolean) {
@ -192,7 +215,7 @@ export class CodebaseIndexer {
workspaceDirs: string[],
): Promise<void> {
if (this.pauseToken.paused) {
// NOTE: by returning here, there is a chance that while paused a file is modified and
// FIXME: by returning here, there is a chance that while paused a file is modified and
// then after unpausing the file is not reindexed
return;
}
@ -763,4 +786,49 @@ export class CodebaseIndexer {
public get currentIndexingState(): IndexingProgressUpdate {
return this.codebaseIndexingState;
}
private hasCodebaseContextProvider() {
return !!this.config.contextProviders?.some(
(provider) =>
provider.description.title ===
CodebaseContextProvider.description.title,
);
}
private isIndexingConfigSame(
config1: ContinueConfig | undefined,
config2: ContinueConfig,
) {
return embedModelsAreEqual(
config1?.selectedModelByRole.embed,
config2.selectedModelByRole.embed,
);
}
private async handleConfigUpdate({
config: newConfig,
}: ConfigResult<ContinueConfig>) {
if (newConfig) {
const needsReindex = !this.isIndexingConfigSame(this.config, newConfig);
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
// No point in indexing if no codebase context provider
const hasCodebaseContextProvider = this.hasCodebaseContextProvider();
if (!hasCodebaseContextProvider) {
return;
}
// Skip codebase indexing if not supported
// No warning message here because would show on ANY config update
if (!this.config.selectedModelByRole.embed) {
return;
}
if (needsReindex) {
const dirs = await this.ide.getWorkspaceDirs();
await this.refreshCodebaseIndex(dirs);
}
}
}
}

View file

@ -7,6 +7,15 @@ export interface SiteIndexingResults {
title: string;
}
/**
* Strip off the trailing forward slash from the given URL
* @param url The URL of the document
* @returns A sanitized URL without trailing forward slash
*/
const stripTrailingSlash = (url: string): string => {
return url.replace(/\/+$/, "");
};
export class DocsCache {
static readonly AWS_REGION: string = "us-west-1";
static readonly BUCKET_NAME: string = "continue-preindexed-docs";
@ -33,7 +42,8 @@ export class DocsCache {
url: string,
): string {
const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
const sanitizedUrl = stripTrailingSlash(url);
const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_"));
return normalizedEmbeddingId + "/" + normalizedUrl;
}

View file

@ -69,7 +69,7 @@ const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
(d) => !docConfigsAreEqual(siteIndexingConfig, d),
);
newFailedDocs.push(siteIndexingConfig);
globalContext.update("failedDocs", newFailedDocs);
@ -81,7 +81,7 @@ const removeFromFailedGlobalContext = (
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
(d) => !docConfigsAreEqual(siteIndexingConfig, d),
);
globalContext.update("failedDocs", newFailedDocs);
};
@ -89,32 +89,69 @@ const removeFromFailedGlobalContext = (
const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
return failedDocs.find((d) =>
siteIndexingConfigsAreEqual(siteIndexingConfig, d),
return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d));
};
export function embedModelsAreEqual(
llm1: ILLM | null | undefined,
llm2: ILLM | null | undefined,
): boolean {
return (
llm1?.underlyingProviderName === llm2?.underlyingProviderName &&
llm1?.title === llm2?.title &&
llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize
);
}
const docConfigsAreEqual = (
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
) => {
return (
siteConfig1.faviconUrl === siteConfig2.faviconUrl &&
siteConfig1.title === siteConfig2.title &&
docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2)
);
};
const docConfigsAreEqualExceptTitleAndFavicon = (
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
) => {
return (
siteConfig1.startUrl === siteConfig2.startUrl &&
siteConfig1.maxDepth === siteConfig2.maxDepth &&
siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling
);
};
const siteIndexingConfigsAreEqual = (
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
contConfig1: ContinueConfig | undefined,
contConfig2: ContinueConfig,
) => {
return (
config1.startUrl === config2.startUrl &&
config1.faviconUrl === config2.faviconUrl &&
config1.title === config2.title &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
docConfigsAreEqual(siteConfig1, siteConfig2) &&
embedModelsAreEqual(
contConfig1?.selectedModelByRole.embed,
contConfig2.selectedModelByRole.embed,
)
);
};
const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
contConfig1: ContinueConfig | undefined,
contConfig2: ContinueConfig,
) => {
return (
config1.startUrl === config2.startUrl &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) &&
embedModelsAreEqual(
contConfig1?.selectedModelByRole.embed,
contConfig2.selectedModelByRole.embed,
)
);
};
@ -1037,12 +1074,22 @@ export default class DocsService {
);
// TODO: Changes to the docs config made while Continue isn't running won't be caught
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
if (
oldConfigDoc &&
!siteIndexingConfigsAreEqual(
oldConfigDoc,
doc,
oldConfig,
newConfig,
)
) {
// When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
if (
siteIndexingConfigsAreEqualExceptTitleAndFavicon(
oldConfigDoc,
doc,
oldConfig,
newConfig,
)
) {
await this.updateMetadataInSqlite(doc);
@ -1262,7 +1309,7 @@ export default class DocsService {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
docConfigsAreEqual(doc, siteIndexingConfig),
);
if (!doesEquivalentDocExist) {

View file

@ -3,7 +3,17 @@ import { fileURLToPath } from "url";
export default {
transform: {
"^.+\\.(ts|js)$": ["ts-jest", { useESM: true, useIsolatedModules: true }],
"^.+\\.(ts|js)$": [
"ts-jest",
{
useESM: true,
useIsolatedModules: true,
tsconfig: {
experimentalDecorators: true,
emitDecoratorMetadata: true,
},
},
],
},
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",

View file

@ -1,10 +1,11 @@
// @ts-nocheck
// Generated by continue
import { ChatMessage, MessagePart } from "../index.js";
import { ChatMessage, MessagePart, ToolCall } from "../index.js";
import {
compileChatMessages,
countTokens,
countTokensAsync,
extractToolSequence,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,
@ -174,3 +175,188 @@ describe.skip("compileChatMessages", () => {
expect(compiled.length).toBe(1);
});
});
describe("extractToolSequence", () => {
// Helper function to create mock messages
const createUserMessage = (content: string): ChatMessage => ({
role: "user",
content,
});
const createAssistantMessage = (
content: string,
toolCalls?: ToolCall[],
): ChatMessage => ({
role: "assistant",
content,
toolCalls,
});
const createToolMessage = (
content: string,
toolCallId: string,
): ChatMessage => ({
role: "tool",
content,
toolCallId,
});
const createToolCall = (
id: string,
name: string,
args: object,
): ToolCall => ({
id,
type: "function",
function: {
name,
arguments: JSON.stringify(args),
},
});
test("extractToolSequence should handle a single user message", () => {
const messages: ChatMessage[] = [createUserMessage("Hello world!")];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(1);
expect(sequence[0].role).toBe("user");
expect(sequence[0].content).toBe("Hello world!");
expect(messages).toHaveLength(0); // Original array should be modified
});
test("extractToolSequence should handle a single tool message with assistant", () => {
const toolCall = createToolCall("tc_1", "read_file", { path: "test.txt" });
const messages: ChatMessage[] = [
createAssistantMessage("I'll read the file for you.", [toolCall]),
createToolMessage("File contents here", "tc_1"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(2);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(sequence[1].toolCallId).toBe("tc_1");
expect(messages).toHaveLength(0);
});
test("extractToolSequence should handle multiple consecutive tool messages", () => {
const toolCall1 = createToolCall("tc_1", "read_file", { path: "test.txt" });
const toolCall2 = createToolCall("tc_2", "write_file", {
path: "output.txt",
content: "data",
});
const messages: ChatMessage[] = [
createAssistantMessage("I'll read and write files.", [
toolCall1,
toolCall2,
]),
createToolMessage("File contents 1", "tc_1"),
createToolMessage("File written successfully", "tc_2"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(3);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(sequence[1].toolCallId).toBe("tc_1");
expect(sequence[2].role).toBe("tool");
expect(sequence[2].toolCallId).toBe("tc_2");
expect(messages).toHaveLength(0);
});
test("extractToolSequence should handle tool sequence with previous context", () => {
const toolCall = createToolCall("tc_1", "search", { query: "test" });
const messages: ChatMessage[] = [
createUserMessage("What's in the codebase?"),
createAssistantMessage("Let me search for you.", [toolCall]),
createToolMessage("Search results here", "tc_1"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(2);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(messages).toHaveLength(1); // User message should remain
expect(messages[0].role).toBe("user");
});
test("extractToolSequence should throw error when tool message has no matching tool call", () => {
const toolCall = createToolCall("tc_1", "read_file", { path: "test.txt" });
const messages: ChatMessage[] = [
createAssistantMessage("I'll read the file for you.", [toolCall]),
createToolMessage("File contents here", "tc_2"), // Wrong tool call ID
];
expect(() => extractToolSequence(messages)).toThrow(
'Error parsing chat history: no tool call found to match tool output for id "tc_2"',
);
});
test("extractToolSequence should throw error when last message is not user or tool", () => {
const messages: ChatMessage[] = [
createUserMessage("Hello"),
createAssistantMessage("Hi there!"),
];
expect(() => extractToolSequence(messages)).toThrow(
"Error parsing chat history: no user/tool message found",
);
});
test("extractToolSequence should throw error when messages array is empty", () => {
const messages: ChatMessage[] = [];
expect(() => extractToolSequence(messages)).toThrow(
"Error parsing chat history: no user/tool message found",
);
});
test("extractToolSequence should handle tool sequence without assistant message", () => {
const messages: ChatMessage[] = [
createToolMessage("Orphaned tool message", "tc_1"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(1);
expect(sequence[0].role).toBe("tool");
expect(sequence[0].toolCallId).toBe("tc_1");
expect(messages).toHaveLength(0);
});
test("extractToolSequence should handle complex tool sequence with multiple tool calls", () => {
const toolCall1 = createToolCall("tc_1", "read_file", {
path: "file1.txt",
});
const toolCall2 = createToolCall("tc_2", "read_file", {
path: "file2.txt",
});
const toolCall3 = createToolCall("tc_3", "write_file", {
path: "output.txt",
content: "merged",
});
const messages: ChatMessage[] = [
createUserMessage("Merge these files"),
createAssistantMessage("I'll read both files and merge them.", [
toolCall1,
toolCall2,
toolCall3,
]),
createToolMessage("Contents of file1", "tc_1"),
createToolMessage("Contents of file2", "tc_2"),
createToolMessage("Files merged successfully", "tc_3"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(4);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(sequence[1].toolCallId).toBe("tc_1");
expect(sequence[2].role).toBe("tool");
expect(sequence[2].toolCallId).toBe("tc_2");
expect(sequence[3].role).toBe("tool");
expect(sequence[3].toolCallId).toBe("tc_3");
expect(messages).toHaveLength(1); // User message should remain
});
});

View file

@ -1,22 +1,24 @@
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
import { renderChatMessage } from "../util/messageContent.js";
import {
AsyncEncoder,
GPTAsyncEncoder,
LlamaAsyncEncoder,
} from "./asyncEncoder.js";
ChatMessage,
CompiledMessagesResult,
MessageContent,
MessagePart,
PruningStatus,
Tool,
} from "../index.js";
import { autodetectTemplateType } from "./autodetect.js";
import llamaTokenizer from "./llamaTokenizer.js";
import {
addSpaceToAnyEmptyMessages,
chatMessageIsEmpty,
flattenMessages,
isUserOrToolMsg,
messageHasToolCallId,
} from "./messages.js";
import { renderChatMessage } from "../util/messageContent.js";
import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
import llamaTokenizer from "./llamaTokenizer.js";
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
@ -47,7 +49,6 @@ class NonWorkerAsyncEncoder implements AsyncEncoder {
}
let gptEncoding: Encoding | null = null;
const gptAsyncEncoder = new GPTAsyncEncoder();
const llamaEncoding = new LlamaEncoding();
const llamaAsyncEncoder = new LlamaAsyncEncoder();
@ -213,6 +214,59 @@ function countChatMessageTokens(
return tokens;
}
/**
* Extracts and validates the tool call sequence from the end of a message array.
* Tool sequences consist of: [assistant_with_tool_calls, tool_response_1, tool_response_2, ...]
* or just a single user message.
*
* @param messages - Array of chat messages (will be modified by popping messages)
* @returns Array of messages that form the tool sequence
*/
function extractToolSequence(messages: ChatMessage[]): ChatMessage[] {
const lastMsg = messages.pop();
if (!lastMsg || !isUserOrToolMsg(lastMsg)) {
throw new Error("Error parsing chat history: no user/tool message found");
}
const toolSequence: ChatMessage[] = [];
if (lastMsg.role === "tool") {
toolSequence.push(lastMsg);
// Collect all consecutive tool messages from the end
while (
messages.length > 0 &&
messages[messages.length - 1].role === "tool"
) {
toolSequence.unshift(messages.pop()!);
}
// Get the assistant message with tool calls
const assistantMsg = messages.pop();
if (assistantMsg) {
toolSequence.unshift(assistantMsg);
// Validate that all tool messages have matching tool call IDs
for (const toolMsg of toolSequence.slice(1)) {
// Skip assistant message
if (
toolMsg.role === "tool" &&
!messageHasToolCallId(assistantMsg, toolMsg.toolCallId)
) {
throw new Error(
`Error parsing chat history: no tool call found to match tool output for id "${toolMsg.toolCallId}"`,
);
}
}
}
} else {
// Single user message
toolSequence.push(lastMsg);
}
return toolSequence;
}
function pruneLinesFromTop(
prompt: string,
maxTokens: number,
@ -326,13 +380,36 @@ function pruneRawPromptFromTop(
return pruneStringFromTop(modelName, maxTokens, prompt);
}
/*
Goal: reconcile chat messages with available context length
Guidelines:
- Always keep last user message, system message, and tools
- Never allow tool output without the corresponding tool call
- Remove older messages first
*/
/**
* Reconciles chat messages with available context length by intelligently pruning older messages
* while preserving critical conversation elements.
*
* Core Guidelines:
* - Always preserve the last user/tool message sequence (including any associated assistant message with tool calls)
* - Always preserve the system message and tools
* - Never allow orphaned tool responses without their corresponding tool calls
* - Remove older messages first when pruning is necessary
* - Maintain conversation coherence by flattening adjacent similar messages
*
* Process:
* 1. Handle image content conversion for models that don't support images
* 2. Extract and preserve system message
* 3. Filter out empty messages and trailing non-user/tool messages
* 4. Extract the complete tool sequence from the end (user message or assistant + tool responses)
* 5. Calculate token requirements for non-negotiable elements (system, tools, last sequence)
* 6. Prune older messages until within available token budget
* 7. Reassemble with proper ordering and flatten adjacent similar messages
*
* @param params - Configuration object containing:
* - modelName: LLM model name for token counting
* - msgs: Array of chat messages to process
* - contextLength: Maximum context length supported by the model
* - maxTokens: Maximum tokens to reserve for the response
* - supportsImages: Whether the model supports image content
* - tools: Optional array of available tools
* @returns Processed array of chat messages that fit within context constraints
* @throws Error if non-negotiable elements exceed available context
*/
function compileChatMessages({
modelName,
msgs,
@ -347,7 +424,7 @@ function compileChatMessages({
maxTokens: number;
supportsImages: boolean;
tools?: Tool[];
}): ChatMessage[] {
}): CompiledMessagesResult {
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
// If images not supported, convert MessagePart[] to string
@ -376,25 +453,14 @@ function compileChatMessages({
msgsCopy.pop();
}
const lastUserOrToolMsg = msgsCopy.pop();
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
}
// // Extract the tool sequence from the end of the message array
// const toolSequence = extractToolSequence(msgsCopy);
let lastToolCallsMsg: ChatMessage | undefined = undefined;
if (lastUserOrToolMsg.role === "tool") {
lastToolCallsMsg = msgsCopy.pop();
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
throw new Error(
`Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`,
);
}
}
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
if (lastToolCallsMsg) {
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
}
// // Count tokens for all messages in the tool sequence
// let lastMessagesTokens = 0;
// for (const msg of toolSequence) {
// lastMessagesTokens += countChatMessageTokens(modelName, msg);
// }
// System message
let systemMsgTokens = 0;
@ -420,7 +486,7 @@ function compileChatMessages({
// Non-negotiable messages
inputTokensAvailable -= toolTokens;
inputTokensAvailable -= systemMsgTokens;
inputTokensAvailable -= lastMessagesTokens;
// inputTokensAvailable -= lastMessagesTokens;
// Make sure there's enough context for the non-excludable items
if (inputTokensAvailable < 0) {
@ -432,7 +498,6 @@ function compileChatMessages({
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
- max output tokens: ${maxTokens}`,
);
}
@ -448,9 +513,12 @@ function compileChatMessages({
};
});
let pruningStatus: PruningStatus = "not-pruned";
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
pruningStatus = "pruned";
// At this point make sure no latent tool response without corresponding call
while (historyWithTokens[0]?.role === "tool") {
@ -459,26 +527,25 @@ function compileChatMessages({
}
}
if (historyWithTokens.length === 0) {
pruningStatus = "deleted-last-input";
}
// Now reassemble
const reassembled: ChatMessage[] = [];
if (systemMsg) {
reassembled.push(systemMsg);
}
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
if (lastToolCallsMsg) {
reassembled.push(lastToolCallsMsg);
}
reassembled.push(lastUserOrToolMsg);
// Flatten the messages (combines adjacent similar messages)
const flattenedHistory = flattenMessages(reassembled);
return flattenedHistory;
return { compiledChatMessages: reassembled, pruningStatus };
}
export {
compileChatMessages,
countTokens,
countTokensAsync,
extractToolSequence,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,

View file

@ -20,6 +20,7 @@ import {
ILLMLogger,
LLMFullCompletionOptions,
LLMOptions,
MessageOption,
ModelCapability,
ModelInstaller,
PromptLog,
@ -867,6 +868,23 @@ export abstract class BaseLLM implements ILLM {
return { role: "assistant" as const, content: completion };
}
compileChatMessages(
message: ChatMessage[],
options: LLMFullCompletionOptions,
) {
let { completionOptions } = this._parseCompletionOptions(options);
completionOptions = this._modifyCompletionOptions(completionOptions);
return compileChatMessages({
modelName: completionOptions.model,
msgs: message,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
}
protected modifyChatBody(
body: ChatCompletionCreateParams,
): ChatCompletionCreateParams {
@ -891,6 +909,7 @@ export abstract class BaseLLM implements ILLM {
_messages: ChatMessage[],
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
@ -901,14 +920,21 @@ export abstract class BaseLLM implements ILLM {
completionOptions = this._modifyCompletionOptions(completionOptions);
const messages = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
let messages = _messages;
// If not precompiled, compile the chat messages
if (!messageOptions || messageOptions.precompiled === false) {
const { compiledChatMessages } = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
messages = compiledChatMessages;
}
const prompt = this.templateMessages
? this.templateMessages(messages)

View file

@ -11,18 +11,14 @@ import {
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import type { CompletionOptions } from "../../index.js";
import { ChatMessage, Chunk, LLMOptions, MessageContent } from "../../index.js";
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
import { getSecureID } from "../utils/getSecureID.js";
import { withLLMRetry } from "../utils/retry.js";
interface ModelConfig {
formatPayload: (text: string) => any;
@ -89,6 +85,7 @@ class Bedrock extends BaseLLM {
}
}
@withLLMRetry()
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
@ -132,16 +129,9 @@ class Bedrock extends BaseLLM {
});
const command = new ConverseStreamCommand(input);
let response: ConverseStreamCommandOutput;
try {
response = (await client.send(command, {
abortSignal: signal,
})) as ConverseStreamCommandOutput;
} catch (error: unknown) {
console.error(error);
const message = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
}
const response = (await client.send(command, {
abortSignal: signal,
})) as ConverseStreamCommandOutput;
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
@ -259,19 +249,9 @@ class Bedrock extends BaseLLM {
}
}
} catch (error: unknown) {
// Clean up state and let the original error bubble up to the retry decorator
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
}
throw new Error(
"Error processing Bedrock stream: Unknown error occurred",
);
throw error;
}
}

View file

@ -11,6 +11,7 @@ import OpenAI from "../OpenAI.js";
import type { Chunk, LLMOptions } from "../../../index.js";
import { LLMConfigurationStatuses } from "../../constants.js";
import { LlmApiRequestType } from "../../openaiTypeConverters.js";
class ContinueProxy extends OpenAI {
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
@ -23,6 +24,8 @@ class ContinueProxy extends OpenAI {
}
}
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
// The apiKey and apiBase are set to the values for the proxy,
// but we need to keep track of the actual values that the proxy will use
// to call whatever LLM API is chosen

View file

@ -1,104 +0,0 @@
import { ChatMessage } from "..";
import { flattenMessages } from "./messages";
describe("flattenMessages", () => {
it("should return an empty array when given an empty array", () => {
expect(flattenMessages([])).toEqual([]);
});
it("should return the same array when there is only one message", () => {
const messages: ChatMessage[] = [{ role: "user", content: "Hello" }];
expect(flattenMessages(messages)).toEqual(messages);
});
it("should return the same array when messages have different roles", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
{ role: "user", content: "How are you?" },
];
expect(flattenMessages(messages)).toEqual(messages);
});
it("should combine consecutive messages with the same role", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "user", content: "How are you?" },
{ role: "assistant", content: "I am an AI assistant." },
{ role: "assistant", content: "How can I help you?" },
];
const expected: ChatMessage[] = [
{ role: "user", content: "Hello\n\nHow are you?" },
{
role: "assistant",
content: "I am an AI assistant.\n\nHow can I help you?",
},
];
expect(flattenMessages(messages)).toEqual(expected);
});
it("should handle messages with undefined or empty content", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "user", content: "" },
{ role: "assistant", content: "" },
{ role: "assistant", content: "Sure, I can help with that." },
];
const expected: ChatMessage[] = [
{ role: "user", content: "Hello\n\n" },
{ role: "assistant", content: "\n\nSure, I can help with that." },
];
expect(flattenMessages(messages)).toEqual(expected);
});
it("should not combine non-consecutive messages with the same role", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Reply to first message" },
{ role: "user", content: "Second message" },
];
expect(flattenMessages(messages)).toEqual(messages);
});
it("should handle a mix of message roles and contents correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Message one" },
{ role: "user", content: "Message two" },
{ role: "assistant", content: "Reply one" },
{ role: "user", content: "Message three" },
{ role: "user", content: "Message four" },
{ role: "assistant", content: "Reply two" },
];
const expected: ChatMessage[] = [
{ role: "user", content: "Message one\n\nMessage two" },
{ role: "assistant", content: "Reply one" },
{ role: "user", content: "Message three\n\nMessage four" },
{ role: "assistant", content: "Reply two" },
];
expect(flattenMessages(messages)).toEqual(expected);
});
it("should not combine adjacent assistant messages when one of them is a tool call", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "What's the capital of France?" },
{ role: "assistant", content: "Paris" },
{
role: "assistant",
content: " ",
toolCalls: [
{
id: "test",
type: "function",
function: {
name: "getCapital",
arguments: JSON.stringify({
country: "France",
}),
},
},
],
},
];
expect(flattenMessages(messages).length).toBe(3);
});
});

View file

@ -4,27 +4,6 @@ export function messageHasToolCalls(msg: ChatMessage): boolean {
return msg.role === "assistant" && !!msg.toolCalls;
}
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role &&
!messageHasToolCalls(msg) &&
!messageHasToolCalls(flattened[flattened.length - 1])
) {
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
}
}
return flattened;
}
export function messageIsEmpty(message: ChatMessage): boolean {
if (typeof message.content === "string") {
return message.content.trim() === "";

View file

@ -24,7 +24,12 @@ export async function* llmStreamChat(
void TTS.kill();
}
const { legacySlashCommandData, completionOptions, messages } = msg.data;
const {
legacySlashCommandData,
completionOptions,
messages,
messageOptions,
} = msg.data;
const model = config.selectedModelByRole.chat;
@ -117,6 +122,7 @@ export async function* llmStreamChat(
messages,
abortController.signal,
completionOptions,
messageOptions,
);
let next = await gen.next();
while (!next.done) {

View file

@ -1,4 +1,4 @@
import { getSecureID } from "../getSecureID";
import { getSecureID } from "./getSecureID";
// Mock the crypto.randomUUID function
const mockRandomUUID = jest.fn();

View file

@ -0,0 +1,481 @@
import { retryAsync, withLLMRetry, withRetry } from "./retry";
// Mock console.warn to avoid noise in tests
const consoleSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
describe("Retry Functionality", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("retryAsync", () => {
it("should succeed on first attempt", async () => {
const mockFn = jest.fn().mockResolvedValue("success");
const result = await retryAsync(mockFn);
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(1);
});
it("should retry on retryable errors", async () => {
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10, // Very short delay for testing
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should not retry on non-retryable errors", async () => {
const error = new Error("Bad Request");
(error as any).status = 400;
const mockFn = jest.fn().mockRejectedValue(error);
await expect(retryAsync(mockFn)).rejects.toThrow("Bad Request");
expect(mockFn).toHaveBeenCalledTimes(1);
});
it("should respect max attempts", async () => {
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(
retryAsync(mockFn, {
maxAttempts: 3,
baseDelay: 10,
}),
).rejects.toThrow("ECONNRESET");
expect(mockFn).toHaveBeenCalledTimes(3);
});
it("should throw the last error when all retries are exhausted", async () => {
const firstError = new Error("First error");
(firstError as any).code = "ECONNRESET";
const secondError = new Error("Second error");
(secondError as any).code = "ECONNRESET";
const lastError = new Error("Last error");
(lastError as any).code = "ECONNRESET";
const mockFn = jest
.fn()
.mockRejectedValueOnce(firstError)
.mockRejectedValueOnce(secondError)
.mockRejectedValueOnce(lastError);
await expect(
retryAsync(mockFn, {
maxAttempts: 3,
baseDelay: 10,
}),
).rejects.toThrow("Last error");
expect(mockFn).toHaveBeenCalledTimes(3);
});
it("should handle HTTP 429 errors", async () => {
const error = new Error("Too Many Requests");
(error as any).status = 429;
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10,
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should handle HTTP 5xx errors", async () => {
const error = new Error("Internal Server Error");
(error as any).status = 500;
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10,
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should handle AWS SDK errors", async () => {
const error = new Error("Throttling");
error.name = "ThrottlingException";
(error as any).$fault = "client";
(error as any).$metadata = {
httpStatusCode: 429,
requestId: "test-request-id",
};
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10,
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should not retry AbortError", async () => {
const error = new Error("Aborted");
error.name = "AbortError";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(retryAsync(mockFn)).rejects.toThrow("Aborted");
expect(mockFn).toHaveBeenCalledTimes(1);
});
it("should use custom shouldRetry function", async () => {
const mockFn = jest.fn().mockRejectedValue(new Error("Custom Error"));
const customShouldRetry = jest.fn().mockReturnValue(true);
await expect(
retryAsync(mockFn, {
maxAttempts: 2,
shouldRetry: customShouldRetry,
baseDelay: 10,
}),
).rejects.toThrow("Custom Error");
expect(customShouldRetry).toHaveBeenCalledWith(expect.any(Error), 1);
expect(mockFn).toHaveBeenCalledTimes(2);
});
});
describe("withRetry decorator functional usage", () => {
it("should work when applied manually to methods", async () => {
const testClass = {
attempts: 0,
async testMethod(): Promise<string> {
this.attempts++;
if (this.attempts < 3) {
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
throw error;
}
return "success";
},
};
// Apply decorator manually
const decorator = withRetry({
maxAttempts: 3,
baseDelay: 10,
});
const descriptor = decorator(testClass, "testMethod", {
value: testClass.testMethod,
writable: true,
enumerable: false,
configurable: true,
});
if (descriptor?.value) {
testClass.testMethod = descriptor.value;
}
const result = await testClass.testMethod();
expect(result).toBe("success");
expect(testClass.attempts).toBe(3);
});
it("should throw the last error when all retries are exhausted", async () => {
const testClass = {
attempts: 0,
async testMethod(): Promise<string> {
this.attempts++;
if (this.attempts === 1) {
const error = new Error("First decorator error");
(error as any).code = "ECONNRESET";
throw error;
} else if (this.attempts === 2) {
const error = new Error("Second decorator error");
(error as any).code = "ECONNRESET";
throw error;
} else {
const error = new Error("Last decorator error");
(error as any).code = "ECONNRESET";
throw error;
}
},
};
// Apply decorator manually
const decorator = withRetry({
maxAttempts: 3,
baseDelay: 10,
});
const descriptor = decorator(testClass, "testMethod", {
value: testClass.testMethod,
writable: true,
enumerable: false,
configurable: true,
});
if (descriptor?.value) {
testClass.testMethod = descriptor.value;
}
await expect(testClass.testMethod()).rejects.toThrow(
"Last decorator error",
);
expect(testClass.attempts).toBe(3);
});
});
describe("withLLMRetry decorator functional usage", () => {
it("should use LLM-specific defaults", async () => {
const testLLM = {
attempts: 0,
async streamChat(): Promise<string> {
this.attempts++;
if (this.attempts < 2) {
const error = new Error("Too Many Requests");
(error as any).status = 429;
throw error;
}
return "success";
},
};
// Apply decorator manually
const decorator = withLLMRetry({ baseDelay: 10 });
const descriptor = decorator(testLLM, "streamChat", {
value: testLLM.streamChat,
writable: true,
enumerable: false,
configurable: true,
});
if (descriptor?.value) {
testLLM.streamChat = descriptor.value;
}
const result = await testLLM.streamChat();
expect(result).toBe("success");
expect(testLLM.attempts).toBe(2);
});
});
describe("exponential backoff with jitter", () => {
it("should increase delay exponentially", async () => {
const delays: number[] = [];
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(
retryAsync(mockFn, {
maxAttempts: 3,
baseDelay: 1000,
jitterFactor: 0, // No jitter for predictable testing
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
}),
).rejects.toThrow();
// First retry should be ~1000ms, second should be ~2000ms
expect(delays).toHaveLength(2);
expect(delays[0]).toBe(1000);
expect(delays[1]).toBe(2000);
});
it("should respect maxDelay", async () => {
const delays: number[] = [];
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(
retryAsync(mockFn, {
maxAttempts: 4,
baseDelay: 1000,
maxDelay: 2500,
jitterFactor: 0,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
}),
).rejects.toThrow();
// Delays should be: 1000, 2000, 2500 (capped)
expect(delays).toEqual([1000, 2000, 2500]);
});
});
describe("rate limiting headers", () => {
it("should respect retry-after header in seconds", async () => {
const delays: number[] = [];
const error = new Error("Too Many Requests");
(error as any).status = 429;
(error as any).headers = { "retry-after": "1" }; // 1 second for fast testing
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100, // 100ms fallback
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
// Should use header value (1000ms) not exponential backoff (100ms)
expect(delays[0]).toBeGreaterThan(940); // 1000ms with wider tolerance for jitter and system performance
expect(delays[0]).toBeLessThan(1080);
});
it("should respect x-ratelimit-reset header", async () => {
const delays: number[] = [];
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "x-ratelimit-reset": "0.5" }; // 500ms for fast testing
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should use header value (500ms) not exponential backoff (100ms)
expect(delays[0]).toBeGreaterThan(470); // 500ms with wider tolerance for jitter and system performance
expect(delays[0]).toBeLessThan(540);
});
it("should handle HTTP date format in retry-after header", async () => {
const delays: number[] = [];
const futureDate = new Date(Date.now() + 2000); // 2 seconds from now to avoid timing issues
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "retry-after": futureDate.toUTCString() };
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
maxDelay: 300, // Cap at 300ms for fast testing
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should be capped at maxDelay (300ms) since original would be ~2000ms
expect(delays[0]).toBeGreaterThan(280);
expect(delays[0]).toBeLessThan(320);
});
it("should fallback to exponential backoff when no headers present", async () => {
const delays: number[] = [];
const error = new Error("Server Error");
(error as any).status = 500;
// No headers property
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 50, // Fast for testing
jitterFactor: 0,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should use exponential backoff (50ms) since no headers
expect(delays[0]).toBe(50);
});
it("should respect maxDelay even with rate limit headers", async () => {
const delays: number[] = [];
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "retry-after": "10" }; // 10 seconds requested
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
maxDelay: 200, // Cap at 200ms for fast testing
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should be capped at maxDelay (200ms) not header value (10000ms)
expect(delays[0]).toBeGreaterThan(190);
expect(delays[0]).toBeLessThan(210);
});
it("should handle case-insensitive header names", async () => {
const delays: number[] = [];
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "Retry-After": "0.3" }; // 300ms for fast testing
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should use header value (300ms)
expect(delays[0]).toBeGreaterThan(284);
expect(delays[0]).toBeLessThan(316);
});
});
});

459
core/llm/utils/retry.ts Normal file
View file

@ -0,0 +1,459 @@
/**
* Configuration options for the retry decorator
*/
export interface RetryOptions {
/** Maximum number of retry attempts (default: 3) */
maxAttempts?: number;
/** Base delay in milliseconds (default: 1000) */
baseDelay?: number;
/** Maximum delay in milliseconds (default: 30000) */
maxDelay?: number;
/** Jitter factor between 0 and 1 (default: 0.3) */
jitterFactor?: number;
/** Custom function to determine if an error should be retried */
shouldRetry?: (error: any, attempt: number) => boolean;
/** Custom function called on each retry attempt */
onRetry?: (error: any, attempt: number, delay: number) => void;
}
/**
* Default configuration for retry behavior
*/
const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
maxAttempts: 3,
baseDelay: 1000,
maxDelay: 30000,
jitterFactor: 0.3,
shouldRetry: defaultShouldRetry,
onRetry: defaultOnRetry,
};
/**
* Default function to determine if an error should be retried
* Retries on:
* - Network errors
* - HTTP 429 (Too Many Requests)
* - HTTP 5xx (Server errors)
* - Specific AWS errors
* - Timeout errors
*/
function defaultShouldRetry(error: any, attempt: number): boolean {
// Note: maxAttempts check is handled by the retry logic itself
// This function only determines if the error type is retryable
// Network/connection errors
if (
error.code === "ENOTFOUND" ||
error.code === "ECONNRESET" ||
error.code === "ECONNREFUSED" ||
error.code === "ETIMEDOUT"
) {
return true;
}
// AWS SDK specific errors (v3 - check for AWS error structure and retryable types)
const isAwsError =
error.$fault || error.$metadata || (error.name && error.__type);
const awsRetryableErrors = [
"ThrottlingException",
"ServiceUnavailableException",
"InternalServerError",
"RequestTimeout",
"ModelNotReadyException",
"ModelTimeoutException",
"ResourceNotFoundException",
];
if (isAwsError && error.name && awsRetryableErrors.includes(error.name)) {
return true;
}
// HTTP status codes
if (error.status || error.statusCode) {
const status = error.status || error.statusCode;
// Rate limiting
if (status === 429) {
return true;
}
// Server errors (5xx)
if (status >= 500 && status < 600) {
return true;
}
// Don't retry client errors (4xx except 429)
if (status >= 400 && status < 500) {
return false;
}
}
// Timeout errors
if (
error.name === "TimeoutError" ||
error.message?.includes("timeout") ||
error.message?.includes("TIMEOUT")
) {
return true;
}
// Abort signal errors should not be retried
if (error.name === "AbortError" || error.code === "ABORT_ERR") {
return false;
}
// Default to not retrying unknown errors
return false;
}
/**
* Default function called on each retry attempt
*/
function defaultOnRetry(error: any, attempt: number, delay: number): void {
console.warn(
`Retry attempt ${attempt} after ${delay}ms delay. Error: ${error.message || error}`,
);
}
/**
* Calculate delay with rate limit header awareness and exponential backoff fallback
*/
function calculateDelay(
attempt: number,
baseDelay: number,
maxDelay: number,
jitterFactor: number,
error?: any,
): number {
// Check for rate limiting headers first (more accurate than exponential backoff)
if (error?.headers) {
const retryAfter =
error.headers["retry-after"] ||
error.headers["x-ratelimit-reset"] ||
error.headers["ratelimit-reset"] ||
error.headers["Retry-After"] ||
error.headers["X-RateLimit-Reset"] ||
error.headers["RateLimit-Reset"];
if (retryAfter) {
let delayMs: number;
// Parse retry-after header (can be seconds or HTTP date)
if (typeof retryAfter === "string" && isNaN(Number(retryAfter))) {
// HTTP date format
const resetTime = new Date(retryAfter).getTime();
const now = Date.now();
delayMs = Math.max(0, resetTime - now);
} else {
// Seconds format
delayMs = Number(retryAfter) * 1000;
}
// Respect maxDelay and add small jitter to spread requests
const cappedDelay = Math.min(delayMs, maxDelay);
const jitterMultiplier = 1 + (Math.random() * 0.1 - 0.05); // Small jitter ±5%
return Math.max(0, Math.floor(cappedDelay * jitterMultiplier));
}
}
// Fallback to exponential backoff if no rate limit headers
const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
const cappedDelay = Math.min(exponentialDelay, maxDelay);
// Add jitter: random value between (1 - jitterFactor) and (1 + jitterFactor)
const jitterMultiplier = 1 + (Math.random() * 2 - 1) * jitterFactor;
const jitteredDelay = cappedDelay * jitterMultiplier;
return Math.max(0, Math.floor(jitteredDelay));
}
/**
* Sleep for the specified number of milliseconds
*/
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Retry decorator for async functions with exponential backoff and jitter
*
* @param options Retry configuration options
* @returns Decorator function
*
* @example
* ```typescript
* class MyLLM {
* @withRetry({ maxAttempts: 5, baseDelay: 2000 })
* async streamChat(messages: ChatMessage[]): Promise<AsyncGenerator<ChatMessage>> {
* // Implementation that might fail
* }
* }
* ```
*/
export function withRetry(options: RetryOptions = {}) {
const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
return function (...args: any[]): any {
// Handle different decorator calling patterns
const [target, propertyName, descriptor] = args;
// Get the original method
let originalMethod: Function;
if (descriptor && descriptor.value) {
originalMethod = descriptor.value;
} else {
// Get method from prototype
originalMethod = target[propertyName];
}
if (!originalMethod || typeof originalMethod !== "function") {
throw new Error(`@withRetry can only be applied to methods`);
}
// Check if the original method is an async generator function
const isAsyncGenerator =
originalMethod.constructor.name === "AsyncGeneratorFunction";
const wrappedMethod = isAsyncGenerator
? async function* (this: any, ...methodArgs: any[]) {
let lastError: any;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
const generator = originalMethod.apply(this, methodArgs);
yield* createRetryableAsyncGenerator(
generator,
config,
originalMethod,
this,
methodArgs,
attempt,
);
return; // Successfully completed
} catch (error) {
lastError = error;
// Check if we should retry this error
if (!config.shouldRetry(error, attempt)) {
throw error;
}
// Don't delay on the last attempt
if (attempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
attempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, attempt, delay);
await sleep(delay);
}
}
// If we get here, all attempts failed
throw lastError;
}
: async function (this: any, ...methodArgs: any[]) {
let lastError: any;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
const result = originalMethod.apply(this, methodArgs);
return await result;
} catch (error) {
lastError = error;
// Check if we should retry this error
if (!config.shouldRetry(error, attempt)) {
throw error;
}
// Don't delay on the last attempt
if (attempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
attempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, attempt, delay);
await sleep(delay);
}
}
// If we get here, all attempts failed
throw lastError;
};
// Apply the wrapped method based on how the decorator was called
if (descriptor) {
descriptor.value = wrappedMethod;
return descriptor;
} else {
// Handle case where descriptor is not provided
target[propertyName] = wrappedMethod;
return wrappedMethod;
}
};
}
/**
* Creates a retryable async generator that handles errors during iteration
*/
async function* createRetryableAsyncGenerator<T>(
generator: AsyncGenerator<T>,
config: Required<RetryOptions>,
originalMethod: Function,
context: any,
args: any[],
initialAttempt: number,
): AsyncGenerator<T> {
let currentGenerator = generator;
let attempt = initialAttempt;
try {
for await (const value of currentGenerator) {
yield value;
}
} catch (error) {
// If we encounter an error during iteration, we can retry by creating a new generator
let lastError = error;
for (
let retryAttempt = attempt + 1;
retryAttempt <= config.maxAttempts;
retryAttempt++
) {
// Check if we should retry this error
if (!config.shouldRetry(error, retryAttempt)) {
throw error;
}
// Don't delay on the last attempt
if (retryAttempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
retryAttempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, retryAttempt, delay);
await sleep(delay);
try {
// Create a new generator and continue iteration
const newGenerator = await originalMethod.apply(context, args);
if (
newGenerator &&
typeof newGenerator[Symbol.asyncIterator] === "function"
) {
for await (const value of newGenerator) {
yield value;
}
return; // Successfully completed
} else {
throw new Error("Method did not return an async generator on retry");
}
} catch (retryError) {
lastError = retryError;
error = retryError;
}
}
// If we get here, all retry attempts failed
throw lastError;
}
}
/**
* Functional version of retry for use without decorators
*
* @param fn Function to retry
* @param options Retry configuration options
* @returns Promise that resolves with the function result or rejects with the last error
*
* @example
* ```typescript
* const result = await retryAsync(
* () => someApiCall(),
* { maxAttempts: 3, baseDelay: 1000 }
* );
* ```
*/
export async function retryAsync<T>(
fn: () => Promise<T>,
options: RetryOptions = {},
): Promise<T> {
const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
let lastError: any;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
// Check if we should retry this error
if (!config.shouldRetry(error, attempt)) {
throw error;
}
// Don't delay on the last attempt
if (attempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
attempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, attempt, delay);
await sleep(delay);
}
}
// If we get here, all attempts failed
throw lastError;
}
/**
* Retry decorator specifically configured for LLM providers
* Uses sensible defaults for LLM API calls, including longer delays
* for capacity provisioning (e.g., AWS Bedrock can require up to 59+ seconds)
*/
export function withLLMRetry(options: Partial<RetryOptions> = {}) {
return withRetry({
maxAttempts: 5, // More attempts for capacity issues
baseDelay: 2000, // Start with 2 seconds
maxDelay: 90000, // Allow up to 90 seconds for capacity provisioning
jitterFactor: 0.4, // Slightly more jitter to spread load
...options,
});
}

View file

@ -158,19 +158,19 @@ export class NextEditProvider {
this.loggingService.cancel();
}
// public accept(completionId: string) {
// const outcome = this.loggingService.accept(completionId);
// if (!outcome) {
// return;
// }
// }
public accept(completionId: string) {
const outcome = this.loggingService.accept(completionId);
if (!outcome) {
return;
}
}
// public reject(completionId: string) {
// const outcome = this.loggingService.reject(completionId);
// if (!outcome) {
// return;
// }
// }
public reject(completionId: string) {
const outcome = this.loggingService.reject(completionId);
if (!outcome) {
return;
}
}
public markDisplayed(completionId: string, outcome: NextEditOutcome) {
this.loggingService.markDisplayed(completionId, outcome);
@ -237,7 +237,6 @@ export class NextEditProvider {
// TODO: Toggle between the default endpoint and the finetuned endpoint.
const prompts: Prompt[] = [];
if (this.endpointType === "default") {
prompts.push(renderDefaultSystemPrompt());
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
@ -272,17 +271,30 @@ export class NextEditProvider {
cursorPosition: helper.pos,
...helper.options,
};
// When using the JetBrains extension, mark as displayed.
// This helps us not need to make additional network calls just to mark as displayed.
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcomeNext);
}
return outcomeNext;
} else {
return undefined;
}
} else {
const msg: ChatMessage = await llm.chat(prompts, token);
if (typeof msg.content === "string") {
// TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
const nextCompletion = replaceEscapedCharacters(
msg.content.split("<|editable_region_start|>\n")[1],
).replace(/\n$/, "");
// NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
const nextCompletion = msg.content.split(
"<|editable_region_start|>\n",
)[1]
? replaceEscapedCharacters(
msg.content.split("<|editable_region_start|>\n")[1],
).replace(/\n$/, "")
: "";
const currCursorPos = helper.pos;
const editableRegionStartLine = Math.max(
@ -319,6 +331,14 @@ export class NextEditProvider {
cursorPosition: helper.pos,
...helper.options,
};
// When using the JetBrains extension, mark as displayed.
// This helps us not need to make additional network calls just to mark as displayed.
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcomeNext);
}
return outcomeNext;
} else {
return undefined;

View file

@ -1,5 +1,5 @@
export const IS_NEXT_EDIT_ACTIVE = false;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";

14
core/package-lock.json generated
View file

@ -51,7 +51,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.76.0",
"openai": "^4.104.0",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
@ -180,7 +180,7 @@
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.76.0",
"openai": "^4.104.0",
"uuid": "^11.1.0",
"zod": "^3.24.2"
},
@ -14329,9 +14329,9 @@
}
},
"node_modules/openai": {
"version": "4.76.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.76.0.tgz",
"integrity": "sha512-QBGIetjX1C9xDp5XGa/3mPnfKI9BgAe2xHQX6PmO98wuW9qQaurBaumcYptQWc9LHZZq7cH/Y1Rjnsr6uUDdVw==",
"version": "4.104.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.104.0.tgz",
"integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
@ -14345,9 +14345,13 @@
"openai": "bin/cli"
},
"peerDependencies": {
"ws": "^8.18.0",
"zod": "^3.23.8"
},
"peerDependenciesMeta": {
"ws": {
"optional": true
},
"zod": {
"optional": true
}

View file

@ -78,6 +78,7 @@
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
@ -91,7 +92,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.76.0",
"openai": "^4.104.0",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",

View file

@ -15,6 +15,7 @@ import { GlobalContextModelSelections } from "../util/GlobalContext";
import {
BrowserSerializedContinueConfig,
ChatMessage,
CompiledMessagesResult,
CompleteOnboardingPayload,
ContextItem,
ContextItemWithId,
@ -25,6 +26,7 @@ import {
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
MessageOption,
ModelDescription,
PromptLog,
RangeInFile,
@ -145,6 +147,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"context/indexDocs": [{ reIndex: boolean }, void];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"nextEdit/predict": [AutocompleteInput, string[]];
"nextEdit/reject": [{ completionId: string }, void];
"nextEdit/accept": [{ completionId: string }, void];
"llm/complete": [
{
prompt: string;
@ -159,6 +164,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
messages: ChatMessage[];
completionOptions: LLMFullCompletionOptions;
title: string;
messageOptions?: MessageOption;
legacySlashCommandData?: {
command: SlashCommandDescWithSource;
input: string;
@ -170,6 +176,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
AsyncGenerator<ChatMessage, PromptLog>,
];
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
"llm/compileChat": [
{ messages: ChatMessage[]; options: LLMFullCompletionOptions },
CompiledMessagesResult,
];
"chatDescriber/describe": [
{
text: string;

View file

@ -37,10 +37,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"nextEdit/predict",
"nextEdit/reject",
"nextEdit/accept",
"tts/kill",
"llm/complete",
"llm/streamChat",
"llm/listModels",
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",

View file

@ -13,6 +13,7 @@ export const ideSettingsPromise = testIde.getIdeSettings();
export const testControlPlaneClient = new ControlPlaneClient(
Promise.resolve(undefined),
ideSettingsPromise,
testIde.getIdeInfo(),
);
export const testConfigHandler = new ConfigHandler(

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
export interface EditToolArgs {
filepath: string;
@ -18,7 +19,7 @@ export const editFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.EditExistingFile,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}`,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "changes"],

View file

@ -4,7 +4,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "LS Tool",
displayTitle: "ls",
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
isCurrently: "listing files and folders in {{{ dirPath }}}",
hasAlready: "listed files and folders in {{{ dirPath }}}",

View file

@ -3,9 +3,13 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface SearchAndReplaceInFileArgs {
filepath: string;
diff: string;
diffs: string[];
}
// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
/**
* This tool is in an experimental state.
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
@ -21,20 +25,22 @@ export const searchAndReplaceInFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description:
"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "diff"],
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description:
"The path of the file to modify, relative to the root of the workspace.",
},
diff: {
type: "string",
description: `One or more SEARCH/REPLACE blocks following this exact format:
diffs: {
type: "array",
items: {
type: "string",
},
description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
------- SEARCH
[exact content to find]
@ -51,16 +57,17 @@ Critical rules:
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
3. Keep SEARCH/REPLACE blocks concise:
3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
4. Keep SEARCH/REPLACE blocks concise:
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
4. Splitting up tool calls:
5. Splitting up tool calls:
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
5. Special operations:
6. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section
@ -78,7 +85,8 @@ Usage:
[new content to replace with]
+++++++ REPLACE
\`\`\`
`,
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
},
},
},

View file

@ -1,5 +1,22 @@
import iconv from "iconv-lite";
import childProcess from "node:child_process";
import util from "node:util";
// Automatically decode the buffer according to the platform to avoid garbled Chinese
function getDecodedOutput(data: Buffer): string {
if (process.platform === "win32") {
try {
let out = iconv.decode(data, "utf-8");
if (/<2F>/.test(out)) {
out = iconv.decode(data, "gbk");
}
return out;
} catch {
return iconv.decode(data, "gbk");
}
} else {
return data.toString();
}
}
import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
@ -77,7 +94,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = data.toString();
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Send partial output to UI
@ -103,7 +120,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = data.toString();
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Send partial output to UI, status is not required

View file

@ -6,7 +6,7 @@ import { editFileTool } from "./definitions/editFile";
import { fetchUrlContentTool } from "./definitions/fetchUrlContent";
import { globSearchTool } from "./definitions/globSearch";
import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/lsTool";
import { lsTool } from "./definitions/ls";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
import { requestRuleTool } from "./definitions/requestRule";

View file

@ -16,6 +16,8 @@
"noEmit": true,
"jsx": "react-jsx",
"noEmitOnError": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"types": ["jest", "node"]
},
"include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"],

View file

@ -120,6 +120,7 @@ class FileSystemIde implements IDE {
version: "0.1",
remoteName: "na",
extensionVersion: "na",
isPrerelease: false,
});
}

View file

@ -57,41 +57,7 @@ The result will be a generated file called `hn.txt` in the current working direc
You can set up an MCP server to search the Continue documentation directly from your agent. This is particularly useful for getting help with Continue configuration and features.
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"
name: Continue Documentation MCP
version: 0.0.1
schema: v1
mcpServers:
- name: Continue Docs Search
type: stdio
command: npx
args:
- mint-mcp
- add
- continue-docs
```
Now you can search the Continue documentation by asking questions like:
```
Search for model setup instructions in the Continue docs
```
```
Find documentation about context providers
```
```
How do I configure autocomplete in Continue?
```
The MCP server will search the Continue documentation and provide relevant information to help with your questions.
For detailed setup instructions and troubleshooting, see the [Continue MCP Reference](/reference/continue-mcp).
For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp).
## Using MCP Servers

View file

@ -258,7 +258,8 @@
"pages": [
"reference",
"reference/json-reference",
"reference/yaml-migration"
"reference/yaml-migration",
"reference/continue-mcp"
]
}
]

View file

@ -1,14 +1,3 @@
We recommend **Claude 3.5 Sonnet** from Anthropic for the best Agent experience.
The models you set up for Chat mode will be used with Agent mode if the model supports tool calling.
- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
- Get your API key from the [Anthropic console](https://console.anthropic.com/)
## Other recommended models
- [Claude Sonnet 4 from Anthropic](https://hub.continue.dev/anthropic)
- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
- [Gemini 2.0 Pro from Google](https://hub.continue.dev/google/gemini-2.0-pro)
Agent can be used with models that support tool use through Continue. The best chat models generally support tool use.
For more information on models, check out [our recommended chat models](/features/chat/model-setup).
The recommended models and how to set them up can be found [here](/features/chat/model-setup).

View file

@ -2,25 +2,43 @@ Setting up the right model for autocomplete is crucial for a smooth coding exper
## Recommended Models
### Hosted-Based (Best Performance)
### Hosted (Best Performance)
For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral.
**Quick Setup:**
This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
1. [Add Codestral from the hub](https://hub.continue.dev/mistral/codestral)
2. Get your API key from the [Mistral Platform](https://console.mistral.ai/codestral)
3. Configure it in your Continue settings
**Codestral Quick Setup:**
### Local/Offline (Privacy First)
1. Get your API key from [Mistral AI](https://console.mistral.ai)
2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub
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
For a fully local autocomplete experience that doesn't send your code to external servers, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)** running on Ollama. This model provides good suggestions while keeping your code completely private.
### Hosted (Best Speed/Quality Tradeoff)
For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception Labs.
This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
**Mercury Coder Small Quick Setup:**
1. Get your API key from [Inception Labs](https://platform.inceptionlabs.ai/)
2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
3. Add `INCEPTION_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
### Local (Offline / Privacy First)
For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**.
This model provides good suggestions while keeping your code completely private.
**Quick Setup:**
1. Install [Ollama](https://ollama.ai/)
2. [Add Qwen 2.5 Coder from the hub](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)
3. Configure it in your Continue settings
2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub
3. Click `Reload config` in the assistant selector in the Continue IDE extension
## Need Help?

View file

@ -1,19 +1,80 @@
We recommend setting up a model for the best experience.
The model you use for for Chat mode will be
- used with Edit mode by default but can be switched
- always used with Agent mode if the model supports tool calling
## Recommended Models
Here's our primary model recommendation:
Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
**Claude 3.5 Sonnet** from Anthropic
Its strong tool calling and reasoning capabilities make it the best model for Agent mode.
- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
- Get your API key from the [Anthropic console](https://console.anthropic.com/)
1. Get your API key from [Anthropic](https://console.anthropic.com/)
2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub
3. Add `ANTHROPIC_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
Other top models to consider:
#### Other hosted models
- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
- [Grok-2 from xAI](https://hub.continue.dev/xai/grok-2)
- [Gemini 2.0 Flash from Google](https://hub.continue.dev/google/gemini-2.0-flash)
- [Llama 3.1 8b from Meta (local)](https://hub.continue.dev/ollama/llama3.1)
These models have varying tool calling and reasoning capabilities.
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
[Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google
1. Get your API key from [Google AI Studio](https://aistudio.google.com)
2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) to your assistant on Continue Hub
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
[o3](https://hub.continue.dev/openai/o3) from OpenAI
1. Get your API key from [OpenAI](https://platform.openai.com)
2. Add [o3](https://hub.continue.dev/openai/o3) to your assistant on Continue Hub
3. Add `OPENAI_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
[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI
1. Get your API key from [xAI](https://console.x.ai/)
2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to your assistant on Continue Hub
3. Add `XAI_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
[Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) from Mistral AI
1. Get your API key from [Mistral AI](https://console.mistral.ai/)
2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) to your assistant on Continue Hub
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
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
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
#### Local models
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 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
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
[Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) from Google
1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) 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
[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

@ -1,6 +1,6 @@
By default, Edit uses the same model as Chat. We recommend **Claude 3.5 Sonnet** from Anthropic.
The model you set up for Chat mode will be used for Edit mode by default.
[Explore other Edit models on the Continue Hub →](https://hub.continue.dev)
The recommended models and how to set them up can be found [here](/features/chat/model-setup).
## Apply Model
@ -8,7 +8,5 @@ We also recommend setting up an Apply model for the best Edit experience.
**Recommended Apply models:**
- [Morph v0 Fast Apply](https://hub.continue.dev)
- [Relace Instant Apply](https://hub.continue.dev)
[Explore other Apply models on the Continue Hub →](https://hub.continue.dev)
- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View file

@ -4,45 +4,52 @@ description: Set up an MCP server to search Continue documentation
keywords: [mcp, documentation, search, mintlify, reference]
---
# Continue Documentation MCP Server
The Continue Documentation 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-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.
## Installation
### Step 1: Install the MCP Server
Run the following command to install the Continue documentation MCP server:
Run the following command to install the continue-docs MCP server:
```bash
npx mint-mcp add continue-docs
npx mint-mcp add docs.continue.dev
```
This will:
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
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
type: stdio
command: npx
command: node
args:
- mint-mcp
- add
- continue-docs
```
- "/path/to/user/.mcp/docs.continue.dev/src/index.js"
````
### Step 3: Enable Agent Mode

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.28
pluginVersion=1.0.29
# 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,6 +1,7 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction
import com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.intellij.openapi.actionSystem.ActionPromoter
import com.intellij.openapi.actionSystem.AnAction
@ -19,6 +20,13 @@ class ContinueActionPromote : ActionPromoter {
}
}
if (actions.any { it is AcceptNextEditAction }) {
val settings = service<ContinueExtensionSettings>()
if (settings.continueState.showIDECompletionSideBySide) {
return actions.filterIsInstance<AcceptNextEditAction>()
}
}
val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
if (rejectDiffActions.isNotEmpty()) {
return rejectDiffActions

View file

@ -1,5 +1,8 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
@ -37,6 +40,16 @@ class AutocompleteCaretListener : CaretListener {
class AutocompleteDocumentListener(private val editorManager: FileEditorManager, private val editor: Editor) :
DocumentListener {
override fun documentChanged(event: DocumentEvent) {
// Ignore empty changes or changes where content didn't actually change.
if (event.newFragment.isEmpty() && event.oldFragment.isEmpty()) {
return
}
// Make sure this is an actual text modification event.
if (!event.isWholeTextReplaced && event.offset == 0 && event.oldLength == 0 && event.newLength == 0) {
return
}
if (editor != editorManager.selectedTextEditor) {
return
}
@ -46,12 +59,55 @@ class AutocompleteDocumentListener(private val editorManager: FileEditorManager,
return
}
// Invoke later is important, otherwise the completion will be triggered before the document is updated
// causing the old caret offset to be used
// TODO: concurrency
invokeLater {
service.triggerCompletion(editor)
val nextEditService = editor.project?.service<NextEditService>() ?: return
// Check if we're in a test environment based on some property or condition
val isAutocompleteTestEnvironment = System.getProperty("continue.autocomplete.test.environment") == "true"
val isNextEditTestEnvironment = System.getProperty("continue.nextEdit.test.environment") == "true"
if (isAutocompleteTestEnvironment) {
invokeLater {
service.triggerCompletion(editor)
}
return
} else if (isNextEditTestEnvironment) {
invokeLater {
nextEditService.triggerNextEdit(editor)
}
return
}
// Check settings to see if next edit is enabled, and then trigger either autocomplete or next exit.
val continuePluginService = editor.project?.service<ContinuePluginService>()
if (continuePluginService == null) {
return
}
continuePluginService.coreMessenger?.request(
"config/getSerializedProfileInfo",
null,
null,
({ response ->
val optInNextEditFeature = response.castNestedOrNull<Boolean>(
"content",
"result",
"config",
"experimental",
"optInNextEditFeature"
) ?: false
invokeLater {
if (optInNextEditFeature) {
nextEditService.triggerNextEdit(editor)
} else {
// Invoke later is important, otherwise the completion will be triggered before the document is updated
// causing the old caret offset to be used
// TODO: concurrency
service.triggerCompletion(editor)
}
}
})
)
}
}

View file

@ -103,10 +103,14 @@ class MessageTypes {
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"nextEdit/predict",
"nextEdit/reject",
"nextEdit/accept",
"tts/kill",
"llm/complete",
"llm/streamChat",
"llm/listModels",
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",
@ -134,4 +138,4 @@ class MessageTypes {
"process/isBackgrounded",
)
}
}
}

View file

@ -1,3 +1,4 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
@ -86,7 +87,8 @@ class IntelliJIDE(
name = ideName,
version = ideVersion,
remoteName = remoteName,
extensionVersion = extensionVersion
extensionVersion = extensionVersion,
isPrerelease = false // TODO: Implement prerelease detection for JetBrains
)
}
@ -623,4 +625,3 @@ class IntelliJIDE(
}
}

View file

@ -0,0 +1,25 @@
package com.github.continuedev.continueintellijextension.nextEdit
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorAction
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
class AcceptNextEditAction : EditorAction(object : EditorActionHandler() {
override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) {
ApplicationManager.getApplication().runWriteAction {
editor.project?.service<NextEditService>()?.accept()
}
}
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
val nextEditService = editor.project?.service<NextEditService>();
val enabled = editor == nextEditService?.pendingCompletion?.editor
// && caret.offset == autocompleteService.pendingCompletion?.offset
&& nextEditService.pendingCompletion?.text != null
return enabled
}
})

View file

@ -0,0 +1,321 @@
package com.github.continuedev.continueintellijextension.nextEdit
import com.github.continuedev.continueintellijextension.FimResult
import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener
import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidget
import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlayRenderer
import com.github.continuedev.continueintellijextension.autocomplete.PendingCompletion
import com.github.continuedev.continueintellijextension.autocomplete.addInlayElement
import com.github.continuedev.continueintellijextension.autocomplete.isInjectedText
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.checkFim
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.github.continuedev.continueintellijextension.utils.uuid
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.InlayProperties
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiDocumentManager
@Service(Service.Level.PROJECT)
class NextEditService(private val project: Project) {
var pendingCompletion: PendingCompletion? = null
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
private val widget: AutocompleteSpinnerWidget? by lazy {
WindowManager.getInstance().getStatusBar(project)
?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget
}
// To avoid triggering another completion on partial acceptance,
// we need to keep track of whether the last change was a partial accept.
var lastChangeWasPartialAccept = false
fun triggerNextEdit(editor: Editor) {
val settings = service<ContinueExtensionSettings>()
if (!settings.continueState.enableTabAutocomplete) {
return
}
if (pendingCompletion != null) {
clearCompletions(pendingCompletion!!.editor)
}
// Set pending completion.
val completionId = uuid()
val offset = editor.caretModel.primaryCaret.offset
pendingCompletion = PendingCompletion(editor, offset, completionId, null)
// Request a completion from the core.
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
val uri = virtualFile?.toUriOrNull() ?: return
widget?.setLoading(true)
val line = editor.caretModel.primaryCaret.logicalPosition.line
val column = editor.caretModel.primaryCaret.logicalPosition.column
val input = mapOf(
"completionId" to completionId,
"filepath" to uri,
"pos" to mapOf(
"line" to line,
"character" to column
),
"clipboardText" to "",
"recentlyEditedRanges" to emptyList<Any>(),
"recentlyVisitedRanges" to emptyList<Any>(),
)
// TODO: Add message support for nextEdit/predict.
project.service<ContinuePluginService>().coreMessenger?.request(
"nextEdit/predict",
input,
null,
({ response ->
if (pendingCompletion == null || pendingCompletion?.completionId == completionId) {
widget?.setLoading(false)
}
val responseObject = response as Map<*, *>
val predictions = responseObject["content"] as List<*>
if (predictions.isNotEmpty()) {
val prediction = predictions[0].toString()
val oldEditRange = predictions[1].toString()
// Check if the prediction is purely additive.
val result = checkFim(
oldEditRange,
prediction,
Pair(line, column)
)
when (result) {
is FimResult.FimEdit -> {
// If so, render ghost text.
val finalTextToInsert = deduplicateCompletion(editor, offset, result.fimText)
if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
renderCompletion(editor, offset, finalTextToInsert)
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
}
}
is FimResult.NotFimEdit -> {
// Else, render a window.
if (shouldRenderCompletion(prediction, offset, line, editor)) {
val nextEditWindowService = NextEditWindowService.getInstance(project)
nextEditWindowService.showCodePreview(prediction, editor, completionId)
}
}
}
}
})
)
}
private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
return false
}
if (completion.lines().size == 1) {
return true
}
val endOffset = editor.document.getLineEndOffset(line)
// Do not render if completion is multi-line and caret is in middle of line
return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
}
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
// Check if completion matches the first 10 characters after the cursor
return ApplicationManager.getApplication().runReadAction<String> {
val document = editor.document
val caretOffset = editor.caretModel.offset
// Don't care about it if it's at the end of the document
if (caretOffset == document.textLength) return@runReadAction completion
val N = 10
var textAfterCursor = if (caretOffset + N <= document.textLength) {
document.getText(TextRange(caretOffset, caretOffset + N))
} else {
document.getText(TextRange(caretOffset, document.textLength))
}
// Avoid truncating the completion text when the text after the cursor is blank
if (textAfterCursor.isBlank()) return@runReadAction completion
// Determine the index of a newline character within the text following the cursor.
val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
// If a newline character is found and the current line is not empty, truncate the text at that point.
if (newlineIndex > 0) {
textAfterCursor = textAfterCursor.substring(0, newlineIndex)
}
val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor)
if (indexOfTextAfterCursorInCompletion > 0) {
return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1)
} else if (indexOfTextAfterCursorInCompletion == 0) {
return@runReadAction ""
}
return@runReadAction completion
}
}
private fun renderCompletion(editor: Editor, offset: Int, completion: String) {
if (completion.isEmpty()) {
return
}
if (isInjectedFile(editor)) return
// Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
if (shouldSkipRender()) {
return
}
ApplicationManager.getApplication().invokeLater {
WriteAction.run<Throwable> {
// Clear existing completions
hideCompletions(editor)
val properties = InlayProperties()
properties.relatesToPrecedingText(true)
properties.disableSoftWrapping(true)
val lines = completion.lines()
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
editor.addInlayElement(lines, offset, properties)
// val attributes = TextAttributes().apply {
// backgroundColor = JBColor.GREEN
// }
// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
// key.let { editor.colorsScheme.setAttributes(it, attributes) }
// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
}
}
}
fun accept() {
val completion = pendingCompletion ?: return
val text = completion.text ?: return
val editor = completion.editor
val offset = completion.offset
editor.document.insertString(offset, text)
editor.caretModel.moveToOffset(offset + text.length)
project.service<ContinuePluginService>().coreMessenger?.request(
"nextEdit/accept",
hashMapOf("completionId" to completion.completionId),
null,
({})
)
invokeLater {
clearCompletions(editor, completion)
}
}
private fun shouldSkipRender(): Boolean {
val settings = service<ContinueExtensionSettings>()
return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
}
private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())
.filter { it.isNotEmpty() }
val result = mutableListOf<String>()
var currentDelimiter = ""
for (part in initialSplit) {
if (part.matches(delimiterPattern.toRegex())) {
currentDelimiter += part
} else {
if (currentDelimiter.isNotEmpty()) {
result.add(currentDelimiter)
currentDelimiter = ""
}
result.add(part)
}
}
if (currentDelimiter.isNotEmpty()) {
result.add(currentDelimiter)
}
return result
}
fun partialAccept() {
val completion = pendingCompletion ?: return
val text = completion.text ?: return
val editor = completion.editor
val offset = completion.offset
lastChangeWasPartialAccept = true
// Split the text into words, keeping delimiters
val words = splitKeepingDelimiters(text)
println(words)
val word = words[0]
editor.document.insertString(offset, word)
editor.caretModel.moveToOffset(offset + word.length)
// Remove the completion and re-display it
hideCompletions(editor)
completion.text = text.substring(word.length)
completion.offset += word.length
renderCompletion(editor, completion.offset, completion.text!!)
}
private fun rejectCompletion(completion: PendingCompletion) {
// Send rejection message to core
widget?.setLoading(false)
project.service<ContinuePluginService>().coreMessenger?.request("nextEdit/reject", null, null, ({}))
}
fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
if (isInjectedFile(editor)) return
if (completion != null) {
// cancelCompletion(completion)
if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
}
disposeInlayRenderer(editor)
}
private fun isInjectedFile(editor: Editor): Boolean {
return runReadAction {
PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false
}
}
fun hideCompletions(editor: Editor) {
if (isInjectedFile(editor)) return
disposeInlayRenderer(editor)
}
private fun disposeInlayRenderer(editor: Editor) {
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueInlayRenderer) {
it.dispose()
}
}
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueInlayRenderer) {
it.dispose()
}
}
}
}

View file

@ -0,0 +1,304 @@
package com.github.continuedev.continueintellijextension.nextEdit
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorSettings
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.EditorTextField
import com.intellij.ui.components.JBScrollPane
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Point
import java.awt.event.ActionEvent
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.AbstractAction
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.KeyStroke
@Service(Service.Level.PROJECT)
class NextEditWindowService(private val project: Project) {
/**
* Creates a Swing component that displays syntax-highlighted code.
*
* @param code The code to display
* @param language The language/file extension of the code (e.g. "java", "kotlin", "py")
* @param isEditable Whether the code should be editable (default: false)
* @return A JComponent that can be added to the UI
*/
fun createCodeViewer(code: String, language: String, document: Document, isEditable: Boolean = false): JComponent {
// Get file type based on extension.
// NOTE: This is actually IDE and tier-dependent. For example, TypeScript won't work on IntelliJ CE.
val fileType = FileTypeManager.getInstance().getFileTypeByExtension(language)
// Create an EditorTextField with the specified code and file type.
val editorTextField = object : EditorTextField(code, project, fileType) {
override fun createEditor(): EditorEx {
val editor = super.createEditor()
// Configure editor settings.
val settings: EditorSettings = editor.settings
settings.isLineNumbersShown = true
settings.isLineMarkerAreaShown = true
settings.isIndentGuidesShown = true
settings.isVirtualSpace = false
settings.isRightMarginShown = false
settings.additionalLinesCount = 0
settings.isShowingSpecialChars = false
settings.isCaretRowShown = true
// Set read-only if not editable.
editor.isViewer = !isEditable
// Syntax highlighter.
// Get current editor color scheme.
val currentScheme = EditorColorsManager.getInstance().globalScheme
// Apply syntax highlighting with current theme.
val virtualFile = FileDocumentManager.getInstance().getFile(document)
var syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile)
// If we couldn't get a syntax highlighter from the file, try to get one just from the file type.
if (syntaxHighlighter == null) {
syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null)
}
// If we have a highlighter, apply it.
if (syntaxHighlighter != null) {
editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(
syntaxHighlighter,
currentScheme
)
} else {
// Fallback to plain text highlighting if all attempts fail.
val plainTextFileType = FileTypeManager.getInstance().getFileTypeByExtension("txt")
editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(
project,
plainTextFileType
)
}
// Apply the theme's background color.
editor.backgroundColor = currentScheme.defaultBackground
return editor
}
// Override to ensure multi-line support.
override fun getPreferredSize(): Dimension {
val lineCount = code.lines().size
// Adjust height based on line count (with some minimum).
val preferredSize = super.getPreferredSize()
val lineHeight = preferredSize.height / (if (lineCount > 0) lineCount else 1)
val newHeight = lineHeight * (if (lineCount > 0) lineCount else 1) + 10 // Add padding
return Dimension(preferredSize.width, newHeight)
}
}
// Enable multi-line mode.
editorTextField.setOneLineMode(false)
// Wrap in a scroll pane for larger code blocks.
val panel = JPanel(BorderLayout())
panel.add(JBScrollPane(editorTextField), BorderLayout.CENTER)
return panel
}
/**
* Shows a popup dialog with the code preview.
*/
fun showCodePreview(code: String, parentEditor: Editor, completionId: String) {
// Use invokeAndWait or invokeLater to ensure we're on the EDT.
com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater {
val codeViewer = createCodeViewer(code, getFileLanguage(parentEditor.document), parentEditor.document)
// Create a button panel.
val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT))
val acceptButton = JButton("Accept (Tab)")
val dismissButton = JButton("Dismiss (Esc)")
buttonPanel.add(acceptButton)
buttonPanel.add(dismissButton)
// Create a panel to hold the code viewer and buttons.
val panel = JPanel(BorderLayout())
panel.add(codeViewer, BorderLayout.CENTER)
panel.add(buttonPanel, BorderLayout.SOUTH)
// Create the popup.
val popup = JBPopupFactory.getInstance()
.createComponentPopupBuilder(panel, codeViewer)
.setMovable(true)
.setResizable(true)
.setRequestFocus(true)
.setCancelOnClickOutside(true)
.setCancelOnOtherWindowOpen(true)
.setFocusable(true)
.addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
if (!event.isOk) {
// This only triggers when dismissed, not when accepted.
println("Dismissing code preview popup")
project.service<ContinuePluginService>().coreMessenger?.request(
"nextEdit/reject",
hashMapOf("completionId" to completionId),
null, ({})
)
}
}
})
.createPopup()
// Helper function to accept the code and apply it to the editor.
fun acceptCode() {
val document = parentEditor.document
val caretModel = parentEditor.caretModel
val caretOffset = caretModel.offset
val caretPosition = document.getLineNumber(caretOffset)
// Calculate start and end lines.
val totalLines = document.lineCount
val startLine = maxOf(0, caretPosition - 5)
val endLine = minOf(totalLines - 1, caretPosition + 5)
// Get start and end offsets.
val startOffset = document.getLineStartOffset(startLine)
val endOffset = document.getLineEndOffset(endLine)
// Write command to replace the text.
WriteCommandAction.runWriteCommandAction(project) {
document.replaceString(startOffset, endOffset, code)
}
project.service<ContinuePluginService>().coreMessenger?.request(
"nextEdit/accept",
hashMapOf("completionId" to completionId),
null, ({})
)
}
// Use ActionManager to handle Tab key globally during popup display.
val acceptAction = object : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
acceptCode()
popup.closeOk(null)
}
}
// Create a custom shortcut set for the Tab key.
val customShortcutSet = CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0))
// Register action with shortcut.
acceptAction.registerCustomShortcutSet(customShortcutSet, panel)
// Add button actions.
acceptButton.addActionListener {
acceptCode()
popup.closeOk(null)
}
dismissButton.addActionListener {
popup.cancel()
}
// Get the exact position of the cursor.
val visualPosition = parentEditor.caretModel.visualPosition
val cursorPoint = parentEditor.visualPositionToXY(visualPosition)
// Convert to screen coordinates.
val editorComponent = parentEditor.component
val locationOnScreen = editorComponent.locationOnScreen
val screenPoint = Point(
locationOnScreen.x + cursorPoint.x,
locationOnScreen.y + cursorPoint.y
)
// Show the popup at the cursor position.
popup.showInScreenCoordinates(editorComponent, screenPoint)
// Ensure proper focus for keyboard shortcuts.
codeViewer.requestFocusInWindow()
}
}
// Move editorConfig to a proper instance property that gets actual editor settings.
private val editorConfig: EditorConfig by lazy {
val settings = EditorSettingsExternalizable.getInstance()
val editorFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize
val editorFontFamily = EditorColorsManager.getInstance().globalScheme.editorFontName
EditorConfig(
fontSize = editorFontSize.toDouble(),
fontFamily = editorFontFamily
)
}
// Data class to hold editor configuration.
private data class EditorConfig(
val fontSize: Double = 14.0,
val fontFamily: String = "JetBrains Mono"
)
/**
* Convenience method to map common programming languages to their file extensions.
*/
fun mapLanguageToExtension(language: String): String {
return when (language.lowercase()) {
"javascript" -> "js"
"typescript" -> "ts"
"python" -> "py"
"java" -> "java"
"kotlin" -> "kt"
"c++" -> "cpp"
"c#" -> "cs"
"go" -> "go"
"rust" -> "rs"
"ruby" -> "rb"
"php" -> "php"
"swift" -> "swift"
"shell", "bash" -> "sh"
"html" -> "html"
"css" -> "css"
"json" -> "json"
"xml" -> "xml"
"yaml", "yml" -> "yaml"
"markdown", "md" -> "md"
// Add more mappings as needed
else -> language
}
}
private fun getFileLanguage(document: Document): String {
val virtualFile = FileDocumentManager.getInstance().getFile(document)
return virtualFile?.extension?.lowercase() ?: "text"
}
companion object {
fun getInstance(project: Project): NextEditWindowService = project.service()
}
}

View file

@ -46,6 +46,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
init {
System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
System.setProperty("ide.browser.jcef.out-of-process.enabled", "false")
}
val browser: ContinueBrowser by lazy {

View file

@ -30,7 +30,8 @@ data class IdeInfo(
val name: String,
val version: String,
val remoteName: String,
val extensionVersion: String
val extensionVersion: String,
val isPrerelease: Boolean
)
data class Problem(
@ -247,4 +248,9 @@ data class AcceptOrRejectDiffPayload(
data class ShowFilePayload(
val filepath: String
)
)
sealed class FimResult {
data class FimEdit(val fimText: String) : FimResult()
object NotFimEdit : FimResult()
}

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.utils
import com.github.continuedev.continueintellijextension.FimResult
import com.intellij.openapi.vfs.VirtualFile
import java.net.NetworkInterface
import java.util.*
@ -117,4 +118,71 @@ fun getOsAndArchTarget(): String {
}
return "$osStr-$arch"
}
/**
* Check if the diff is indeed a FIM (Fill-In-Middle).
* @param oldEditRange Original string content.
* @param newEditRange New string content.
* @param cursorPosition The position of the cursor in the old string.
* @return A Pair where the first value is a boolean indicating if the change is purely additive (FIM)
* and the second value is the FIM text content or null if not a FIM.
*/
fun checkFim(
oldEditRange: String,
newEditRange: String,
cursorPosition: Pair<Int, Int> // line, character
): FimResult {
// Find the common prefix
var prefixLength = 0
while (prefixLength < oldEditRange.length &&
prefixLength < newEditRange.length &&
oldEditRange[prefixLength] == newEditRange[prefixLength]) {
prefixLength++
}
// Find the common suffix
var oldSuffixPos = oldEditRange.length - 1
var newSuffixPos = newEditRange.length - 1
while (oldSuffixPos >= prefixLength &&
newSuffixPos >= prefixLength &&
oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]) {
oldSuffixPos--
newSuffixPos--
}
// The old text is purely preserved if:
// 1. The prefix ends before or at the cursor.
// 2. The suffix starts after or at the cursor.
// 3. There's no gap between prefix and suffix in the old text.
val suffixStartInOld = oldSuffixPos + 1
val suffixStartInNew = newSuffixPos + 1
// Convert cursor position to an offset in the string.
// For simplicity, we need to calculate the cursor's position in the string.
// This requires knowledge of line endings in the oldEditRange.
val lines = oldEditRange.substring(0, prefixLength).split("\n")
val cursorOffset = if (lines.size > 1) {
lines.dropLast(1).sumOf { it.length + 1 } + cursorPosition.second
} else {
cursorPosition.second
}
// Check if the cursor is positioned between the prefix and suffix.
val cursorBetweenPrefixAndSuffix =
prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld
// Check if the old text is completely preserved (no deletion).
val noTextDeleted = suffixStartInOld - prefixLength <= 0
val isFim = cursorBetweenPrefixAndSuffix && noTextDeleted
return if (isFim) {
// Extract the content between prefix and suffix in the new string.
FimResult.FimEdit(newEditRange.substring(prefixLength, suffixStartInNew))
} else {
FimResult.NotFimEdit
}
}

View file

@ -176,6 +176,13 @@
<keyboard-shortcut keymap="Mac OS X" first-keystroke="TAB"/>
</action>
<action id="com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction"
class="com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction"
text="Accept Autocomplete Suggestion" description="Accept Next Edit Prediction">
<keyboard-shortcut keymap="$default" first-keystroke="TAB"/>
<keyboard-shortcut keymap="Mac OS X" first-keystroke="TAB"/>
</action>
<action id="com.github.continuedev.continueintellijextension.autocomplete.CancelAutocompleteAction"
class="com.github.continuedev.continueintellijextension.autocomplete.CancelAutocompleteAction"
text="Cancel Autocomplete Suggestion" description="Cancel Autocomplete Suggestion">

View file

@ -28,11 +28,15 @@ class Autocomplete {
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
System.setProperty("continue.autocomplete.test.environment", "true")
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
fun closeProject(remoteRobot: RemoteRobot) {
System.clearProperty("continue.autocomplete.test.environment")
CommonSteps(remoteRobot).closeProject()
}
@Test
@Video

View file

@ -16,6 +16,7 @@ import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.VK_I
@ -37,6 +38,7 @@ class InlineEdit {
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
@Test
@Disabled("Failing in CI, seems like the timeout just needs to be increased")
@Video
fun submitInlineEdit(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {

View file

@ -0,0 +1,51 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.FimResult
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
import com.github.continuedev.continueintellijextension.utils.checkFim
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.io.File
import kotlin.test.assertEquals
class CheckFimTest {
@Test
fun testFim() {
val oldEditRange = "hello world"
val newEditRange = "hello this world"
val cursorPosition = Pair(0, 6)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("this "))
}
@Test
fun testMultilineFim() {
val oldEditRange = "hello {\n world\n}"
val newEditRange = "hello {\n print()\n world\n}"
val cursorPosition = Pair(1, 2)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("print()\n "))
}
@Test
fun testNotFim() {
val oldEditRange = "hello world"
val newEditRange = "hello this world"
val cursorPosition = Pair(0, 8)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
}
@Test
fun testMultilineNotFim() {
val oldEditRange = "hello {\n world\n}"
val newEditRange = "hello {\n world\n}\nprint()"
val cursorPosition = Pair(1, 2)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
}
@Test
fun testFimEdge() {
val oldEditRange = ""
val newEditRange = ""
val cursorPosition = Pair(0, 0)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit(""))
}
}

View file

@ -1,51 +0,0 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcess
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.RepeatedTest
import java.io.InputStream
import java.io.OutputStream
class ContinueProcessHandlerTest {
@RepeatedTest(5)
fun `test concurrent writes with queue`() = runTest {
val process = StringContinueProcess()
val handler = ContinueProcessHandler(this, process) {}
(0..100).map { i -> launch(Dispatchers.Default) { handler.write("message number $i") } }
.joinAll()
handler.close()
// assert all message lines are present (order is not important)
val lines = process.string.split("\r\n").filter { it.isNotBlank() }
for (i in 0..100)
Assertions.assertTrue(lines.contains("message number $i"))
// note: this test will fail if the handler writes messages directly to the output stream
// this problem can be easily reproduced by removing the channel<string> from the handler code
}
class StringContinueProcess : ContinueProcess {
val string = StringBuilder()
override val input: InputStream = InputStream.nullInputStream()
override val output: OutputStream = object : OutputStream() {
override fun write(b: Int) {
string.append(b.toChar())
}
override fun write(b: ByteArray, off: Int, len: Int) {
string.append(String(b, off, len))
}
}
override fun close() {
}
}
}

View file

@ -26,29 +26,31 @@
<p></p>
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](../../docs/images/agent.gif)
## Chat
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave the IDE
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
the IDE
![chat](docs/static/img/chat.gif)
![chat](../../docs/images/chat.gif)
## Autocomplete
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
![autocomplete](docs/static/img/autocomplete.gif)
![autocomplete](../../docs/images/autocomplete.gif)
## Edit
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
file
![edit](docs/static/img/edit.gif)
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](docs/static/img/agent.gif)
![edit](../../docs/images/edit.gif)
</div>

View file

@ -32,16 +32,14 @@ export class GUISelectors {
}
public static getAcceptToolCallButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(
view,
"accept-tool-call-button",
return view.findWebElement(
By.css("[data-testid*='accept-tool-call-button']"),
);
}
public static getRejectToolCallButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(
view,
"reject-tool-call-button",
return view.findWebElement(
By.css("[data-testid*='reject-tool-call-button']"),
);
}
@ -102,11 +100,9 @@ export class GUISelectors {
}
public static getNthMessageDeleteButton(view: WebView, index: number) {
const adjustedIndex = 1 + index * 2;
return SelectorUtils.getElementByDataTestId(
view,
`delete-button-${adjustedIndex}`,
`delete-button-${index}`,
);
}

View file

@ -156,20 +156,20 @@ describe("GUI Test", () => {
GUISelectors.getThreadMessageByText(view, llmResponse2),
);
GUISelectors.getThreadMessageByText(view, llmResponse1);
// Delete the first assistant response (index 1) - this deletes both user msg 0 and assistant response 0
await (await GUISelectors.getNthMessageDeleteButton(view, 1)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse0),
);
// Delete the second assistant response (now at index 1) - this deletes both user msg 1 and assistant response 1
await (await GUISelectors.getNthMessageDeleteButton(view, 1)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse1),
);
GUISelectors.getThreadMessageByText(view, llmResponse0);
await (await GUISelectors.getNthMessageDeleteButton(view, 0)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse0),
);
GUISelectors.getThreadMessageByText(view, llmResponse2);
await (await GUISelectors.getNthMessageDeleteButton(view, 0)).click();
// Delete the third assistant response (now at index 1) - this deletes both user msg 2 and assistant response 2
await (await GUISelectors.getNthMessageDeleteButton(view, 1)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse2),
);
@ -584,4 +584,4 @@ describe("GUI Test", () => {
);
}).timeout(DEFAULT_TIMEOUT.XL);
});
});
});

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.60",
"version": "1.1.63",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.60",
"version": "1.1.63",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -2544,9 +2544,10 @@
"integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g=="
},
"node_modules/@types/node": {
"version": "16.18.119",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.119.tgz",
"integrity": "sha512-ia7V9a2FnhUFfetng4/sRPBMTwHZUkPFY736rb1cg9AgG7MZdR97q7/nLR9om+sq5f1la9C857E0l/nrI0RiFQ=="
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"license": "MIT"
},
"node_modules/@types/node-fetch": {
"version": "2.6.12",

View file

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

View file

@ -1,4 +1,3 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import * as vscode from "vscode";
import { getTheme } from "./util/getTheme";
@ -59,16 +58,10 @@ export class ContinueGUIWebviewViewProvider
}
constructor(
private readonly configHandlerPromise: Promise<ConfigHandler>,
private readonly windowId: string,
private readonly extensionContext: vscode.ExtensionContext,
) {
this.webviewProtocol = new VsCodeWebviewProtocol(
(async () => {
const configHandler = await this.configHandlerPromise;
return configHandler.reloadConfig();
}).bind(this),
);
this.webviewProtocol = new VsCodeWebviewProtocol();
}
getSidebarContent(

View file

@ -27,6 +27,7 @@ import type {
TerminalOptions,
Thread,
} from "core";
import { getExtensionVersion, isExtensionPrerelease } from "./util/util";
class VsCodeIde implements IDE {
ideUtils: VsCodeIdeUtils;
@ -153,9 +154,8 @@ class VsCodeIde implements IDE {
name: vscode.env.appName,
version: vscode.version,
remoteName: vscode.env.remoteName || "local",
extensionVersion:
vscode.extensions.getExtension("continue.continue")?.packageJSON
.version,
extensionVersion: getExtensionVersion(),
isPrerelease: isExtensionPrerelease(),
});
}

View file

@ -3,8 +3,9 @@ import { EXTENSION_NAME } from "core/control-plane/env";
// @ts-ignore
import * as vscode from "vscode";
import { DiffLine } from "core";
import { DiffChar, DiffLine } from "core";
import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
import { myersCharDiff } from "core/diff/myers";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
@ -295,14 +296,19 @@ export class NextEditWindowManager {
);
// Create and apply decoration with the text.
await this.renderTooltip(
await this.renderWindow(
editor,
currCursorPos,
oldEditRangeSlice,
newEditRangeSlice,
editableRegionStartLine,
diffLines,
);
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
this.renderDeletes(editor, editableRegionStartLine, diffChars);
// Reserve tab and esc to either accept or reject the displayed next edit contents.
await NextEditWindowManager.reserveTabAndEsc();
}
@ -531,6 +537,7 @@ export class NextEditWindowManager {
private async createCodeRender(
text: string,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<
| { uri: vscode.Uri; dimensions: { width: number; height: number } }
| undefined
@ -546,14 +553,15 @@ export class NextEditWindowManager {
const uri = await this.codeRenderer.getDataUri(
text,
"typescript",
this.fontSize,
this.fontFamily,
dimensions,
SVG_CONFIG.lineHeight,
{
imageType: "svg",
fontSize: this.fontSize,
fontFamily: this.fontFamily,
dimensions: dimensions,
lineHeight: SVG_CONFIG.lineHeight,
},
currLineOffsetFromTop,
newDiffLines,
);
return {
@ -576,11 +584,13 @@ export class NextEditWindowManager {
predictedCode: string,
position: vscode.Position,
editableRegionStartLine: number,
newDiffLines: DiffLine[],
): Promise<vscode.TextEditorDecorationType | undefined> {
const currLineOffsetFromTop = position.line - editableRegionStartLine;
const uriAndDimensions = await this.createCodeRender(
predictedCode,
currLineOffsetFromTop,
newDiffLines,
);
if (!uriAndDimensions) {
return undefined;
@ -598,12 +608,12 @@ export class NextEditWindowManager {
SVG_CONFIG.getTipWidth(originalCode) -
SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]);
console.log(marginLeft);
console.log(SVG_CONFIG.getTipWidth(originalCode));
console.log(
SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]),
);
console.log(originalCode.split("\n")[currLineOffsetFromTop]);
// console.log(marginLeft);
// console.log(SVG_CONFIG.getTipWidth(originalCode));
// console.log(
// SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]),
// );
// console.log(originalCode.split("\n")[currLineOffsetFromTop]);
return vscode.window.createTextEditorDecorationType({
before: {
contentIconPath: uri,
@ -703,16 +713,16 @@ export class NextEditWindowManager {
}
/**
* Render a tooltip with the given text at the specified position.
* Render a window with the given text at the specified position.
*/
private async renderTooltip(
private async renderWindow(
editor: vscode.TextEditor,
position: vscode.Position,
originalCode: string,
predictedCode: string,
editableRegionStartLine: number,
newDiffLines: DiffLine[],
) {
console.log("renderTooltip");
// Capture document version to detect changes.
const docVersion = editor.document.version;
@ -722,6 +732,7 @@ export class NextEditWindowManager {
predictedCode,
position,
editableRegionStartLine,
newDiffLines,
);
if (!decoration) {
console.error("Failed to create decoration for text:", predictedCode);
@ -737,7 +748,8 @@ export class NextEditWindowManager {
// Store the decoration and editor.
await this.hideAllNextEditWindows();
this.currentDecoration = decoration;
this.currentDecoration = decoration; // TODO: This might be redundant.
this.disposables.push(decoration);
this.activeEditor = editor;
// Calculate how far off to the right of the cursor the decoration should be.
@ -773,6 +785,66 @@ export class NextEditWindowManager {
this.mostRecentCompletionId,
);
}
private renderDeletes(
editor: vscode.TextEditor,
editableRegionStartLine: number,
// oldEditRangeSlice: string,
// newEditRangeSlice: string,
oldDiffChars: DiffChar[],
) {
const charsToDelete: vscode.DecorationOptions[] = [];
// const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
oldDiffChars.forEach((diff) => {
// TODO: This check if technically redundant.
if (diff.type === "old") {
charsToDelete.push({
range: new vscode.Range(
new vscode.Position(
editableRegionStartLine + diff.oldLineIndex!,
diff.oldCharIndexInLine!,
),
new vscode.Position(
editableRegionStartLine + diff.oldLineIndex!,
diff.oldCharIndexInLine! + diff.char.length,
),
),
});
}
});
const deleteDecorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: "rgba(255, 0, 0, 0.5)",
textDecoration: "line-through",
});
editor.setDecorations(deleteDecorationType, charsToDelete);
this.disposables.push(deleteDecorationType);
}
async getExactCharacterWidth(): Promise<number> {
// For VS Code extensions, you can sometimes access the editor's text metrics
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
// VS Code has internal methods to measure text, but they're not all exposed
// in the public API. You might need to use reflection or known properties.
// Example accessing through reflection (this is pseudocode)
const editorInstance = activeEditor as any;
if (editorInstance._modelData && editorInstance._modelData.viewModel) {
const viewModel = editorInstance._modelData.viewModel;
return (
viewModel.getLineWidth(0) /
activeEditor.document.lineAt(0).text.length
);
}
}
// If all else fails, return a reasonable default
return SVG_CONFIG.fontSize * 0.6;
}
}
export default async function setupNextEditWindowManager(

View file

@ -100,7 +100,6 @@ export class VsCodeExtension {
resolveConfigHandler = resolve;
});
this.sidebar = new ContinueGUIWebviewViewProvider(
configHandlerPromise,
this.windowId,
this.extensionContext,
);
@ -147,8 +146,10 @@ export class VsCodeExtension {
);
resolveVerticalDiffManager?.(this.verticalDiffManager);
void setupRemoteConfigSync(
this.configHandler.reloadConfig.bind(this.configHandler),
void setupRemoteConfigSync(() =>
this.configHandler.reloadConfig.bind(this.configHandler)(
"Remote config sync",
),
);
void this.configHandler.loadConfig().then(({ config }) => {
@ -284,7 +285,9 @@ export class VsCodeExtension {
if (stats.size === 0) {
return;
}
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Global JSON config updated - fs file watch",
);
});
fs.watchFile(
@ -294,7 +297,9 @@ export class VsCodeExtension {
if (stats.size === 0) {
return;
}
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Global YAML config updated - fs file watch",
);
},
);
@ -302,7 +307,7 @@ export class VsCodeExtension {
if (stats.size === 0) {
return;
}
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("config.ts updated - fs file watch");
});
vscode.workspace.onDidChangeTextDocument(async (event) => {
@ -363,7 +368,7 @@ export class VsCodeExtension {
);
if (e.provider.id === "github") {
this.configHandler.reloadConfig();
this.configHandler.reloadConfig("Github sign-in status changed");
}
}
});

View file

@ -8,6 +8,7 @@ import {
} from "core/control-plane/AuthTypes";
import { getControlPlaneEnvSync } from "core/control-plane/env";
import fetch from "node-fetch";
import { EventEmitter as NodeEventEmitter } from "node:events";
import { v4 as uuidv4 } from "uuid";
import {
authentication,
@ -101,6 +102,10 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
this.secretStorage = new SecretStorage(context);
// Immediately refresh any existing sessions
this.attemptEmitter = new NodeEventEmitter();
WorkOsAuthProvider.hasAttemptedRefresh = new Promise((resolve) => {
this.attemptEmitter.on("attempted", resolve);
});
void this.refreshSessions();
// Set up a regular interval to refresh tokens
@ -147,6 +152,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
public async getSessions(
scopes?: string[],
): Promise<ContinueAuthenticationSession[]> {
// await this.hasAttemptedRefresh;
const data = await this.secretStorage.get(SESSIONS_SECRET_KEY);
if (!data) {
return [];
@ -182,6 +188,8 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
return this.ideRedirectUri;
}
public static hasAttemptedRefresh: Promise<void>;
private attemptEmitter: NodeEventEmitter;
async refreshSessions() {
// Prevent concurrent refresh operations
if (this._isRefreshing) {
@ -198,9 +206,12 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
}
}
// It is important that every path in this function emits the attempted event
// As config loading in core will be locked until refresh is attempted
private async _refreshSessions(): Promise<void> {
const sessions = await this.getSessions();
if (!sessions.length) {
this.attemptEmitter.emit("attempted");
return;
}
@ -247,6 +258,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
try {
return await this._refreshSession(refreshToken);
} catch (error: any) {
this.attemptEmitter.emit("attempted");
// Don't retry for auth errors
if (
error.message?.includes("401") ||
@ -270,6 +282,8 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
.catch(reject);
}, delay);
});
} finally {
this.attemptEmitter.emit("attempted");
}
}
@ -553,7 +567,7 @@ export async function getControlPlaneSessionInfo(
if (useOnboarding) {
WorkOsAuthProvider.useOnboardingUri = true;
}
await WorkOsAuthProvider.hasAttemptedRefresh;
const session = await authentication.getSession(
controlPlaneEnv.AUTH_TYPE,
[],

View file

@ -61,7 +61,7 @@ export const handleTextDocumentChange = async (
const editor = vscode.window.activeTextEditor;
const { config } = await configHandler.loadConfig();
if (!config?.experimental?.logEditingData) return;
// if (!config?.experimental?.logEditingData) return;
if (!editor) return;
if (event.contentChanges.length === 0) return;

View file

@ -126,3 +126,15 @@ export function getExtensionVersion(): string {
export function getvsCodeUriScheme(): string {
return vscode.env.uriScheme;
}
export function isExtensionPrerelease(): boolean {
const extensionVersion = getExtensionVersion();
const versionParts = extensionVersion.split(".");
if (versionParts.length >= 2) {
const minorVersion = parseInt(versionParts[1], 10);
if (!isNaN(minorVersion)) {
return minorVersion % 2 !== 0;
}
}
return false;
}

View file

@ -0,0 +1,26 @@
import { expect, test, vi } from "vitest";
import * as vscode from "vscode";
// Mock the vscode module
vi.mock("vscode", () => ({
extensions: {
getExtension: vi.fn(),
},
}));
// Import the function after mocking
import { isExtensionPrerelease } from "./util";
test("isExtensionPrerelease detects prerelease versions correctly", () => {
// 1.0.0 is not prerelease (even minor version)
vi.mocked(vscode.extensions.getExtension).mockReturnValue({
packageJSON: { version: "1.0.0" },
} as any);
expect(isExtensionPrerelease()).toBe(false);
// 1.1.0 is prerelease (odd minor version)
vi.mocked(vscode.extensions.getExtension).mockReturnValue({
packageJSON: { version: "1.1.0" },
} as any);
expect(isExtensionPrerelease()).toBe(true);
});

View file

@ -152,7 +152,7 @@ export class VsCodeWebviewProtocol
this._webviewListener = this._webview.onDidReceiveMessage(handleMessage);
}
constructor(private readonly reloadConfig: () => void) {}
constructor() {}
invoke<T extends keyof FromWebviewProtocol>(
messageType: T,

View file

@ -2,8 +2,7 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
import { useAppDispatch } from "../redux/hooks";
import { cancelToolCall } from "../redux/slices/sessionSlice";
import { getMetaKeyLabel } from "../util";
import { ToolTip } from "./gui/Tooltip";
@ -23,21 +22,22 @@ export default function AcceptRejectAllButtons({
(state) => state.status === "done",
);
const ideMessenger = useContext(IdeMessengerContext);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const dispatch = useAppDispatch();
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
if (
status === "rejectDiff" &&
currentToolCallApplyState?.status === "done"
) {
dispatch(
cancelToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// For reject operations, cancel all tool calls associated with pending apply states
if (status === "rejectDiff") {
for (const applyState of pendingApplyStates) {
if (applyState.toolCallId && applyState.status === "done") {
dispatch(
cancelToolCall({
toolCallId: applyState.toolCallId,
}),
);
}
}
}
// Process all pending apply states
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {
filepath,

View file

@ -161,18 +161,14 @@ export function AssistantAndOrgListbox() {
</ListboxOption>
<ListboxOption
value="new-assistant"
value="reload-assistant"
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={session ? onNewAssistant : () => login(false)}
onClick={() => refreshProfiles()}
>
<span
className="text-description flex flex-row items-center"
style={{ fontSize: tinyFont }}
onClick={async (e) => {
e.stopPropagation();
await refreshProfiles();
}}
>
<ArrowPathIcon
className={cn(

View file

@ -17,11 +17,9 @@ import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
export function HistoryTableRow({
sessionMetadata,
date,
index,
}: {
sessionMetadata: SessionMetadata;
date: Date;
index: number;
}) {
const dispatch = useAppDispatch();
@ -67,7 +65,7 @@ export function HistoryTableRow({
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
data-testid={`history-row-${index}`}
className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3"
className="border-border relative mb-2 box-border flex w-full cursor-pointer overflow-hidden rounded-lg border border-solid p-3"
onClick={async () => {
await dispatch(exitEdit({}));
if (sessionMetadata.sessionId !== currentSessionId) {
@ -83,7 +81,7 @@ export function HistoryTableRow({
>
<div className="flex-1 cursor-pointer space-y-1">
{editing ? (
<div className="text-md">
<div>
<Input
type="text"
className="w-full"
@ -95,13 +93,13 @@ export function HistoryTableRow({
/>
</div>
) : (
<span className="line-clamp-1 break-all text-base font-semibold">
<span className="line-clamp-1 break-all text-sm font-semibold">
{sessionMetadata.title}
</span>
)}
<div className="flex" style={{ color: "#9ca3af" }}>
<span className="line-clamp-1 break-all">
<div className="text-description-muted flex">
<span className="line-clamp-1 break-all text-xs">
{getUriPathBasename(sessionMetadata.workspaceDirectory || "")}
</span>
{/* Uncomment to show the date */}
@ -119,7 +117,7 @@ export function HistoryTableRow({
</div>
{hovered && !editing && (
<div className="bg-vsc-background absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-2 rounded-full py-1.5 pl-4 pr-4 shadow-md">
<div className="bg-badge absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
<HeaderButtonWithToolTip
text="Edit"
onClick={async (e) => {
@ -127,7 +125,7 @@ export function HistoryTableRow({
setEditing(true);
}}
>
<PencilSquareIcon width="1.3em" height="1.3em" />
<PencilSquareIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Delete"
@ -136,7 +134,7 @@ export function HistoryTableRow({
await dispatch(deleteSession(sessionMetadata.sessionId));
}}
>
<TrashIcon width="1.3em" height="1.3em" />
<TrashIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
</div>
)}

View file

@ -23,18 +23,9 @@ import { refreshSessionMetadata } from "../../redux/thunks/session";
import { getFontSize, getPlatform } from "../../util";
import { ROUTES } from "../../util/navigation";
import ConfirmationDialog from "../dialogs/ConfirmationDialog";
import { Button } from "../ui";
import { HistoryTableRow } from "./HistoryTableRow";
const parseDate = (date: string): Date => {
let dateObj = new Date(date);
if (isNaN(dateObj.getTime())) {
dateObj = new Date(parseInt(date));
}
return dateObj;
};
const HEADER_CLASS =
"flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6";
import { groupSessionsByDate, parseDate } from "./util";
export function History() {
const dispatch = useAppDispatch();
@ -124,10 +115,9 @@ export function History() {
);
}, [allSessionMetadata, searchTerm, minisearch]);
const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7);
const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30);
const earlier = new Date(0);
const sessionGroups = useMemo(() => {
return groupSessionsByDate(filteredAndSortedSessions);
}, [filteredAndSortedSessions]);
const showClearSessionsDialog = () => {
dispatch(
@ -158,9 +148,9 @@ export function History() {
style={{ fontSize: getFontSize() }}
className="flex flex-1 flex-col overflow-auto px-1"
>
<div className="relative my-2 flex justify-center space-x-2">
<div className="relative my-2 mt-4 flex justify-center space-x-2">
<input
className="bg-vsc-input-background text-vsc-foreground flex-1 rounded-md border border-none py-1 pl-2 pr-8 text-base outline-none focus:outline-none"
className="bg-vsc-input-background text-vsc-foreground flex-1 rounded-md border border-none py-1 pl-2 pr-8 text-sm outline-none focus:outline-none"
ref={searchInputRef}
placeholder="Search past sessions"
type="text"
@ -179,7 +169,8 @@ export function History() {
/>
)}
</div>
<div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto pr-4">
<div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto">
{filteredAndSortedSessions.length === 0 && (
<div className="m-3 text-center">
{isSessionMetadataLoading ? (
@ -196,60 +187,42 @@ export function History() {
<table className="flex flex-1 flex-col">
<tbody className="">
{filteredAndSortedSessions.map((session, index) => {
const prevDate =
index > 0
? parseDate(filteredAndSortedSessions[index - 1].dateCreated)
: earlier;
const date = parseDate(session.dateCreated);
return (
<Fragment key={index}>
{index === 0 && date > yesterday && (
<tr className={HEADER_CLASS}>
<td colSpan={3}>Today</td>
</tr>
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
<div className={HEADER_CLASS}>
<td colSpan={3}>This Week</td>
</div>
)}
{date < lastWeek &&
date > lastMonth &&
prevDate > lastWeek && (
<div className={HEADER_CLASS}>
<td colSpan={3}>This Month</td>
</div>
)}
{date < lastMonth && prevDate > lastMonth && (
<div className={HEADER_CLASS}>
<td colSpan={3}>Older</td>
</div>
)}
{sessionGroups.map((group, groupIndex) => (
<Fragment key={group.label}>
<tr
className={`user-select-none sticky mb-3 ml-2 flex h-6 justify-start text-left text-base font-bold opacity-75 ${
groupIndex === 0 ? "mt-2" : "mt-8"
}`}
>
<td colSpan={3}>{group.label}</td>
</tr>
{group.sessions.map((session, sessionIndex) => (
<HistoryTableRow
key={session.sessionId}
sessionMetadata={session}
date={date}
index={index}
index={sessionIndex}
/>
</Fragment>
);
})}
))}
</Fragment>
))}
</tbody>
</table>
</div>
<div className="flex flex-col items-end justify-center border-0 border-t border-solid border-gray-400 px-2 py-1.5 text-sm">
<i
className=""
data-testid="history-sessions-note"
>{`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`}</i>
<div className="border-border flex flex-col items-end justify-center border-0 border-t border-solid px-2 py-3 text-xs">
<Button variant="secondary" size="sm" onClick={showClearSessionsDialog}>
Clear chats
</Button>
<span
className="cursor-pointer text-xs text-gray-400 hover:underline"
onClick={showClearSessionsDialog}
className="text-description text-2xs"
data-testid="history-sessions-note"
>
Clear session history
Chat history is saved to{" "}
<span className="italic">
{platform === "windows"
? "%USERPROFILE%/.continue"
: "~/.continue/sessions"}
</span>
</span>
</div>
</div>

View file

@ -0,0 +1,50 @@
import { SessionMetadata } from "core";
export const parseDate = (date: string): Date => {
let dateObj = new Date(date);
if (isNaN(dateObj.getTime())) {
dateObj = new Date(parseInt(date));
}
return dateObj;
};
export interface SessionGroup {
label: string;
sessions: SessionMetadata[];
}
export const groupSessionsByDate = (
sessions: SessionMetadata[],
): SessionGroup[] => {
const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7);
const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30);
const groups: SessionGroup[] = [];
const todaySessions = sessions.filter(
(session) => parseDate(session.dateCreated) > yesterday,
);
const weekSessions = sessions.filter((session) => {
const date = parseDate(session.dateCreated);
return date <= yesterday && date > lastWeek;
});
const monthSessions = sessions.filter((session) => {
const date = parseDate(session.dateCreated);
return date <= lastWeek && date > lastMonth;
});
const olderSessions = sessions.filter(
(session) => parseDate(session.dateCreated) <= lastMonth,
);
if (todaySessions.length > 0)
groups.push({ label: "Today", sessions: todaySessions });
if (weekSessions.length > 0)
groups.push({ label: "This Week", sessions: weekSessions });
if (monthSessions.length > 0)
groups.push({ label: "This Month", sessions: monthSessions });
if (olderSessions.length > 0)
groups.push({ label: "Older", sessions: olderSessions });
return groups;
};

View file

@ -97,6 +97,18 @@ export function ModeSelect() {
<div className="flex flex-row items-center gap-1.5">
<ModeIcon mode="chat" />
<span className="">Chat</span>
<InformationCircleIcon
data-tooltip-id="chat-tip"
className="h-2.5 w-2.5 flex-shrink-0"
/>
<ToolTip
id="chat-tip"
style={{
zIndex: 200001,
}}
>
All tools disabled
</ToolTip>
<span
className={`text-description-muted text-[${getFontSize() - 3}px] mr-auto`}
>
@ -123,7 +135,7 @@ export function ModeSelect() {
zIndex: 200001,
}}
>
In Plan mode, only read-only and MCP tools are enabled
Read-only/MCP tools available
</ToolTip>
</div>
{agentModeSupported ? (
@ -152,7 +164,7 @@ export function ModeSelect() {
zIndex: 200001,
}}
>
All tools are enabled based on policies
All tools available
</ToolTip>
</div>
{agentModeSupported ? (

View file

@ -1,6 +1,6 @@
import {
BarsArrowDownIcon,
PlusIcon,
PencilSquareIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
@ -47,18 +47,13 @@ export default function ResponseActions({
return (
<div className="text-description-muted mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs">
{isLast && ruleGenerationSupported && (
<div
className="mr-1 border-y-0 border-l-0 border-r border-solid pr-2"
<HeaderButtonWithToolTip
tabIndex={-1}
text="Generate rule"
onClick={onGenerateRule}
>
<span className="flex cursor-pointer items-center hover:brightness-125">
<PlusIcon className="mr-1 h-3 w-3" />
<span className="xs:block hidden whitespace-nowrap">
Generate rule
</span>
<span className="xs:hidden block whitespace-nowrap">Rule</span>
</span>
</div>
<PencilSquareIcon className="text-description-muted h-3.5 w-3.5" />
</HeaderButtonWithToolTip>
)}
{isTruncated && (
@ -67,7 +62,7 @@ export default function ResponseActions({
text="Continue generation"
onClick={onContinueGeneration}
>
<BarsArrowDownIcon className="h-3.5 w-3.5" />
<BarsArrowDownIcon className="text-description-muted h-3.5 w-3.5" />
</HeaderButtonWithToolTip>
)}

View file

@ -2,12 +2,9 @@ import { ChatHistoryItem } from "core";
import { renderChatMessage, stripImages } from "core/util/messageContent";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { vscBackground } from "..";
import { useAppSelector } from "../../redux/hooks";
import { selectUIConfig } from "../../redux/slices/configSlice";
import { deleteMessage } from "../../redux/slices/sessionSlice";
import { getFontSize } from "../../util";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import Reasoning from "./Reasoning";
import ResponseActions from "./ResponseActions";
@ -19,16 +16,6 @@ interface StepContainerProps {
isLast: boolean;
}
const ContentDiv = styled.div<{ fontSize?: number }>`
padding: 4px;
padding-left: 6px;
padding-right: 6px;
background-color: ${vscBackground};
font-size: ${getFontSize()}px;
overflow: hidden;
`;
export default function StepContainer(props: StepContainerProps) {
const dispatch = useDispatch();
const [isTruncated, setIsTruncated] = useState(false);
@ -36,12 +23,27 @@ export default function StepContainer(props: StepContainerProps) {
const historyItemAfterThis = useAppSelector(
(state) => state.session.history[props.index + 1],
);
const warningMessage = useAppSelector(
(state) => state.session.warningMessage,
);
const uiConfig = useAppSelector(selectUIConfig);
const hideActionSpace =
const isNextMsgAssistantOrThinking =
historyItemAfterThis?.message.role === "assistant" ||
historyItemAfterThis?.message.role === "thinking";
const hideActions = hideActionSpace || (isStreaming && props.isLast);
historyItemAfterThis?.message.role === "thinking" ||
historyItemAfterThis?.message.role === "tool";
const shouldRenderResponseAction = () => {
if (isNextMsgAssistantOrThinking) {
return false;
}
if (!historyItemAfterThis) {
return !props.item.toolCallStates;
}
return true;
};
useEffect(() => {
if (!isStreaming) {
@ -81,12 +83,9 @@ export default function StepContainer(props: StepContainerProps) {
return (
<div>
<ContentDiv>
<div className="bg-background overflow-hidden p-1 px-1.5">
{uiConfig?.displayRawMarkdown ? (
<pre
className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"
style={{ fontSize: getFontSize() - 2 }}
>
<pre className="text-2xs max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4">
{renderChatMessage(props.item.message)}
</pre>
) : (
@ -101,11 +100,11 @@ export default function StepContainer(props: StepContainerProps) {
</>
)}
{props.isLast && <ThinkingIndicator historyItem={props.item} />}
</ContentDiv>
{/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete */}
{!hideActionSpace && (
</div>
{shouldRenderResponseAction() && (
// We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete
<div className={`mt-2 h-7 transition-opacity duration-300 ease-in-out`}>
{!hideActions && (
{!isStreaming && (
<ResponseActions
isTruncated={isTruncated}
onDelete={onDelete}

View file

@ -3,7 +3,9 @@ import {
MagnifyingGlassMinusIcon,
MagnifyingGlassPlusIcon,
} from "@heroicons/react/24/outline";
// @ts-ignore
import Panzoom from "@panzoom/panzoom";
// @ts-ignore
import mermaid from "mermaid";
import { useEffect, useId, useRef, useState } from "react";
import { useDebouncedEffect } from "../find/useDebounce";

View file

@ -22,7 +22,7 @@ export function ApplyActions(props: ApplyActionsProps) {
switch (props.applyState ? props.applyState.status : null) {
case "streaming":
return (
<div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
<div className="bg-badge flex select-none items-center rounded pl-2 pr-1">
<span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
Applying
<Spinner />
@ -31,18 +31,18 @@ export function ApplyActions(props: ApplyActionsProps) {
);
case "done":
return (
<div className="flex select-none items-center rounded bg-zinc-700 sm:gap-1 md:px-1.5">
<span className="text-lightgray text-center text-xs max-md:hidden">
<div className="bg-badge flex select-none items-center rounded sm:gap-1 md:px-1.5">
<span className="text-lightgray flex items-center text-center text-xs max-md:hidden">
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
</span>
<div className="flex">
<div className="flex items-center">
<ToolbarButtonWithTooltip
data-testid="codeblock-toolbar-reject"
onClick={onClickReject}
tooltipContent={`Reject all (${getMetaKeyLabel()}⇧⌫)`}
>
<XMarkIcon className="text-error h-3.5 w-3.5 hover:brightness-125" />
<XMarkIcon className="text-error h-3.5 w-3.5 flex-shrink-0 hover:brightness-125" />
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
@ -50,7 +50,7 @@ export function ApplyActions(props: ApplyActionsProps) {
onClick={props.onClickAccept}
tooltipContent={`Accept all (${getMetaKeyLabel()}⇧⏎)`}
>
<CheckIcon className="text-success h-3.5 w-3.5 hover:brightness-125" />
<CheckIcon className="text-success h-3.5 w-3.5 flex-shrink-0 hover:brightness-125" />
</ToolbarButtonWithTooltip>
</div>
</div>
@ -68,7 +68,7 @@ export function ApplyActions(props: ApplyActionsProps) {
>
<button
data-testid="codeblock-toolbar-apply"
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
onClick={props.onClickApply}
>
<div className="text-lightgray flex items-center gap-1">

View file

@ -28,7 +28,7 @@ export function ToolbarButtonWithTooltip({
}}
data-tooltip-id={tooltipId}
data-testid={testId}
className="hover:description-muted/30 cursor-pointer select-none rounded bg-transparent px-1 py-0.5 hover:opacity-80"
className="hover:description-muted/30 flex cursor-pointer select-none items-center justify-center rounded bg-transparent px-0.5 py-0.5 hover:opacity-80"
>
{children}
</div>

View file

@ -355,7 +355,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
return (
<StyledMarkdown
contentEditable="false"
fontSize={getFontSize()}
whiteSpace={codeWrapState}
bgColor={props.useParentBackgroundColor ? "" : vscBackground}

View file

@ -1,6 +1,6 @@
import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline";
import { ComponentType, useState } from "react";
import { lightGray, vscBackground } from ".";
import { vscBackground } from ".";
interface ToggleProps {
children: React.ReactNode;
@ -26,31 +26,31 @@ function ToggleDiv({
}}
>
<div
className="flex cursor-pointer items-center justify-start text-xs text-gray-300"
className="text-description flex cursor-pointer items-center justify-start text-xs hover:brightness-125"
onClick={() => setOpen((prev) => !prev)}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
data-testid={testId}
>
<div className="relative mr-1 h-4 w-4">
<div className="relative h-4 w-4">
{Icon && !isHovered && !open ? (
<Icon className={`absolute h-4 w-4 text-[${lightGray}]`} />
<Icon className="absolute h-4 w-4" />
) : (
<>
<ChevronRightIcon
className={`absolute h-4 w-4 transition-all duration-200 ease-in-out text-[${lightGray}] ${
className={`absolute h-4 w-4 transition-all duration-200 ease-in-out ${
open ? "rotate-90 opacity-0" : "rotate-0 opacity-100"
}`}
/>
<ChevronDownIcon
className={`absolute h-4 w-4 transition-all duration-200 ease-in-out text-[${lightGray}] ${
className={`absolute h-4 w-4 transition-all duration-200 ease-in-out ${
open ? "rotate-0 opacity-100" : "-rotate-90 opacity-0"
}`}
/>
</>
)}
</div>
<span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
<span className="ml-1 text-xs transition-colors duration-200">
{title}
</span>
</div>

View file

@ -8,10 +8,12 @@ import { ReactNode } from "react";
import { vscBackground } from "..";
type AlertTypes = "info" | "success" | "warning" | "error";
type AlertSize = "sm" | "lg";
export interface AlertProps {
children?: ReactNode;
type?: AlertTypes;
size?: AlertSize;
}
type AlertConfig = {
@ -35,18 +37,35 @@ const ALERT_CONFIGS: AlertConfig = {
},
};
function Alert({ children, type = "info" }: AlertProps) {
const alertSizes = {
sm: "px-2 py-1.5 rounded border-l-2",
lg: "px-4 py-3 rounded-lg border-l-4",
};
const iconSizes = {
sm: "h-3 w-3",
lg: "h-5 w-5",
};
const spacingSizes = {
sm: "ml-1.5",
lg: "ml-3",
};
function Alert({ children, type = "info", size = "lg" }: AlertProps) {
const { Icon } = ALERT_CONFIGS[type];
return (
<div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none">
<div className="flex items-start">
<div
className={`bg-editor-foreground opacity-70 shadow-none ${alertSizes[size]}`}
>
<div className="flex items-center">
<Icon
className="h-6 min-h-5 w-6 min-w-5"
className={`flex-shrink-0 ${iconSizes[size]}`}
style={{ color: vscBackground }}
/>
<div className="ml-3" style={{ color: vscBackground }}>
<div className={spacingSizes[size]} style={{ color: vscBackground }}>
{children}
</div>
</div>

View file

@ -2,12 +2,14 @@ import { CSSProperties } from "react";
import ReactDOM from "react-dom";
import { ITooltip, Tooltip } from "react-tooltip";
import { vscBackground, vscForeground } from "..";
import { varWithFallback } from "../../styles/theme";
import { fontSize } from "../../util";
// Needed to override styles in react-tooltip
const TooltipStyles: CSSProperties = {
fontSize: fontSize(-2),
fontSize: fontSize(-4),
backgroundColor: vscBackground,
outline: `0.5px solid ${vscForeground}`,
outline: `0.5px solid ${varWithFallback("badge-background")}`,
color: vscForeground,
padding: "4px 8px",
zIndex: 1000,

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