Merge branch 'main' into panyamkeerthana/current_file_context

This commit is contained in:
Keerthana Panyam 2025-08-08 11:51:33 -04:00 • committed by GitHub
commit bbc200f283
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
119 changed files with 4770 additions and 1720 deletions

View file

@ -1,9 +0,0 @@
---
name: Add Continue pun easter eggs
description: Adds an easter egg whenever the "continue" keyword
pattern: "continue"
---
Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase
Do not add a comment if the use of "continue" is not in a code continue statement

View file

@ -1,5 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: Something else? Message us on Discord :)
- name: Have a feature request?
url: https://github.com/continuedev/continue/discussions
about: Upvote existing suggestions or make a new one
- name: Have a question?
url: https://github.com/continuedev/continue/discussions
about: Search for existing questions or ask a new one
- name: Something else? Join the Continue Community
url: https://discord.gg/vapESyrFmJ
about: Join our Discord to ask questions, share thoughts, and more!
about: Join our Discord to chat with our community

View file

@ -1,35 +0,0 @@
---
name: 💪 Improvement suggestion
description: Share how you think Continue could be better
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to share your perspective! We are keen to hear how you think Continue could work better for you.
- type: checkboxes
id: checkboxes
attributes:
label: Validations
description: Before submitting your suggested improvement
options:
- label: I believe this is a way to improve. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions
required: false
- label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement) that requests the same enhancement
required: false
- type: textarea
attributes:
label: Problem
description: Please describe the problem you are aiming to solve with this suggested improvement. If applicable, add a screenshot, gif, or video to better convey your idea.
placeholder: |
Short description
validations:
required: false
- type: textarea
attributes:
label: Solution
description: Please describe what you might want to happen to address this issue. If applicable, add a screenshot, gif, or video to better convey your idea.
placeholder: |
Short description
validations:
required: false

View file

@ -9,10 +9,18 @@ on:
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the JetBrains marketplace"
build_only:
description: "If true, only build the extension for the given channels, don't publish"
required: true
default: false
default: "true"
eap_channel:
description: "If true, build/publish the extension to the EAP channel"
required: true
default: "true"
stable_channel:
description: "If true, build/publish the extension to the Stable channel"
required: true
default: "true"
defaults:
run:
@ -37,50 +45,50 @@ jobs:
echo "should_run=false" >> $GITHUB_OUTPUT
fi
bump-version:
runs-on: ubuntu-latest
needs:
- check_release_name
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
pull-requests: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
# bump-version:
# runs-on: ubuntu-latest
# needs:
# - check_release_name
# if: github.event_name != 'workflow_dispatch' || github.event.inputs.eap_channel == 'true' || github.event.inputs.stable_channel == 'true'
# permissions:
# contents: write
# pull-requests: write
# steps:
# # 0. Setup git
# - name: Checkout
# uses: actions/checkout@v4
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
# - name: Set up Git
# run: |
# git config --local user.email "action@github.com"
# git config --local user.name "GitHub Action"
- name: Create PR branch
run: |
BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
# - name: Create PR branch
# run: |
# BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
# git checkout -b $BRANCH_NAME
# echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
- name: Bump version in gradle.properties
run: |
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
# - name: Bump version in gradle.properties
# run: |
# awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
# rm -rf tmp
# NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
# echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
body: |
Automated PR to bump the JetBrains extension version after successful pre-release publication.
# - name: Create Pull Request
# uses: peter-evans/create-pull-request@v7
# with:
# token: ${{ secrets.CI_GITHUB_TOKEN }}
# commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
# title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
# body: |
# Automated PR to bump the JetBrains extension version after successful pre-release publication.
- Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
branch: ${{ env.BRANCH_NAME }}
base: main
delete-branch: true
# - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
# branch: ${{ env.BRANCH_NAME }}
# base: main
# delete-branch: true
# Prepare and publish the plugin to JetBrains Marketplace repository
build:
@ -140,7 +148,7 @@ jobs:
echo "$CHANGELOG" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier
./gradlew printProductsReleases # prepare list of IDEs for Plugin Verifier
# # Setup Node.js
- name: Use Node.js from .nvmrc
@ -223,9 +231,30 @@ jobs:
# apple-product-id: dev.continue.continue-binary
# options: --options runtime --entitlements entitlements.xml
# Build the plugin if not publishing
- name: Build EAP Plugin (no publish)
if: github.event_name != 'release' && github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only == 'true'
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: eap
run: ./gradlew buildPlugin --info --stacktrace
- name: Build Stable Plugin (no publish)
if: github.event_name != 'release' && github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only == 'true'
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: default
run: ./gradlew buildPlugin --info --stacktrace
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true')
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -235,7 +264,7 @@ jobs:
run: ./gradlew publishPlugin --info --stacktrace
- name: Publish Stable Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true')
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -365,7 +394,7 @@ jobs:
# Download the binary artifact
- name: Download binary artifact
uses: actions/download-artifact@v4
uses: actions/download-artifact@v5
with:
name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }}
path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/
@ -504,7 +533,7 @@ jobs:
uses: actions/cache@v4
with:
path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides
key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }}
key: plugin-verifier-${{ hashFiles('build/printProductsReleases.txt') }}
# Run Verify Plugin task and IntelliJ Plugin Verifier tool
- name: Run Plugin Verification tasks
@ -536,7 +565,7 @@ jobs:
# ./gradlew patchChangelog --release-note="$CHANGELOG"
- name: Download the plugin
uses: actions/download-artifact@v4
uses: actions/download-artifact@v5
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./build/distributions/

View file

@ -120,7 +120,7 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v5
with:
pattern: "*-vsix"
path: vsix-artifacts
@ -156,7 +156,7 @@ jobs:
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v5
with:
pattern: "*-vsix"
path: vsix-artifacts

View file

@ -104,7 +104,7 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v5
with:
pattern: "*-vsix"
path: vsix-artifacts
@ -142,7 +142,7 @@ jobs:
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v5
with:
pattern: "*-vsix"
path: vsix-artifacts

View file

@ -358,6 +358,9 @@ export default async function doLoadConfig(options: {
};
if (newConfig.analytics) {
// FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in
// controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls
// where undefined is :workspaceId
// await TeamAnalytics.setup(
// newConfig.analytics,
// uniqueId,

View file

@ -68,6 +68,7 @@ async function modelConfigToBaseLLM({
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),
nextEdit: model.capabilities?.includes("next_edit"),
},
autocompleteOptions: model.autocompleteOptions,
};

View file

@ -20,8 +20,12 @@ export default class ContinueProxyAnalyticsProvider
event: string,
properties: { [key: string]: any },
): Promise<void> {
if (!this.controlPlaneProxyInfo?.workspaceId) {
return;
}
const url = new URL(
`proxy/analytics/${this.controlPlaneProxyInfo?.workspaceId}/capture`,
`proxy/analytics/${this.controlPlaneProxyInfo.workspaceId}/capture`,
this.controlPlaneProxyInfo?.controlPlaneProxyUrl,
).toString();
void fetch(url, {

View file

@ -580,7 +580,7 @@ export class Core {
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
msg.data,
undefined,
{ withChain: false },
{ withChain: false, usingFullFileDiff: true },
);
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
});

6
core/index.d.ts vendored
View file

@ -1093,7 +1093,10 @@ export interface Tool {
faviconUrl?: string;
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
systemMessageDescription?: {
prefix: string;
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
}
@ -1138,6 +1141,7 @@ export interface BaseCompletionOptions {
export interface ModelCapability {
uploadImage?: boolean;
tools?: boolean;
nextEdit?: boolean;
}
export interface ModelDescription {

View file

@ -1,4 +1,5 @@
import { ChatMessage, ModelCapability, TemplateType } from "../index.js";
import { NEXT_EDIT_MODELS } from "./constants.js";
import {
anthropicTemplateMessages,
@ -173,6 +174,34 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
);
}
// NOTE: When updating this list,
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.MODEL_1,
];
function modelSupportsNextEdit(
capabilities: ModelCapability | undefined,
model: string,
title: string | undefined,
): boolean {
if (capabilities?.nextEdit !== undefined) {
return capabilities.nextEdit;
}
const lower = model.toLowerCase();
if (
MODEL_SUPPORTS_NEXT_EDIT.some(
(modelName) => lower.includes(modelName) || title?.includes(modelName),
)
) {
return true;
}
return false;
}
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
@ -391,4 +420,5 @@ export {
autodetectTemplateType,
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsNextEdit,
};

View file

@ -1,5 +1,5 @@
import { expect, test } from "vitest";
import { autodetectTemplateType } from "./autodetect";
import { describe, expect, it, test } from "vitest";
import { autodetectTemplateType, modelSupportsNextEdit } from "./autodetect";
test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => {
expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
@ -201,3 +201,137 @@ test("autodetectTemplateType handles models with mixed keywords", () => {
expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined
expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2
});
describe("modelSupportsNextEdit", () => {
describe("when capabilities.nextEdit is defined", () => {
it("should return true when capabilities.nextEdit is true", () => {
expect(
modelSupportsNextEdit(
{
nextEdit: true,
},
"any-model",
"Any Title",
),
).toBe(true);
});
it("should return false when capabilities.nextEdit is false", () => {
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"Mercury Coder",
),
).toBe(false);
});
it("should prioritize capabilities over model name matching", () => {
// Even though model name matches, capabilities should take precedence.
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"Mercury Coder",
),
).toBe(false);
});
});
describe("when capabilities.nextEdit is undefined", () => {
it("should return true for mercury-coder-nextedit model (case insensitive)", () => {
expect(
modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined),
).toBe(true);
});
it("should return true for model-1", () => {
expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true);
});
it("should return true when model contains supported model name as substring", () => {
expect(
modelSupportsNextEdit(
undefined,
"provider/mercury-coder-nextedit-v2",
undefined,
),
).toBe(true);
});
it("should return true when title contains supported model name", () => {
expect(
modelSupportsNextEdit(
undefined,
"some-model",
"This is mercury-coder-nextedit model",
),
).toBe(true);
});
it("should return true when title contains model-1", () => {
expect(
modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"),
).toBe(true);
});
it("should return true for unsupported models that have capabilities explicitly set to true", () => {
expect(
modelSupportsNextEdit(
{
nextEdit: true,
},
"gpt-4",
"GPT-4 Model",
),
).toBe(true);
});
it("should return false for unsupported models", () => {
expect(modelSupportsNextEdit(undefined, "gpt-4", "GPT-4 Model")).toBe(
false,
);
});
it("should return false when model and title are both undefined/null", () => {
expect(modelSupportsNextEdit(undefined, "", undefined)).toBe(false);
});
it("should return false when model and title do not contain supported names", () => {
expect(
modelSupportsNextEdit(undefined, "claude-3", "Claude 3 Sonnet"),
).toBe(false);
});
});
describe("edge cases", () => {
it("should handle empty strings", () => {
expect(modelSupportsNextEdit(undefined, "", "")).toBe(false);
});
it("should handle undefined title gracefully", () => {
expect(
modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined),
).toBe(true);
});
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"),
).toBe(true);
});
it("should handle capabilities with other properties", () => {
expect(
modelSupportsNextEdit(
{
nextEdit: true,
uploadImage: false,
},
"unsupported-model",
undefined,
),
).toBe(true);
});
});
});

View file

@ -19,6 +19,11 @@ export enum LLMConfigurationStatuses {
MISSING_ENV_SECRET = "missing-env-secret",
}
export enum NEXT_EDIT_MODELS {
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
MODEL_1 = "model-1",
}
export {
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,

View file

@ -61,7 +61,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
If you need to use multiple tools, you can call call multiple read only tools simultaneously.
If you need to use multiple tools, you can call multiple read only tools simultaneously.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;

View file

@ -5,30 +5,30 @@ describe("OpenAI", () => {
const openai = new OpenAI({
model: "o3-mini",
});
expect(openai.isOSeriesModel("o4-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o3-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o1-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o1")).toBeTruthy();
expect(openai.isOSeriesModel("o3")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o4-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o3-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o1-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o1")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o3")).toBeTruthy();
// artificially correct samples for future models
expect(openai.isOSeriesModel("o5-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o6")).toBeTruthy();
expect(openai.isOSeriesModel("o77")).toBeTruthy();
expect(openai.isOSeriesModel("o54-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o5-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o6")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o77")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o54-mini")).toBeTruthy();
});
test("should identify incorrect o-series models", () => {
const openai = new OpenAI({
model: "o3-mini",
});
expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy();
expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy();
expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("gpt-o4-mini")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("gpt-4.5")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("gpt-4.1")).toBeFalsy();
// artificially wrong samples
expect(openai.isOSeriesModel("os1")).toBeFalsy();
expect(openai.isOSeriesModel("so1")).toBeFalsy();
expect(openai.isOSeriesModel("ao31")).toBeFalsy();
expect(openai.isOSeriesModel("1os")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("os1")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("so1")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("ao31")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("1os")).toBeFalsy();
});
});

View file

@ -36,12 +36,12 @@ function isChatOnlyModel(model: string): boolean {
return model.startsWith("gpt") || model.startsWith("o");
}
const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => {
const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => {
return messages?.map((message: any) => {
if (message?.role === "system") {
return {
...message,
role: "user",
role: "developer",
};
}
@ -77,8 +77,8 @@ class OpenAI extends BaseLLM {
return model;
}
public isOSeriesModel(model?: string): boolean {
return !!model && !!model.match(/^o[0-9]+/);
public isOSeriesOrGpt5Model(model?: string): boolean {
return !!model && (!!model.match(/^o[0-9]+/) || model.includes("gpt-5"));
}
private isFireworksAiModel(model?: string): boolean {
@ -139,13 +139,13 @@ class OpenAI extends BaseLLM {
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
if (this.isOSeriesModel(options.model)) {
if (this.isOSeriesOrGpt5Model(options.model)) {
// a) use max_completion_tokens instead of max_tokens
finalOptions.max_completion_tokens = options.maxTokens;
finalOptions.max_tokens = undefined;
// b) don't support system message
finalOptions.messages = formatMessageForO1(finalOptions.messages);
finalOptions.messages = formatMessageForO1OrGpt5(finalOptions.messages);
}
if (options.model === "o1") {
@ -241,13 +241,13 @@ class OpenAI extends BaseLLM {
body.stop = body.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
if (this.isOSeriesModel(body.model)) {
if (this.isOSeriesOrGpt5Model(body.model)) {
// a) use max_completion_tokens instead of max_tokens
body.max_completion_tokens = body.max_tokens;
body.max_tokens = undefined;
// b) don't support system message
body.messages = formatMessageForO1(body.messages);
body.messages = formatMessageForO1OrGpt5(body.messages);
}
if (body.model === "o1") {

View file

@ -54,15 +54,20 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
},
openai: (model) => {
const lower = model.toLowerCase();
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
if (
model.toLowerCase().startsWith("gpt-4") ||
model.toLowerCase().startsWith("o3")
lower.startsWith("gpt-4") ||
lower.startsWith("gpt-5") ||
lower.startsWith("o3")
) {
return true;
}
if (lower.includes("gpt-oss")) {
return true;
}
// https://ai.google.dev/gemma/docs/capabilities/function-calling
if (model.toLowerCase().startsWith("gemma")) {
if (lower.startsWith("gemma")) {
return true;
}
// firworks-ai https://docs.fireworks.ai/guides/function-calling
@ -174,6 +179,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"firefunction-v2",
"mistral",
"devstral",
"gpt-oss",
].some((part) => modelName.toLowerCase().includes(part))
) {
return true;
@ -237,6 +243,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"openai/o1",
"openai/o3",
"openai/o4",
"openai/gpt-oss",
"anthropic/claude-3",
"anthropic/claude-4",
"microsoft/phi-3",

View file

@ -2,9 +2,14 @@ import Parser from "web-tree-sitter";
import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from "..";
import { getAst } from "../autocomplete/util/ast";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "./constants";
export enum EditableRegionStrategy {
Naive = "naive",
Sliding = "sliding",
Rerank = "rerank",
StaticRerank = "staticRerank",
Static = "static",
@ -17,6 +22,8 @@ export async function getNextEditableRegion(
switch (strategy) {
case EditableRegionStrategy.Naive:
return naiveJump(ctx);
case EditableRegionStrategy.Sliding:
return slidingJump(ctx);
case EditableRegionStrategy.Rerank:
return await rerankJump(ctx);
case EditableRegionStrategy.StaticRerank:
@ -51,6 +58,63 @@ function naiveJump(ctx: any): RangeInFile[] | null {
];
}
// Sliding splits the file using into sliding window.
function slidingJump(ctx: any): RangeInFile[] | null {
const { fileLines, filepath } = ctx;
if (!fileLines || !filepath) {
console.warn("Missing required context for naive jump");
return null;
}
const windowSize =
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN +
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN +
1; // 1 for current line;
if (fileLines.length <= windowSize) {
return [
{
filepath,
range: {
start: { line: 0, character: 0 },
end: {
line: fileLines.length - 1,
character: fileLines[fileLines.length - 1].length,
},
},
},
];
}
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
const ranges: RangeInFile[] = [];
for (
let startLine = 0;
startLine < fileLines.length;
startLine += slidingStep
) {
const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1);
ranges.push({
filepath,
range: {
start: { line: startLine, character: 0 },
end: {
line: endLine,
character: fileLines[endLine].length,
},
},
});
if (endLine >= fileLines.length - 1) {
break;
}
}
return ranges;
}
// A rerank jump splits the current file into chunks.
// Then it uses a rerank model to get the most relevant chunks and their positions.
async function rerankJump(ctx: {

View file

@ -0,0 +1,121 @@
import { RangeInFile } from "..";
import { NextEditProvider } from "./NextEditProvider";
import { NextEditOutcome } from "./types";
interface ProcessedItem {
location: RangeInFile;
outcome: NextEditOutcome; // Result from the model
}
export class PrefetchQueue {
private static instance: PrefetchQueue | null = null;
private unprocessedQueue: RangeInFile[] = [];
private processedQueue: ProcessedItem[] = [];
private prefetchLimit: number;
private abortController: AbortController;
private usingFullFileDiff: boolean = true;
private constructor(prefetchLimit: number = 3) {
this.prefetchLimit = prefetchLimit;
this.abortController = new AbortController();
}
public static getInstance(prefetchLimit: number = 3): PrefetchQueue {
if (!PrefetchQueue.instance) {
PrefetchQueue.instance = new PrefetchQueue(prefetchLimit);
}
return PrefetchQueue.instance;
}
initialize(usingFullFileDiff: boolean) {
this.usingFullFileDiff = usingFullFileDiff;
}
// Queue management methods
enqueueUnprocessed(location: RangeInFile): void {
this.unprocessedQueue.push(location);
}
private dequeueUnprocessed(): RangeInFile | undefined {
return this.unprocessedQueue.shift();
}
enqueueProcessed(item: ProcessedItem): void {
this.processedQueue.push(item);
}
dequeueProcessed(): ProcessedItem | undefined {
return this.processedQueue.shift();
}
// Process items from unprocessed queue
async process(ctx: any): Promise<void> {
while (
this.unprocessedQueue.length > 0 &&
this.processedQueue.length < this.prefetchLimit &&
!this.abortController.signal.aborted
) {
const location = this.dequeueUnprocessed();
if (!location) break;
try {
const outcome =
await NextEditProvider.getInstance().provideInlineCompletionItemsWithChain(
ctx,
location,
this.abortController.signal,
this.usingFullFileDiff,
);
if (!outcome) continue;
this.enqueueProcessed({
location,
outcome,
});
} catch (error) {
if (!this.abortController.signal.aborted) {
// Handle error
console.error("Error processing item:", error);
}
// If aborted, we just stop processing
break;
}
}
}
// Abort all operations
abort(): void {
this.abortController.abort();
this.clear();
// Create a new AbortController for future operations
this.abortController = new AbortController();
}
// Clear all queues
clear(): void {
this.unprocessedQueue = [];
this.processedQueue = [];
}
// Additional helper methods
get unprocessedCount(): number {
return this.unprocessedQueue.length;
}
get processedCount(): number {
return this.processedQueue.length;
}
peekProcessed(): ProcessedItem | undefined {
return this.processedQueue[0];
}
setPreetchLimit(limit: number): void {
this.prefetchLimit = limit;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,259 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IDE, ILLM } from "../index.js";
import { NextEditProvider } from "./NextEditProvider.js";
// Mock the countTokens function
vi.mock("../llm/countTokens.js", () => ({
countTokens: (text: string) => {
// Simple mock that counts 1 token per character for predictable tests
return text.length;
},
}));
// Create a helper function to set up the test context
function createMockHelper(
fileContents: string,
cursorLine: number,
): HelperVars {
const fileLines = fileContents.split("\n");
return {
fileLines,
fileContents,
pos: { line: cursorLine, character: 0 },
modelName: "gpt-4",
lang: { name: "typescript" },
filepath: "test/file.ts",
workspaceUris: ["test/workspace"],
options: {},
input: { completionId: "test-completion-id" },
} as unknown as HelperVars;
}
// TODO: Add more tests for other methods.
describe("_calculateOptimalEditableRegion", () => {
let nextEditProvider: NextEditProvider;
let mockConfigHandler: ConfigHandler;
let mockIde: IDE;
let mockGetLlm: () => Promise<ILLM | undefined>;
let mockOnError: (e: any) => void;
let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction;
beforeEach(() => {
// Create comprehensive mocks for all dependencies
mockConfigHandler = {
loadConfig: vi.fn().mockResolvedValue({ config: {} }),
} as unknown as ConfigHandler;
mockIde = {
readFile: vi.fn().mockResolvedValue(""),
getWorkspaceDirs: vi.fn().mockResolvedValue([]),
getRepoName: vi.fn().mockResolvedValue("test-repo"),
getUniqueId: vi.fn().mockResolvedValue("test-id"),
getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }),
onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => {
// Return a disposable object that does nothing when disposed
return {
dispose: () => {},
};
}),
} as unknown as IDE;
mockGetLlm = vi.fn().mockResolvedValue({
model: "gpt-4",
providerName: "openai",
underlyingProviderName: "openai",
completionOptions: {},
chat: vi.fn(),
});
mockOnError = vi.fn();
mockGetDefinitionsFromLsp = vi.fn();
// Initialize NextEditProvider with mocked dependencies
nextEditProvider = NextEditProvider.initialize(
mockConfigHandler,
mockIde,
mockGetLlm,
mockOnError,
mockGetDefinitionsFromLsp,
"default",
);
// Expose the private method for testing
// This is a bit of a hack, but necessary for testing private methods
(nextEditProvider as any)._calculateOptimalEditableRegion = (
NextEditProvider.prototype as any
)._calculateOptimalEditableRegion.bind(nextEditProvider);
});
// Test cases remain the same as before...
it("should include only the cursor line when it already exceeds token limit", () => {
// Create a mock helper with a very long cursor line (>500 characters)
const longLine = "X".repeat(600);
const helper = createMockHelper(longLine, 0);
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(0);
});
it("should expand symmetrically when possible", () => {
// Create content with identical lines and cursor in the middle
const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each
const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5)
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should expand 5 lines in each direction (total 11 lines) for symmetry
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(10);
});
it("should expand asymmetrically when hitting a file boundary", () => {
// Create content with cursor near the top
const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each
const helper = createMockHelper(lines, 1); // Cursor near the top (line 1)
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should include more lines below since it can't expand much above
expect(result.editableRegionStartLine).toBe(0);
// Should include many more lines below to reach token limit
expect(result.editableRegionEndLine).toBeGreaterThan(10);
});
it("should handle files with varying line lengths", () => {
// Create content with varying line lengths
const fileContents = [
"Short line", // 10 chars
"A".repeat(100), // 100 chars
"Medium length line here", // 24 chars
"B".repeat(200), // 200 chars
"Another typical line of code", // 28 chars
].join("\n");
const helper = createMockHelper(fileContents, 2); // Cursor on the medium line
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should include all lines since total tokens < 500
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(4);
});
it("should respect the token limit and not include too many lines", () => {
// Create content with many small lines (10 chars each)
const lines = Array(600).fill("C".repeat(10)).join("\n");
const helper = createMockHelper(lines, 300); // Cursor in the middle
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Each line is 10 chars = 10 tokens per line with our mock.
// So with 500 token limit, we should get 50 lines total.
// 25 above, 25 below, +1 current
const totalLines =
result.editableRegionEndLine - result.editableRegionStartLine + 1;
expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line)
});
it("should use character approximation when using fourChars heuristic", () => {
// In this test, we're setting up a situation where tiktoken and fourChars would give different results
// Creating 5 lines, each 100 characters
const lines = Array(10).fill("D".repeat(100)).join("\n");
const helper = createMockHelper(lines, 2); // Cursor in the middle
// Mock for tiktoken counting (1 char = 1 token)
//@ts-ignore
const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Mock for fourChars counting (1 token = 4 chars)
// This should include more lines since each line is counted as 25 tokens instead of 100
//@ts-ignore
const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion(
helper,
"fourChars",
);
// The fourChars approach should include more lines since it estimates fewer tokens per line
expect(
fourCharsResult.editableRegionEndLine -
fourCharsResult.editableRegionStartLine,
).toBeGreaterThan(
tokenizerResult.editableRegionEndLine -
tokenizerResult.editableRegionStartLine,
);
});
it("should include the entire file if it's within token limit", () => {
// Create a small file
const smallFile = "Small file\nwith just\na few lines\nof text";
const helper = createMockHelper(smallFile, 1);
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should include all lines
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(3);
});
it("should prioritize balanced context when token limit allows", () => {
// Create content with alternating long and short lines
const fileContents = [
"Short", // 5 chars
"E".repeat(80), // 80 chars
"Also short", // 10 chars
"F".repeat(80), // 80 chars
"Another short one", // 17 chars
"G".repeat(80), // 80 chars
"Final short line", // 16 chars
].join("\n");
const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3)
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should try to include equal number of lines above and below cursor
const linesAbove = result.editableRegionStartLine;
const linesBelow =
helper.fileLines.length - 1 - result.editableRegionEndLine;
// Difference between lines above and below should be minimal
expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1);
});
});

View file

@ -1,22 +1,27 @@
export const IS_NEXT_EDIT_ACTIVE = false;
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|>";
export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const RECENTLY_VIEWED_CODE_SNIPPETS_OPEN =
// Model 1-specific tokens.
export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
// Mercury Coder Next Edit-specific tokens.
export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN =
"<|recently_viewed_code_snippets|>";
export const RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE =
export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE =
"<|/recently_viewed_code_snippets|>";
export const RECENTLY_VIEWED_CODE_SNIPPET_OPEN =
export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN =
"<|recently_viewed_code_snippet|>";
export const RECENTLY_VIEWED_CODE_SNIPPET_CLOSE =
export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE =
"<|/recently_viewed_code_snippet|>";
export const CURRENT_FILE_CONTENT_OPEN = "<|current_file_content|>";
export const CURRENT_FILE_CONTENT_CLOSE = "<|/current_file_content|>";
export const CODE_TO_EDIT_OPEN = "<|code_to_edit|>";
export const CODE_TO_EDIT_CLOSE = "<|/code_to_edit|>";
export const EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>";
export const EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>";
export const CURSOR = "<|cursor|>";
export const MERCURY_CURRENT_FILE_CONTENT_OPEN = "<|current_file_content|>";
export const MERCURY_CURRENT_FILE_CONTENT_CLOSE = "<|/current_file_content|>";
export const MERCURY_CODE_TO_EDIT_OPEN = "<|code_to_edit|>";
export const MERCURY_CODE_TO_EDIT_CLOSE = "<|/code_to_edit|>";
export const MERCURY_EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>";
export const MERCURY_EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>";
export const MERCURY_CURSOR = "<|cursor|>";
export const MERCURY_SYSTEM_PROMPT =
"You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response.";

View file

@ -210,6 +210,9 @@ export function calculateFinalCursorPosition(
oldEditRangeSlice: string,
newEditRangeSlice: string,
) {
if (newEditRangeSlice === "") {
return currCursorPos;
}
// How far away is the current line from the start of the editable region?
const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine;
@ -266,3 +269,171 @@ export function applyCompletionToFile(
return newLines.join("\n");
}
export interface DiffGroup {
startLine: number;
endLine: number;
lines: DiffLine[];
type?: string; // Optional classification of the group
}
/**
* Group diff lines into meaningful sections based on changes
* @param diffLines The diff lines to group
* @param offset Optional line offset to apply to the resulting line numbers
* @param maxGroupSize Optional maximum group size constraint (Mode 2)
* @returns Array of DiffGroup objects representing the changes
*/
export function groupDiffLines(
diffLines: DiffLine[],
offset: number = 0,
maxGroupSize?: number,
): DiffGroup[] {
const groups: DiffGroup[] = [];
const changedAreas = findChangedAreas(diffLines);
for (const area of changedAreas) {
if (maxGroupSize === undefined) {
// Mode 1: Flexible group size.
groups.push(
processFlexibleSizeGroup(diffLines, area.start, area.end, offset),
);
} else {
// Mode 2: Limited group size.
groups.push(
processLimitedSizeGroup(
diffLines,
area.start,
area.end,
maxGroupSize,
offset,
),
);
}
}
return groups;
}
/**
* Find areas of change in the diff lines.
*/
function findChangedAreas(
diffLines: DiffLine[],
): { start: number; end: number }[] {
const changedAreas: { start: number; end: number }[] = [];
let changedAreaStart = -1;
for (let i = 0; i < diffLines.length; i++) {
if (diffLines[i].type !== "same" && changedAreaStart === -1) {
changedAreaStart = i;
} else if (diffLines[i].type === "same" && changedAreaStart !== -1) {
// We've found the end of a changed area.
changedAreas.push({ start: changedAreaStart, end: i - 1 });
changedAreaStart = -1;
}
}
// Handle the last changed area if it extends to the end.
if (changedAreaStart !== -1) {
changedAreas.push({ start: changedAreaStart, end: diffLines.length - 1 });
}
return changedAreas;
}
/**
* Count the number of lines in the old content (excluding "new" lines).
*/
function countOldContentLines(
diffLines: DiffLine[],
startIdx: number,
endIdx: number,
): number {
let count = 0;
for (let i = startIdx; i <= endIdx; i++) {
if (diffLines[i].type !== "new") {
count++;
}
}
return count;
}
/**
* Process a changed area with a limited group size.
*/
function processLimitedSizeGroup(
diffLines: DiffLine[],
start: number,
end: number,
maxGroupSize: number,
offset: number,
): DiffGroup {
// Calculate the starting line in old content.
let oldContentLineStart = countOldContentLines(diffLines, 0, start - 1);
// Track how many lines we have left in our group size budget.
let remainingGroupSize = maxGroupSize;
let currentLine = start;
const lines: DiffLine[] = [];
// Process lines until we hit our size limit or reach the end.
while (currentLine <= end && remainingGroupSize > 0) {
// Add current line to results if we haven't seen it yet.
if (
lines.length === 0 ||
(lines.length > 0 &&
lines[lines.length - 1].line !== diffLines[currentLine].line)
) {
lines.push(diffLines[currentLine]);
}
if (diffLines[currentLine].type === "old") {
currentLine++;
} else if (diffLines[currentLine].type === "same") {
remainingGroupSize--;
currentLine++;
} else if (diffLines[currentLine].type === "new") {
remainingGroupSize--;
currentLine++;
}
}
// Adjust for the last increment.
currentLine--;
// Calculate the end line in old content.
let oldContentLineEnd =
oldContentLineStart +
countOldContentLines(diffLines, start, currentLine) -
1;
return {
startLine: oldContentLineStart + offset,
endLine: oldContentLineEnd + offset,
lines,
};
}
/**
* Process a changed area with flexible sizing.
*/
function processFlexibleSizeGroup(
diffLines: DiffLine[],
start: number,
end: number,
offset: number,
): DiffGroup {
// Calculate the starting line in old content.
let oldContentLineStart = countOldContentLines(diffLines, 0, start - 1);
// Calculate the end line in old content.
let oldContentLineEnd =
oldContentLineStart + countOldContentLines(diffLines, start, end) - 1;
return {
startLine: oldContentLineStart + offset,
endLine: oldContentLineEnd + offset,
lines: diffLines.slice(start, end + 1),
};
}

View file

@ -3,14 +3,14 @@ import { Position } from "../..";
import { SnippetPayload } from "../../autocomplete/snippets";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import {
CURRENT_FILE_CONTENT_CLOSE,
CURRENT_FILE_CONTENT_OPEN,
CURSOR,
EDIT_DIFF_HISTORY_CLOSE,
EDIT_DIFF_HISTORY_OPEN,
RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
USER_CURSOR_IS_HERE_TOKEN,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import {
MercuryTemplateVars,
@ -30,29 +30,22 @@ import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
} from "./utils";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
type TemplateRenderer = (vars: TemplateVars) => string;
export type NextEditModelName =
| "mercury-coder-nextedit"
| "model-1"
| "this field is not used";
const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
"mercury-coder-nextedit": {
template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at [CURRENT FILE PATH].\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
},
"model-1": {
template:
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
},
"this field is not used": {
template: "NEXT_EDIT",
},
};
function templateRendererOfModel(
modelName: NextEditModelName,
modelName: NEXT_EDIT_MODELS,
): TemplateRenderer {
let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
if (!template) {
@ -70,18 +63,7 @@ export async function renderPrompt(
helper: HelperVars,
ctx: any,
): Promise<PromptMetadata> {
let modelName = helper.modelName as NextEditModelName;
if (modelName === "this field is not used") {
return {
prompt: {
role: "user",
content: "NEXT_EDIT",
},
userEdits: "",
userExcerpts: helper.fileContents,
};
}
let modelName = helper.modelName as NEXT_EDIT_MODELS;
// Validate that the modelName is actually a supported model.
if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
@ -91,7 +73,7 @@ export async function renderPrompt(
);
if (matchingModel) {
modelName = matchingModel as NextEditModelName;
modelName = matchingModel as NEXT_EDIT_MODELS;
} else {
throw new Error(
`${helper.modelName} is not yet supported for next edit.`,
@ -111,7 +93,7 @@ export async function renderPrompt(
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
CURSOR,
MERCURY_CURSOR,
);
const mercuryCtx: MercuryTemplateVars = {
@ -125,6 +107,7 @@ export async function renderPrompt(
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
@ -137,7 +120,7 @@ export async function renderPrompt(
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
USER_CURSOR_IS_HERE_TOKEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
);
const model1Ctx: Model1TemplateVars = {

View file

@ -4,21 +4,21 @@ import { SnippetPayload } from "../../autocomplete/snippets";
import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import {
CURRENT_FILE_CONTENT_CLOSE,
CURRENT_FILE_CONTENT_OPEN,
CURSOR,
EDIT_DIFF_HISTORY_CLOSE,
EDIT_DIFF_HISTORY_OPEN,
RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
USER_CURSOR_IS_HERE_TOKEN,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import {
NextEditModelName,
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
} from "./NextEditPromptEngine";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
@ -30,25 +30,19 @@ describe("NextEditPromptEngine", () => {
beforeEach(() => {
mercuryHelper = {
modelName: "inception/mercury-coder-nextedit" as NextEditModelName,
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
model1Helper = {
modelName: "continuedev/model-1" as NextEditModelName,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
testHelper = {
modelName: "this field is not used" as NextEditModelName,
modelName: "continuedev/model-1" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
unsupportedHelper = {
modelName: "mistral/codestral" as NextEditModelName,
modelName: "mistral/codestral" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -75,15 +69,15 @@ describe("NextEditPromptEngine", () => {
expect(result.prompt.role).toBe("user");
const content = result.prompt.content;
expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(content).toContain(CURRENT_FILE_CONTENT_OPEN);
expect(content).toContain(CURRENT_FILE_CONTENT_CLOSE);
expect(content).toContain(EDIT_DIFF_HISTORY_OPEN);
expect(content).toContain(EDIT_DIFF_HISTORY_CLOSE);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
expect(result.userEdits).toBe(ctx.editDiffHistory);
expect(result.userExcerpts).toContain(CURSOR);
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
it("should render model-1 prompt correctly", async () => {
@ -96,17 +90,7 @@ describe("NextEditPromptEngine", () => {
expect(result.prompt.content).toContain("```ts");
expect(result.userEdits).toBe(ctx.userEdits);
expect(result.userExcerpts).toContain(USER_CURSOR_IS_HERE_TOKEN);
});
it("should handle 'this field is not used' model name", async () => {
const result = await renderPrompt(testHelper, ctx);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
expect(result.prompt.content).toBe("NEXT_EDIT");
expect(result.userEdits).toBe("");
expect(result.userExcerpts).toBe(testHelper.fileContents);
expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
});
it("should throw error for unsupported model name", async () => {
@ -209,7 +193,7 @@ describe("NextEditPromptEngine", () => {
describe("insertTokens", () => {
it("should correctly insert cursor and editable region tokens", () => {
const mercuryHelper = {
modelName: "inception/mercury-coder-nextedit" as NextEditModelName,
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -229,7 +213,7 @@ describe("NextEditPromptEngine", () => {
};
return renderPrompt(mercuryHelper, ctx).then((result) => {
expect(result.userExcerpts).toContain(CURSOR);
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
});
});

View file

@ -1,5 +1,9 @@
import { Position, Range } from "../..";
import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants";
import {
MERCURY_CODE_TO_EDIT_CLOSE,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_CURSOR,
} from "../constants";
import { insertCursorToken } from "./utils";
export function recentlyViewedCodeSnippetsBlock(
@ -28,17 +32,17 @@ export function currentFileContentBlock(
const insertedCursorLines = insertCursorToken(
currentFileContentLines,
cursorPosition,
CURSOR,
MERCURY_CURSOR,
);
const instrumentedLines = [
...insertedCursorLines.slice(0, editableRegionStartLine),
CODE_TO_EDIT_OPEN,
MERCURY_CODE_TO_EDIT_OPEN,
...insertedCursorLines.slice(
editableRegionStartLine,
editableRegionEndLine + 1,
),
CODE_TO_EDIT_CLOSE,
MERCURY_CODE_TO_EDIT_CLOSE,
...insertedCursorLines.slice(editableRegionEndLine + 1),
];
@ -48,7 +52,10 @@ export function currentFileContentBlock(
export function editHistoryBlock(
editDiffHistory: string, // could be a singe large unified diff
) {
return editDiffHistory;
// diffHistory is made from createDiff.
// This uses createPatch from npm diff library, which includes an index line and a separator.
// We get rid of these first two lines.
return editDiffHistory.split("\n").slice(2).join("\n");
}
function mercuryNextEditTemplateBuilder(

View file

@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { Position } from "../..";
import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants";
import {
MERCURY_CODE_TO_EDIT_CLOSE,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_CURSOR,
} from "../constants";
import {
currentFileContentBlock,
editHistoryBlock,
@ -51,14 +55,14 @@ describe("mercuryCoderNextEdit", () => {
const expected =
"line 1\n" +
CODE_TO_EDIT_OPEN +
MERCURY_CODE_TO_EDIT_OPEN +
"\n" +
"line 2\n" +
"lin" +
CURSOR +
MERCURY_CURSOR +
"e 3\n" +
"line 4\n" +
CODE_TO_EDIT_CLOSE +
MERCURY_CODE_TO_EDIT_CLOSE +
"\n" +
"line 5";
@ -78,9 +82,9 @@ describe("mercuryCoderNextEdit", () => {
cursorPosition,
);
expect(result).toContain(CODE_TO_EDIT_OPEN);
expect(result).toContain(CURSOR + "line 2");
expect(result).toContain(CODE_TO_EDIT_CLOSE);
expect(result).toContain(MERCURY_CODE_TO_EDIT_OPEN);
expect(result).toContain(MERCURY_CURSOR + "line 2");
expect(result).toContain(MERCURY_CODE_TO_EDIT_CLOSE);
});
it("should handle cursor at the end of a line", () => {
@ -96,15 +100,16 @@ describe("mercuryCoderNextEdit", () => {
cursorPosition,
);
expect(result).toContain("line 2" + CURSOR);
expect(result).toContain("line 2" + MERCURY_CURSOR);
});
});
describe("editHistoryBlock", () => {
it("should return the edit diff history unchanged", () => {
const diffHistory = "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@";
const diffHistory =
"diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@";
const result = editHistoryBlock(diffHistory);
expect(result).toBe(diffHistory);
expect(result).toBe("@@ -1,3 +1,4 @@");
});
it("should handle empty diff history", () => {

View file

@ -1,7 +1,7 @@
import { Position } from "../..";
import {
EDITABLE_REGION_END_TOKEN,
EDITABLE_REGION_START_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange(
const instrumentedLines = [
...lines.slice(0, editableRegionStart),
EDITABLE_REGION_START_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
...lines.slice(editableRegionStart, editableRegionEnd + 1),
EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
...lines.slice(editableRegionEnd + 1),
];

View file

@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import { Position } from "../..";
import {
EDITABLE_REGION_END_TOKEN,
EDITABLE_REGION_START_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
...lines.slice(0, expectedStart),
EDITABLE_REGION_START_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
...lines.slice(expectedStart, expectedEnd + 1),
EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
...lines.slice(expectedEnd + 1),
];
@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
"line 0",
EDITABLE_REGION_START_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
"line 1",
"line 2",
"line 3",
EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
"line 4",
];

View file

@ -1,4 +1,10 @@
import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../";
import {
DiffLine,
Position,
Range,
RangeInFile,
TabAutocompleteOptions,
} from "../";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
export type RecentlyEditedRange = RangeInFile & {
@ -57,6 +63,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
accepted?: boolean;
editableRegionStartLine: number;
editableRegionEndLine: number;
diffLines: DiffLine[];
}
export interface PromptMetadata {
@ -93,4 +100,5 @@ export interface MercuryTemplateVars extends TemplateVars {
recentlyViewedCodeSnippets: string;
currentFileContent: string;
editDiffHistory: string; // could be a singe large unified diff
currentFilePath: string;
}

View file

@ -1,15 +1,13 @@
type NextEditModelName = "mercury-coder-nextedit";
export function isNextEditTest(): boolean {
const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
export function isModelCapableOfNextEdit(modelName: string): boolean {
// In test mode, we can control whether next edit is enabled via environment variable.
if (process.env.NEXT_EDIT_TEST_ENABLED === "false") {
if (enabled === "false") {
return false;
}
if (process.env.NEXT_EDIT_TEST_ENABLED === "true") {
if (enabled === "true") {
return true;
}
const supportedModels: NextEditModelName[] = ["mercury-coder-nextedit"];
return supportedModels.some((supported) => modelName.includes(supported));
return false;
}

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const codebaseTool: Tool = {
type: "function",
@ -28,9 +27,10 @@ export const codebaseTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CodebaseTool,
`To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,
[["query", "How is user authentication handled in this codebase?"]],
),
systemMessageDescription: {
prefix: `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,
exampleArgs: [
["query", "How is user authentication handled in this codebase?"],
],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const createNewFileTool: Tool = {
type: "function",
@ -32,12 +31,11 @@ export const createNewFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateNewFile,
`To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`,
[
systemMessageDescription: {
prefix: `To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`,
exampleArgs: [
["filepath", "path/to/the_file.txt"],
["contents", "Contents of the file"],
],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
const NAME_ARG_DESC =
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')";
@ -61,9 +60,8 @@ export const createRuleBlock: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateRuleBlock,
`Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions.
systemMessageDescription: {
prefix: `Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions.
This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules.
To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments:
- name: ${NAME_ARG_DESC}
@ -72,7 +70,7 @@ To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call a
- globs: ${GLOB_ARG_DESC}
- alwaysApply: ${ALWAYS_APPLY_DESC}
For example:`,
[
exampleArgs: [
["name", "Use PropTypes"],
[
"rule",
@ -85,5 +83,5 @@ For example:`,
["globs", "**/*.js"],
["alwaysApply", "false"],
],
),
},
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
export interface EditToolArgs {
@ -41,19 +40,18 @@ export const editFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.EditExistingFile,
`To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with
systemMessageDescription: {
prefix: `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with
- filepath: the relative filepath to the file.
- changes: ${CHANGES_DESCRIPTION}
Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first.
For example:`,
[
exampleArgs: [
["filepath", "path/to/the_file.ts"],
[
"changes",
"// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...",
],
],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const fetchUrlContentTool: Tool = {
type: "function",
@ -27,9 +26,8 @@ export const fetchUrlContentTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FetchUrlContent,
`To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
[["url", "https://example.com"]],
),
systemMessageDescription: {
prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
exampleArgs: [["url", "https://example.com"]],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const globSearchTool: Tool = {
type: "function",
@ -27,9 +26,8 @@ export const globSearchTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FileGlobSearch,
`To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
[["pattern", "*.py"]],
),
systemMessageDescription: {
prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
exampleArgs: [["pattern", "*.py"]],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const grepSearchTool: Tool = {
type: "function",
@ -28,9 +27,8 @@ export const grepSearchTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.GrepSearch,
`To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
[["query", ".*main_services.*"]],
),
systemMessageDescription: {
prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
exampleArgs: [["query", ".*main_services.*"]],
},
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const lsTool: Tool = {
type: "function",
@ -32,12 +31,11 @@ export const lsTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.LSTool,
`To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,
[
systemMessageDescription: {
prefix: `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,
exampleArgs: [
["dirPath", "path/to/dir"],
["recursive", "false"],
],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const readCurrentlyOpenFileTool: Tool = {
type: "function",
@ -21,10 +20,8 @@ export const readCurrentlyOpenFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadCurrentlyOpenFile,
`To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
systemMessageDescription: {
prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
[],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const readFileTool: Tool = {
type: "function",
@ -27,10 +26,9 @@ export const readFileTool: Tool = {
},
},
},
systemMessageDescription: {
prefix: `To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`,
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadFile,
`To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`,
[["filepath", "path/to/the_file.txt"]],
),
};

View file

@ -1,6 +1,5 @@
import { ConfigDependentToolParams, GetTool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export interface RequestRuleArgs {
name: string;
@ -60,10 +59,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
},
},
},
systemMessageDescription: {
prefix: getRequestRuleSystemMessageDescription(rules),
exampleArgs: [["name", "rule_name"]],
},
defaultToolPolicy: "disabled",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RequestRule,
getRequestRuleSystemMessageDescription(rules),
[["name", "rule_name"]],
),
});

View file

@ -1,7 +1,6 @@
import os from "os";
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
/**
* Get the preferred shell for the current platform
@ -57,12 +56,11 @@ export const runTerminalCommandTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RunTerminalCommand,
`To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
systemMessageDescription: {
prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
${RUN_COMMAND_NOTES}
You can also optionally include the waitForCompletion argument set to false to run the command in the background.
For example, to see the git log, you could respond with:`,
[["command", "git log"]],
),
exampleArgs: [["command", "git log"]],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export interface SearchAndReplaceInFileArgs {
filepath: string;
@ -11,9 +10,6 @@ export interface SearchAndReplaceInFileArgs {
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
const SEARCH_AND_REPLACE_TOOL_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}`;
const SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION =
"The path of the file to modify, relative to the root of the workspace.";
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
[exact content to find]
=======
@ -40,7 +36,8 @@ const SEARCH_AND_REPLACE_RULES = `Critical rules:
* 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]
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`;
* To delete code: Use empty REPLACE section
7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`;
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
@ -73,14 +70,14 @@ export const searchAndReplaceInFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description: SEARCH_AND_REPLACE_TOOL_DESCRIPTION,
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", "diffs"],
properties: {
filepath: {
type: "string",
description: SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION,
description: `The path of the file to modify, relative to the root of the workspace.`,
},
diffs: {
type: "array",
@ -92,33 +89,24 @@ export const searchAndReplaceInFileTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchAndReplaceInFile,
`To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
systemMessageDescription: {
prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
Each block should follow this format:
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
${SEARCH_AND_REPLACE_RULES}
For example, you could respond with:`,
[
exampleArgs: [
["filepath", "path/to/file.ts"],
[
"diffs",
`[
"------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE",
"------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE"
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}",
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}"
]`,
],
],
),
},
defaultToolPolicy: "allowedWithPermission",
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const searchWebTool: Tool = {
type: "function",
@ -27,9 +26,8 @@ export const searchWebTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchWeb,
`To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
[["query", "What is the current weather in San Francisco?"]],
),
systemMessageDescription: {
prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
exampleArgs: [["query", "What is the current weather in San Francisco?"]],
},
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewDiffTool: Tool = {
type: "function",
@ -20,10 +19,8 @@ export const viewDiffTool: Tool = {
properties: {},
},
},
systemMessageDescription: {
prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewDiff,
`To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
[],
),
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewRepoMapTool: Tool = {
type: "function",
@ -20,10 +19,8 @@ export const viewRepoMapTool: Tool = {
properties: {},
},
},
systemMessageDescription: {
prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewRepoMap,
`To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
[],
),
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewSubdirectoryTool: Tool = {
type: "function",
@ -26,10 +25,9 @@ export const viewSubdirectoryTool: Tool = {
},
},
},
systemMessageDescription: {
prefix: `To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`,
exampleArgs: [["directory_path", "path/to/subdirectory"]],
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewSubdirectory,
`To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`,
[["directory_path", "path/to/subdirectory"]],
),
};

View file

@ -1,91 +1,13 @@
import { Tool } from "../..";
import { closeTag } from "./systemToolUtils";
import { SystemMessageToolsFramework } from "./types";
export const TOOL_INSTRUCTIONS_TAG = "<tool_use_instructions>";
export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION";
export const TOOL_DESCRIPTION_TAG = "DESCRIPTION";
const EXAMPLE_DYNAMIC_TOOL = `
\`\`\`tool_definition
TOOL_NAME: example_tool
TOOL_ARG: arg_1 (string, required)
Description of the first argument
END_ARG
TOOL_ARG: arg_2 (number, optional)
END_ARG
\`\`\``.trim();
const EXAMPLE_DYNAMIC_TOOL_CALL = `
\`\`\`tool
TOOL_NAME: example_tool
BEGIN_ARG: arg_1
The value
of arg 1
END_ARG
BEGIN_ARG: arg_2
3
END_ARG
\`\`\``.trim();
export function createSystemMessageExampleCall(
name: string,
instructions: string,
args: Array<[string, string]> = [],
) {
let callExample = `\`\`\`tool
TOOL_NAME: ${name}`;
// Add each argument dynamically
for (const [argName, argValue] of args) {
callExample += `
BEGIN_ARG: ${argName}
${argValue}
END_ARG`;
}
callExample += `
\`\`\``;
return `${instructions.trim()}
${callExample}`;
}
function toolToSystemToolDefinition(tool: Tool): string {
let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`;
if (tool.function.description) {
toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`;
}
if (tool.function.parameters && "properties" in tool.function.parameters) {
for (const [key, value] of Object.entries(
tool.function.parameters.properties as object,
)) {
const isRequired = tool.function.parameters.required?.includes(key);
const requiredText = isRequired ? "required" : "optional";
let argType = "string";
if ("type" in value) {
argType = value.type;
}
let argDescription = "";
if ("description" in value) {
argDescription = value.description;
}
toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`;
if (argDescription) {
toolDefinition += argDescription + "\n";
}
toolDefinition += `END_ARG\n`;
}
}
toolDefinition += `\`\`\``;
return toolDefinition.trim();
}
export const generateToolsSystemMessage = (tools: Tool[]): string => {
export const generateToolsSystemMessage = (
tools: Tool[],
framework: SystemMessageToolsFramework,
): string => {
if (tools.length === 0) {
return "";
}
@ -99,17 +21,17 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => {
const instructions: string[] = [];
instructions.push(TOOL_INSTRUCTIONS_TAG);
instructions.push(
`You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`,
);
instructions.push(
`To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`,
);
instructions.push(framework.systemMessagePrefix);
if (withPredefinedMessage.length > 0) {
instructions.push(`\nThe following tools are available to you:`);
for (const tool of withPredefinedMessage) {
instructions.push(`\n${tool.systemMessageDescription}`);
const definition = framework.createSystemMessageExampleCall(
tool.function.name,
tool.systemMessageDescription!.prefix,
tool.systemMessageDescription!.exampleArgs,
);
instructions.push(`\n${definition}`);
}
}
@ -120,7 +42,7 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => {
for (const tool of tools) {
try {
const definition = toolToSystemToolDefinition(tool);
const definition = framework.toolToSystemToolDefinition(tool);
instructions.push(`\n${definition}`);
} catch (e) {
console.error(
@ -131,35 +53,28 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => {
}
instructions.push(`\nFor example, this tool definition:\n`);
instructions.push(EXAMPLE_DYNAMIC_TOOL);
instructions.push(framework.exampleDynamicToolDefinition);
instructions.push("\nCan be called like this:\n");
instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL);
instructions.push(framework.exampleDynamicToolCall);
}
instructions.push(
`\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`,
);
instructions.push(
`Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`,
);
instructions.push(
`Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`,
);
instructions.push(
`You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`,
);
instructions.push("\n" + framework.systemMessageSuffix);
instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`);
return instructions.join("\n");
};
export function addSystemMessageToolsToSystemMessage(
framework: SystemMessageToolsFramework,
baseSystemMessage: string,
systemMessageTools: Tool[],
): string {
let systemMessage = baseSystemMessage;
if (systemMessageTools.length > 0) {
const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools);
const toolsSystemMessage = generateToolsSystemMessage(
systemMessageTools,
framework,
);
systemMessage += `\n\n${toolsSystemMessage}`;
}

View file

@ -12,22 +12,7 @@ import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
import { SystemMessageToolsFramework } from "./types";
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
@ -46,6 +31,7 @@ function toolCallStateToSystemToolOutput(state: ToolCallState): string {
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
framework: SystemMessageToolsFramework,
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
@ -55,7 +41,7 @@ export function convertToolCallStatesToSystemCallsAndOutput(
parts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
text: framework.toolCallStateToSystemToolCall(state),
})),
);
}

View file

@ -1,19 +1,16 @@
let boundaryTypeIndex = 0;
import { SystemMessageToolsFramework } from "./types";
// Poor models are really bad at following instructions
// Give some leeway in how the initiate
const acceptedToolStarts: [string, string][] = [
["```tool\n", "```tool\n"],
["tool_name:", "```tool\nTOOL_NAME:"],
];
export function detectToolCallStart(buffer: string) {
export function detectToolCallStart(
buffer: string,
toolCallFramework: SystemMessageToolsFramework,
) {
const starts = toolCallFramework.acceptedToolCallStarts;
let modifiedBuffer = buffer;
let isInToolCall = false;
let isInPartialStart = false;
const lowerCaseBuffer = buffer.toLowerCase();
for (let i = 0; i < acceptedToolStarts.length; i++) {
const [start, replacement] = acceptedToolStarts[i];
for (let i = 0; i < starts.length; i++) {
const [start, replacement] = starts[i];
if (lowerCaseBuffer.startsWith(start)) {
// for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive
if (i !== 0) {

View file

@ -1,12 +1,12 @@
import { ChatMessage, PromptLog, TextMessagePart } from "../..";
import { normalizeToMessageParts } from "../../util/messageContent";
import { detectToolCallStart } from "./detectToolCallStart";
import {
getInitialTooLCallParseState,
handleToolCallBuffer,
ToolCallParseState,
} from "./parseSystemToolCall";
import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
import {
getInitialToolCallParseState,
SystemMessageToolsFramework,
ToolCallParseState,
} from "./types";
/*
Function to intercept tool calls in markdown code blocks format from a chat message stream
@ -24,6 +24,7 @@ import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
export async function* interceptSystemToolCalls(
messageGenerator: AsyncGenerator<ChatMessage[], PromptLog | undefined>,
abortController: AbortController,
systemToolFramework: SystemMessageToolsFramework,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
let buffer = "";
let parseState: ToolCallParseState | undefined;
@ -70,19 +71,22 @@ export async function* interceptSystemToolCalls(
buffer += chunk;
if (!parseState) {
const { isInPartialStart, isInToolCall, modifiedBuffer } =
detectToolCallStart(buffer);
detectToolCallStart(buffer, systemToolFramework);
if (isInPartialStart) {
continue;
}
if (isInToolCall) {
parseState = getInitialTooLCallParseState();
parseState = getInitialToolCallParseState();
buffer = modifiedBuffer;
}
}
if (parseState && !parseState.done) {
const delta = handleToolCallBuffer(buffer, parseState);
const delta = systemToolFramework.handleToolCallBuffer(
buffer,
parseState,
);
if (delta) {
yield [
{

View file

@ -1,102 +0,0 @@
import {
AssistantChatMessage,
MessagePart,
ToolCallState,
UserChatMessage,
} from "../..";
import {
normalizeToMessageParts,
renderContextItems,
} from "../../util/messageContent";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
// TODO - include tool call id for parallel. Confuses dumb models
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
if (state.status === "canceled") {
output += CANCELLED_TOOL_CALL_MESSAGE;
} else if (state.output?.length) {
output += renderContextItems(state.output);
} else {
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
}
return output;
}
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
} {
const assistantParts = normalizeToMessageParts(originalAssistantMessage);
if (originalAssistantMessage.toolCalls) {
assistantParts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
})),
);
}
const userParts: MessagePart[] = [];
if (toolCallStates) {
for (const state of toolCallStates) {
userParts.push({
type: "text",
text: toolCallStateToSystemToolOutput(state),
});
}
}
if (userParts.length === 0) {
userParts.push({
type: "text",
text: "No tool output for tool calls",
});
}
const nonEmptyAssistantParts = assistantParts.filter(
(p) => p.type !== "text" || !!p.text,
);
const nonEmptyUserParts = userParts.filter(
(p) => p.type !== "text" || !!p.text,
);
// new message with tool calls moved to content
const assistantMessage: AssistantChatMessage = {
...originalAssistantMessage,
content: nonEmptyAssistantParts,
toolCalls: undefined, // remove tool calls from the assistant message
};
const userMessage: UserChatMessage = {
role: "user",
content: nonEmptyUserParts,
};
return {
assistantMessage,
userMessage,
};
}

View file

@ -1,12 +1,13 @@
import { describe, expect, it } from "vitest";
import { Tool } from "../..";
import { Tool } from "../../..";
import {
TOOL_INSTRUCTIONS_TAG,
addSystemMessageToolsToSystemMessage,
createSystemMessageExampleCall,
generateToolsSystemMessage,
} from "./buildToolsSystemMessage";
import { closeTag } from "./systemToolUtils";
} from "../buildToolsSystemMessage";
import { SystemMessageToolCodeblocksFramework } from ".";
import { closeTag } from "../systemToolUtils";
const SHARED_TOOL_FIELDS = {
displayTitle: "DUD",
@ -15,9 +16,11 @@ const SHARED_TOOL_FIELDS = {
type: "function" as const,
};
const framework = new SystemMessageToolCodeblocksFramework();
describe("createSystemMessageExampleCall", () => {
it("creates a system message example call with no args", () => {
const result = createSystemMessageExampleCall(
const result = framework.createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
);
@ -28,7 +31,7 @@ describe("createSystemMessageExampleCall", () => {
});
it("creates a system message example call with args", () => {
const result = createSystemMessageExampleCall(
const result = framework.createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
[
@ -49,7 +52,7 @@ describe("createSystemMessageExampleCall", () => {
it("handles multiline arg values correctly", () => {
const multilineValue = "value\nwith\nmultiple\nlines";
const result = createSystemMessageExampleCall(
const result = framework.createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
[["arg1", multilineValue]],
@ -63,7 +66,7 @@ describe("createSystemMessageExampleCall", () => {
describe("generateToolsSystemMessage", () => {
it("returns empty string for empty tools array", () => {
const result = generateToolsSystemMessage([]);
const result = generateToolsSystemMessage([], framework);
expect(result).toBe("");
});
@ -81,12 +84,14 @@ describe("generateToolsSystemMessage", () => {
required: [],
},
},
systemMessageDescription: customDescription,
systemMessageDescription: {
prefix: customDescription,
},
...SHARED_TOOL_FIELDS,
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check structure rather than exact text
expect(result).includes(TOOL_INSTRUCTIONS_TAG);
@ -123,7 +128,7 @@ describe("generateToolsSystemMessage", () => {
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check for key elements without requiring exact wording
expect(result).includes(`TOOL_NAME: ${toolName}`);
@ -150,7 +155,9 @@ describe("generateToolsSystemMessage", () => {
required: [],
},
},
systemMessageDescription: customMsg,
systemMessageDescription: {
prefix: customMsg,
},
...SHARED_TOOL_FIELDS,
},
{
@ -172,7 +179,7 @@ describe("generateToolsSystemMessage", () => {
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check for both types of tools
expect(result).includes(customMsg);
@ -202,7 +209,7 @@ describe("generateToolsSystemMessage", () => {
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check for example sections without exact text
expect(result).includes("```tool_definition");
@ -221,7 +228,11 @@ describe("generateToolsSystemMessage", () => {
describe("addSystemMessageToolsToSystemMessage", () => {
it("returns original system message when no tools are provided", () => {
const baseMessage = "This is the base system message";
const result = addSystemMessageToolsToSystemMessage(baseMessage, []);
const result = addSystemMessageToolsToSystemMessage(
framework,
baseMessage,
[],
);
expect(result).toBe(baseMessage);
});
@ -243,7 +254,11 @@ describe("addSystemMessageToolsToSystemMessage", () => {
},
];
const result = addSystemMessageToolsToSystemMessage(baseMessage, tools);
const result = addSystemMessageToolsToSystemMessage(
framework,
baseMessage,
tools,
);
expect(result.startsWith(baseMessage)).toBe(true);
expect(result).includes(TOOL_INSTRUCTIONS_TAG);

View file

@ -1,10 +1,12 @@
import { describe, expect, it } from "vitest";
import { detectToolCallStart } from "./detectToolCallStart";
import { SystemMessageToolCodeblocksFramework } from ".";
import { detectToolCallStart } from "../detectToolCallStart";
describe("detectToolCallStart", () => {
let framework = new SystemMessageToolCodeblocksFramework();
it("detects standard tool call start", () => {
const buffer = "```tool\nTOOL_NAME: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -13,7 +15,7 @@ describe("detectToolCallStart", () => {
it("detects tool_name start without codeblock", () => {
const buffer = "tool_name: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -22,7 +24,7 @@ describe("detectToolCallStart", () => {
it("detects case-insensitive tool call start", () => {
const buffer = "```ToOl\nTOOL_NAME: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -31,7 +33,7 @@ describe("detectToolCallStart", () => {
it("detects case-insensitive tool_name start", () => {
const buffer = "ToOl_NaMe: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -40,7 +42,7 @@ describe("detectToolCallStart", () => {
it("identifies partial tool call start", () => {
const buffer = "```to";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(true);
@ -49,7 +51,7 @@ describe("detectToolCallStart", () => {
it("identifies partial tool_name start", () => {
const buffer = "tool_na";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(true);
@ -58,7 +60,7 @@ describe("detectToolCallStart", () => {
it("does not detect tool call in unrelated text", () => {
const buffer = "This is some regular text.";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(false);
@ -67,7 +69,7 @@ describe("detectToolCallStart", () => {
it("does not detect tool call in similar but different markdown block", () => {
const buffer = "```javascript\nconst x = 10;";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(false);

View file

@ -0,0 +1,120 @@
import { Tool, ToolCallState } from "../../..";
import { SystemMessageToolsFramework } from "../types";
import { handleToolCallBuffer } from "./parseSystemToolCall";
export class SystemMessageToolCodeblocksFramework
implements SystemMessageToolsFramework
{
// Poor models are really bad at following instructions, alternate starts allowed:
acceptedToolCallStarts: [string, string][] = [
["```tool\n", "```tool\n"],
["tool_name:", "```tool\nTOOL_NAME:"],
];
toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
handleToolCallBuffer = handleToolCallBuffer;
toolToSystemToolDefinition(tool: Tool): string {
let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`;
if (tool.function.description) {
toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`;
}
if (tool.function.parameters && "properties" in tool.function.parameters) {
for (const [key, value] of Object.entries(
tool.function.parameters.properties as object,
)) {
const isRequired = tool.function.parameters.required?.includes(key);
const requiredText = isRequired ? "required" : "optional";
let argType = "string";
if ("type" in value) {
argType = value.type;
}
let argDescription = "";
if ("description" in value) {
argDescription = value.description;
}
toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`;
if (argDescription) {
toolDefinition += argDescription + "\n";
}
toolDefinition += `END_ARG\n`;
}
}
toolDefinition += `\`\`\``;
return toolDefinition.trim();
}
systemMessagePrefix = `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.
To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`;
systemMessageSuffix = `If it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions
Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.
Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.
You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`;
exampleDynamicToolDefinition = `
\`\`\`tool_definition
TOOL_NAME: example_tool
TOOL_ARG: arg_1 (string, required)
Description of the first argument
END_ARG
TOOL_ARG: arg_2 (number, optional)
END_ARG
\`\`\``.trim();
exampleDynamicToolCall = `
\`\`\`tool
TOOL_NAME: example_tool
BEGIN_ARG: arg_1
The value
of arg 1
END_ARG
BEGIN_ARG: arg_2
3
END_ARG
\`\`\``.trim();
createSystemMessageExampleCall(
toolName: string,
prefix: string,
exampleArgs: Array<[string, string | number]> = [],
) {
let callExample = `\`\`\`tool
TOOL_NAME: ${toolName}`;
// Add each argument dynamically
for (const [argName, argValue] of exampleArgs) {
callExample += `
BEGIN_ARG: ${argName}
${argValue}
END_ARG`;
}
callExample += `
\`\`\``;
return `${prefix.trim()}
${callExample}`;
}
}

View file

@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it } from "vitest";
import { AssistantChatMessage, ChatMessage, PromptLog } from "../..";
import { interceptSystemToolCalls } from "./interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from ".";
import { AssistantChatMessage, ChatMessage, PromptLog } from "../../..";
import { interceptSystemToolCalls } from "../interceptSystemToolCalls";
describe("interceptSystemToolCalls", () => {
let abortController: AbortController;
let framework = new SystemMessageToolCodeblocksFramework();
beforeEach(() => {
abortController = new AbortController();
@ -27,6 +29,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
let result = await generator.next();
@ -64,6 +67,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
const result = await generator.next();
@ -91,6 +95,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
const result = await generator.next();
@ -116,6 +121,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// First chunk should be normal text
@ -185,6 +191,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// First chunk should be normal text
@ -249,6 +256,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
let result;
@ -271,6 +279,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// Process the first part
@ -300,6 +309,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// Skip to number arg end

View file

@ -1,34 +1,12 @@
import { ToolCallDelta } from "../..";
import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils";
export type ToolCallParseState = {
toolCallId: string;
isOnArgBeginLine: boolean;
currentArgName: string | undefined;
currentArgLines: string[];
processedArgNames: Set<string>;
currentLineIndex: number;
lineChunks: string[][];
done: boolean;
};
export const getInitialTooLCallParseState = (): ToolCallParseState => ({
toolCallId: generateOpenAIToolCallId(),
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
});
import { ToolCallDelta } from "../../..";
import { createDelta } from "../systemToolUtils";
import { ToolCallParseState } from "../types";
/*
Efficiently applies chunks to a tool call state as they come in
Expects chunks to be broken so that new lines and codeblocks are alone
For now, this parser collects entire arg before
This is because support for JSON booleans is tricky otherwise
*/
export function handleToolCallBuffer(
chunk: string,
@ -72,14 +50,14 @@ export function handleToolCallBuffer(
}
return;
default:
if (state.isOnArgBeginLine) {
if (state.isWithinArgStart) {
if (isNewLine) {
const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim();
if (!argName) {
throw new Error("Invalid begin arg line");
}
state.currentArgName = argName;
state.isOnArgBeginLine = false;
state.isWithinArgStart = false;
const argPrefix = state.processedArgNames.size === 0 ? "{" : ",";
return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId);
}
@ -87,8 +65,8 @@ export function handleToolCallBuffer(
if (isNewLine) {
const isEndArgTag = line.match(/end_?arg/i);
if (isEndArgTag) {
let trimmedValue = state.currentArgLines.join("").trim();
state.currentArgLines.length = 0;
let trimmedValue = state.currentArgChunks.join("").trim();
state.currentArgChunks.length = 0;
state.processedArgNames.add(state.currentArgName);
state.currentArgName = undefined;
@ -120,14 +98,14 @@ export function handleToolCallBuffer(
return createDelta("", stringifiedArg, state.toolCallId);
}
} else {
state.currentArgLines.push(line);
state.currentArgChunks.push(line);
}
}
} else {
// Check for entry into arg
const isBeginArgLine = line.match(/begin_?arg:/i);
if (isBeginArgLine) {
state.isOnArgBeginLine = true;
state.isWithinArgStart = true;
}
// Check for exit

View file

@ -1,32 +1,12 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
ToolCallParseState,
getInitialTooLCallParseState,
handleToolCallBuffer,
} from "./parseSystemToolCall";
describe("getInitialTooLCallParseState", () => {
it("returns a properly initialized parse state", () => {
const state = getInitialTooLCallParseState();
expect(state).toEqual({
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
toolCallId: expect.any(String),
});
});
});
import { getInitialToolCallParseState, ToolCallParseState } from "../types";
import { handleToolCallBuffer } from "./parseSystemToolCall";
describe("handleToolCallBuffer", () => {
let state: ToolCallParseState;
beforeEach(() => {
state = getInitialTooLCallParseState();
state = getInitialToolCallParseState();
});
it("handles the ```tool\ntool_name the name", () => {
@ -88,7 +68,7 @@ describe("handleToolCallBuffer", () => {
const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state);
expect(result).toBeUndefined();
expect(state.isOnArgBeginLine).toBe(true);
expect(state.isWithinArgStart).toBe(true);
const newLineResult = handleToolCallBuffer("\n", state);
@ -101,7 +81,7 @@ describe("handleToolCallBuffer", () => {
id: expect.any(String),
});
expect(state.currentArgName).toBe("test_arg");
expect(state.isOnArgBeginLine).toBe(false);
expect(state.isWithinArgStart).toBe(false);
});
it("handles case-insensitive begin arg", () => {
@ -109,7 +89,7 @@ describe("handleToolCallBuffer", () => {
const result = handleToolCallBuffer("begin_arg: test_arg", state);
expect(result).toBeUndefined();
expect(state.isOnArgBeginLine).toBe(true);
expect(state.isWithinArgStart).toBe(true);
const newLineResult = handleToolCallBuffer("\n", state);
@ -135,13 +115,13 @@ describe("handleToolCallBuffer", () => {
const newLineResult2 = handleToolCallBuffer("\n", state);
expect(newLineResult2).toBeUndefined();
expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]);
expect(state.currentArgChunks).toEqual(["line 1\n", "line 2\n"]);
});
it("ends an argument correctly with string value", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["string value"];
state.currentArgChunks = ["string value"];
const result = handleToolCallBuffer("END_ARG", state);
expect(result).toBeUndefined();
@ -163,7 +143,7 @@ describe("handleToolCallBuffer", () => {
it("handles case-insensitive end arg", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["string value"];
state.currentArgChunks = ["string value"];
const result = handleToolCallBuffer("end_arg", state);
expect(result).toBeUndefined();
@ -183,7 +163,7 @@ describe("handleToolCallBuffer", () => {
it("attempts to parse JSON values", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["123"];
state.currentArgChunks = ["123"];
handleToolCallBuffer("END_ARG", state);
const newLineResult = handleToolCallBuffer("\n", state);
@ -201,7 +181,7 @@ describe("handleToolCallBuffer", () => {
it("handles multiple arguments", () => {
// Setup first arg
state.currentLineIndex = 2;
state.isOnArgBeginLine = true;
state.isWithinArgStart = true;
state.lineChunks[2] = ["BEGIN_ARG: first_arg"];
handleToolCallBuffer("\n", state);
@ -213,7 +193,7 @@ describe("handleToolCallBuffer", () => {
expect(state.processedArgNames.has("first_arg")).toBe(true);
// Setup second arg
state.isOnArgBeginLine = true;
state.isWithinArgStart = true;
handleToolCallBuffer("BEGIN_ARG: second_arg", state);
handleToolCallBuffer("\n", state);
handleToolCallBuffer("value2", state);
@ -270,7 +250,7 @@ describe("handleToolCallBuffer", () => {
it("handles JSON array args", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = [
state.currentArgChunks = [
"[\n",
'"------- SEARCH\n',
" subtract(number) {\n",

View file

@ -0,0 +1,51 @@
import { Tool, ToolCallDelta, ToolCallState } from "../..";
import { generateOpenAIToolCallId } from "./systemToolUtils";
export interface SystemMessageToolsFramework {
acceptedToolCallStarts: [string, string][];
toolCallStateToSystemToolCall(state: ToolCallState): string;
handleToolCallBuffer(
chunk: string,
state: ToolCallParseState,
): ToolCallDelta | undefined;
toolToSystemToolDefinition: (tool: Tool) => string;
systemMessagePrefix: string;
systemMessageSuffix: string;
exampleDynamicToolDefinition: string;
exampleDynamicToolCall: string;
createSystemMessageExampleCall(
toolName: string,
prefix: string,
exampleArgs?: Array<[string, string | number]>,
): string;
}
export type ToolCallParseState = {
toolCallId: string;
isWithinArgStart: boolean;
currentArgName: string | undefined;
currentArgChunks: string[];
processedArgNames: Set<string>;
currentLineIndex: number;
lineChunks: string[][];
done: boolean;
};
export const getInitialToolCallParseState = (): ToolCallParseState => ({
toolCallId: generateOpenAIToolCallId(),
isWithinArgStart: false,
currentArgName: undefined,
currentArgChunks: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
});

View file

@ -32,12 +32,15 @@ export function escapeForSVG(text: string): string {
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
.replace(/'/g, "&apos;")
.replace(/\n/g, "\\n") // newlines
.replace(/\t/g, "\\t") // tabs
.replace(/\r/g, "\\r"); // carriage returns
}
export function kebabOfStr(str: string): string {
return str
.replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase
.replace(/([a-z0-9])([A-Z])/g, "$1-$2") // handle camelCase, PascalCase, and numbers followed by uppercase
.replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens
.toLowerCase();
}

186
core/util/text.vitest.ts Normal file
View file

@ -0,0 +1,186 @@
import { describe, expect, it } from "vitest";
import {
capitalizeFirstLetter,
escapeForSVG,
kebabOfStr,
replaceEscapedCharacters,
} from "./text";
describe("capitalizeFirstLetter", () => {
it("should capitalize the first letter of a string", () => {
expect(capitalizeFirstLetter("hello")).toBe("Hello");
expect(capitalizeFirstLetter("world")).toBe("World");
});
it("should handle already capitalized strings", () => {
expect(capitalizeFirstLetter("Hello")).toBe("Hello");
});
it("should handle single character strings", () => {
expect(capitalizeFirstLetter("a")).toBe("A");
expect(capitalizeFirstLetter("A")).toBe("A");
});
it("should handle empty strings", () => {
expect(capitalizeFirstLetter("")).toBe("");
});
it("should handle strings with numbers", () => {
expect(capitalizeFirstLetter("123abc")).toBe("123abc");
});
it("should handle strings with special characters", () => {
expect(capitalizeFirstLetter("@hello")).toBe("@hello");
expect(capitalizeFirstLetter("!world")).toBe("!world");
});
});
describe("replaceEscapedCharacters", () => {
it("should replace escaped newlines with actual newlines", () => {
expect(replaceEscapedCharacters("Hello\\nWorld")).toBe("Hello\nWorld");
});
it("should replace escaped tabs with actual tabs", () => {
expect(replaceEscapedCharacters("Hello\\tWorld")).toBe("Hello\tWorld");
});
it("should replace escaped carriage returns with actual carriage returns", () => {
expect(replaceEscapedCharacters("Hello\\rWorld")).toBe("Hello\rWorld");
});
it("should replace escaped backslashes with actual backslashes", () => {
expect(replaceEscapedCharacters("Hello\\\\World")).toBe("Hello\\World");
});
it("should replace escaped double quotes with actual double quotes", () => {
expect(replaceEscapedCharacters('Hello\\"World')).toBe('Hello"World');
});
it("should replace escaped single quotes with actual single quotes", () => {
expect(replaceEscapedCharacters("Hello\\'World")).toBe("Hello'World");
});
it("should handle multiple escaped characters", () => {
expect(
replaceEscapedCharacters("Line1\\nLine2\\tTabbed\\\\Backslash"),
).toBe("Line1\nLine2\tTabbed\\Backslash");
});
it("should handle strings without escaped characters", () => {
expect(replaceEscapedCharacters("Hello World")).toBe("Hello World");
});
it("should handle empty strings", () => {
expect(replaceEscapedCharacters("")).toBe("");
});
it("should not replace invalid escape sequences", () => {
expect(replaceEscapedCharacters("Hello\\xWorld")).toBe("Hello\\xWorld");
});
});
describe("escapeForSVG", () => {
it("should escape XML entities", () => {
expect(escapeForSVG("Hello & World")).toBe("Hello &amp; World");
expect(escapeForSVG("Hello < World")).toBe("Hello &lt; World");
expect(escapeForSVG("Hello > World")).toBe("Hello &gt; World");
expect(escapeForSVG('Hello "World"')).toBe("Hello &quot;World&quot;");
expect(escapeForSVG("Hello 'World'")).toBe("Hello &apos;World&apos;");
});
it("should escape whitespace characters as literal escape sequences", () => {
expect(escapeForSVG("Hello\nWorld")).toBe("Hello\\nWorld");
expect(escapeForSVG("Hello\tWorld")).toBe("Hello\\tWorld");
expect(escapeForSVG("Hello\rWorld")).toBe("Hello\\rWorld");
});
it("should handle multiple types of characters together", () => {
expect(escapeForSVG("Line1\nLine2&<>\"'Tab\tHere")).toBe(
"Line1\\nLine2&amp;&lt;&gt;&quot;&apos;Tab\\tHere",
);
});
it("should handle empty strings", () => {
expect(escapeForSVG("")).toBe("");
});
it("should handle strings with only whitespace characters", () => {
expect(escapeForSVG("\n\t\r")).toBe("\\n\\t\\r");
});
it("should handle strings without special characters", () => {
expect(escapeForSVG("Hello World 123")).toBe("Hello World 123");
});
it("should handle complex multiline code examples", () => {
const codeExample = `function test() {
console.log("Hello & World");
return true;
}`;
const expected = `function test() {\\n console.log(&quot;Hello &amp; World&quot;);\\n return true;\\n}`;
expect(escapeForSVG(codeExample)).toBe(expected);
});
it("should handle edge case with all escape types", () => {
expect(escapeForSVG("&<>\"'\n\t\r")).toBe(
"&amp;&lt;&gt;&quot;&apos;\\n\\t\\r",
);
});
});
describe("kebabOfStr", () => {
it("should convert camelCase to kebab-case", () => {
expect(kebabOfStr("camelCase")).toBe("camel-case");
expect(kebabOfStr("someVariableName")).toBe("some-variable-name");
});
it("should convert PascalCase to kebab-case", () => {
expect(kebabOfStr("PascalCase")).toBe("pascal-case");
expect(kebabOfStr("SomeClassName")).toBe("some-class-name");
});
it("should convert spaces to hyphens", () => {
expect(kebabOfStr("hello world")).toBe("hello-world");
expect(kebabOfStr("multiple spaces")).toBe("multiple-spaces");
});
it("should convert underscores to hyphens", () => {
expect(kebabOfStr("snake_case")).toBe("snake-case");
expect(kebabOfStr("multiple___underscores")).toBe("multiple-underscores");
});
it("should convert mixed formats", () => {
expect(kebabOfStr("mixedCase_with spaces")).toBe("mixed-case-with-spaces");
expect(kebabOfStr("PascalCase_Snake SPACE")).toBe(
"pascal-case-snake-space",
);
});
it("should handle already kebab-case strings", () => {
expect(kebabOfStr("already-kebab")).toBe("already-kebab");
});
it("should handle strings with numbers", () => {
expect(kebabOfStr("version2Beta")).toBe("version2-beta");
expect(kebabOfStr("test123Case")).toBe("test123-case");
});
it("should handle empty strings", () => {
expect(kebabOfStr("")).toBe("");
});
it("should handle single characters", () => {
expect(kebabOfStr("A")).toBe("a");
expect(kebabOfStr("a")).toBe("a");
});
it("should handle special characters", () => {
expect(kebabOfStr("hello@world")).toBe("hello@world");
expect(kebabOfStr("test.file.name")).toBe("test.file.name");
});
it("should convert to lowercase", () => {
expect(kebabOfStr("UPPERCASE")).toBe("uppercase");
expect(kebabOfStr("MiXeD cAsE")).toBe("mi-xe-d-c-as-e");
});
});

32
docs/custom.css Normal file
View file

@ -0,0 +1,32 @@
/* Custom CSS for Continue documentation */
/* Enable smooth scrolling for anchor links */
html {
scroll-behavior: smooth;
/* Adjust scroll padding to account for fixed header */
scroll-padding-top: 80px;
}
/* Ensure proper spacing for heading anchors */
h1[id],
h2[id],
h3[id],
h4[id],
h5[id],
h6[id] {
scroll-margin-top: 80px;
}
/* Optional: Add a subtle highlight effect when navigating to anchors */
:target {
animation: highlight 2s ease-out;
}
@keyframes highlight {
0% {
background-color: rgba(255, 235, 59, 0.3);
}
100% {
background-color: transparent;
}
}

View file

@ -60,6 +60,11 @@ Example
`config.ts` must export a `modifyConfig` function, like:
<Warning>
The `slashCommands` array shown below is deprecated. For creating custom slash
commands, use [prompt files](./slash-commands) instead.
</Warning>
```ts title="config.ts"
export function modifyConfig(config: Config): Config {
config.slashCommands?.push({
@ -82,4 +87,4 @@ export function modifyConfig(config: Config): Config {
});
return config;
}
```
```

View file

@ -9,7 +9,14 @@ keywords: [slash command, custom commands, step]
Slash commands are shortcuts that can be activated by typing '/' in a chat session (press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)), and selecting from the dropdown.
![slash-commands](/images/slash-commands.png)
Slash commands can be combined with additional instructions, including [context providers](../custom-providers.mdx) or highlighted code.
Slash commands can be combined with additional instructions, including [context providers](../custom-providers) or highlighted code.
<Note>
**Recommended approach**: Use prompt files to create slash commands instead of
the deprecated `config.json` approach. The methods described below provide
better flexibility and are the actively maintained ways to add custom
commands.
</Note>
## Prompts
@ -21,7 +28,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/
It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more.
Learn more about prompt files [here](./prompts.md)
Learn more about prompt files [here](./prompts).
### MCP Server prompts

View file

@ -337,6 +337,9 @@
"apiKey": "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs"
}
},
"custom": {
"css": ["custom.css"]
},
"redirects": [
{
"source": "/hub",

View file

@ -1,5 +1,6 @@
---
title: "Continue CLI (cn)"
description: "Context engineering on the command line"
---
<Warning>Continue CLI (cn) is currently in Alpha</Warning>

View file

@ -175,12 +175,12 @@ The `models` section defines the language models used in your configuration. Mod
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include:
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. Supported capabilities include:
- `tool_use`: Enables function/tool calling support (required for Agent mode)
- `image_input`: Enables image upload and processing support
Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information.
Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly.
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.

View file

@ -1,12 +1,18 @@
---
title: "config.json Reference"
title: "config.json Reference (Deprecated)"
description: "Legacy configuration reference for config.json - use config.yaml instead"
noindex: true
---
<Info>
We recently introduced a new configuration format, `config.yaml`, to replace
`config.json`. See the `config.yaml` reference and migration guide
[here](/reference).
</Info>
<Warning>
**This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use:
- [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands
- [config.yaml](/reference) for configuration
See the `config.yaml` reference and migration guide
[here](/reference).
</Warning>
Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json).

View file

@ -1,6 +1,6 @@
pluginGroup=com.github.continuedev.continueintellijextension
pluginRepositoryUrl=https://github.com/continuedev/continue
pluginVersion=1.0.33
pluginVersion=1.0.34
pluginSinceBuild=223
platformType=IC
platformVersion=2022.3.3

View file

@ -30,27 +30,27 @@
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](./media/agent.gif)
![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](./media/chat.gif)
![chat](docs/images/chat.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](./media/edit.gif)
![edit](docs/images/edit.gif)
## Autocomplete
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
![autocomplete](./media/autocomplete.gif)
![autocomplete](docs/images/autocomplete.gif)
</div>

View file

@ -287,7 +287,6 @@ describe("GUI Test", () => {
}).timeout(DEFAULT_TIMEOUT.MD);
it("should render tool call", async () => {
await GUIActions.toggleToolPolicy(view, "view_diff", 0);
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");
await messageInput.sendKeys(Key.ENTER);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 MiB

View file

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

View file

@ -1,6 +1,10 @@
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { NextEditOutcome } from "core/nextEdit/types";
import * as vscode from "vscode";
import {
HandlerPriority,
SelectionChangeManager,
} from "./SelectionChangeManager";
export interface CompletionDataForAfterJump {
completionId: string;
@ -41,7 +45,9 @@ export class JumpManager {
public dispose() {
// Dispose current decoration.
this._disposables.forEach((d) => d.dispose());
this._disposables.forEach((d) => {
if (d) d.dispose();
});
this._disposables = [];
}
@ -55,11 +61,13 @@ export class JumpManager {
// identical to the completion content,
// then we don't have to jump.
if (completionContent !== undefined) {
console.log("completionContent is not null");
const editor = vscode.window.activeTextEditor;
if (editor) {
try {
const completionLines = completionContent.split("\n");
console.log("completionLines:", completionLines);
// Get document content at jump location spanning multiple lines.
const document = editor.document;
@ -69,51 +77,32 @@ export class JumpManager {
document.lineCount - 1,
);
// Check if we have enough lines in the document to compare.
// First check if we have enough lines in the document
if (endLine - startLine + 1 < completionLines.length) {
// Not enough lines in document, so content can't be identical.
// Proceed to jump!
} else {
// Check the first line first for early exit.
const firstLineText = document.lineAt(startLine).text;
const firstLineSubstring = firstLineText.substring(
nextJumpLocation.character,
console.log(
"Not enough lines in document to match completion content",
);
const firstCompletionLine = completionLines[0];
} else {
let contentMatches = true;
if (!firstLineSubstring.startsWith(firstCompletionLine)) {
// First line doesn't match, so proceed to jump.
} else {
// Check remaining lines if there are any.
if (completionLines.length > 1) {
let fullMatch = true;
// Process remaining lines.
for (let i = 1; i < completionLines.length; i++) {
const documentLine = startLine + i;
if (documentLine <= endLine) {
const lineText = document.lineAt(documentLine).text;
if (lineText !== completionLines[i]) {
fullMatch = false;
break;
}
}
}
if (fullMatch) {
console.log(
"Skipping jump as content is identical at jump location",
);
return false; // Exit early, don't suggest jump.
}
} else {
// Only one line and it matches.
console.log(
"Skipping jump as content is identical at jump location",
);
return false; // Exit early, don't suggest jump.
// Check all lines for match.
for (let i = 0; i < completionLines.length && contentMatches; i++) {
const documentLine = startLine + i;
const lineText = document.lineAt(documentLine).text;
if (lineText !== completionLines[i]) {
contentMatches = false;
console.log(`Line ${i + 1} doesn't match`);
}
}
if (contentMatches) {
console.log(
"Skipping jump as content is identical at jump location",
);
return false; // Exit early, don't suggest jump.
}
}
} catch (error) {
console.error("Error checking content at jump location:", error);
@ -174,28 +163,10 @@ export class JumpManager {
vscode.TextEditorRevealType.InCenter,
);
// Set up a way to detect when the jump is complete.
const disposable = vscode.window.onDidChangeTextEditorSelection(() => {
console.log("_jumpInProgress is false");
this._jumpInProgress = false;
disposable.dispose();
// If there's a completion waiting to be shown after the jump,
// execute the command to show it.
if (this._completionAfterJump) {
vscode.commands.executeCommand(
"continue.showNextEditAfterJump",
this._completionAfterJump,
);
this._completionAfterJump = null;
}
});
// Clean up after timeout if no jump has been made.
setTimeout(() => {
this._jumpInProgress = false;
disposable.dispose();
}, 10000);
// setTimeout(() => {
// this._jumpInProgress = false;
// }, 10000);
return true;
}
@ -211,8 +182,8 @@ export class JumpManager {
// Create a decoration for jump.
this._jumpDecoration = vscode.window.createTextEditorDecorationType({
before: {
contentText: "🦘 Press Tab to jump, Esc to cancel",
color: new vscode.ThemeColor("editorInfo.foreground"),
contentText: "📍 Press Tab to jump, Esc to cancel",
color: new vscode.ThemeColor("editor.foreground"),
backgroundColor: new vscode.ThemeColor("editorInfo.background"),
margin: `0 0 0 4px`,
},
@ -248,8 +219,7 @@ export class JumpManager {
}
// Dispose any active listeners.
this._disposables.forEach((d) => d.dispose());
this._disposables = [];
this.dispose();
// Reset the context.
await vscode.commands.executeCommand(
@ -275,6 +245,7 @@ export class JumpManager {
await this.clearJumpDecoration();
this._jumpAccepted = false;
vscode.commands.executeCommand("editor.action.inlineSuggest.trigger");
}
},
);
@ -328,6 +299,10 @@ export class JumpManager {
return this._jumpInProgress;
}
setJumpInProgress(jumpInProgress: boolean) {
this._jumpInProgress = jumpInProgress;
}
wasJumpJustAccepted(): boolean {
return this._jumpAccepted;
}
@ -335,4 +310,31 @@ export class JumpManager {
setCompletionAfterJump(completionData: CompletionDataForAfterJump): void {
this._completionAfterJump = completionData;
}
clearCompletionAfterJump(): void {
this._completionAfterJump = null;
}
get completionAfterJump() {
return this._completionAfterJump;
}
public registerSelectionChangeHandler(): void {
const manager = SelectionChangeManager.getInstance();
manager.registerListener(
"jumpManager",
async (e, state) => {
if (state.jumpInProgress || state.jumpJustAccepted) {
console.log(
"JumpManager: jump in progress or just accepted, preserving chain",
);
return true;
}
return false;
},
HandlerPriority.HIGH,
);
}
}

View file

@ -8,78 +8,66 @@ import { CompletionDataForAfterJump, JumpManager } from "./JumpManager";
vi.mock("vscode", () => {
return {
window: {
createTextEditorDecorationType: vi.fn(() => ({
dispose: vi.fn(),
})),
activeTextEditor: {
document: {
lineAt: vi.fn((line) => ({
text: "Test line content",
lineNumber: line,
})),
lineCount: 10,
lineAt: vi.fn().mockReturnValue({
text: "Sample line text",
lineNumber: 0,
}),
getText: vi.fn().mockReturnValue("Sample document text"),
lineCount: 5,
},
selection: {
active: { line: 0, character: 0 },
},
setDecorations: vi.fn(),
selection: { active: { line: 0, character: 0 } },
revealRange: vi.fn(),
visibleRanges: [{ start: { line: 0 }, end: { line: 5 } }],
visibleRanges: [
{
start: { line: 0, character: 0 },
end: { line: 4, character: 0 }, // Changed to be within document bounds
},
],
},
onDidChangeTextEditorSelection: vi.fn(() => ({
createTextEditorDecorationType: vi.fn().mockReturnValue({
dispose: vi.fn(),
})),
},
commands: {
executeCommand: vi.fn(),
registerCommand: vi.fn(() => ({
}),
onDidChangeTextEditorSelection: vi.fn().mockReturnValue({
dispose: vi.fn(),
})),
}),
},
Position: class {
line: number;
character: number;
constructor(line: number, character: number) {
this.line = line;
this.character = character;
}
isEqual(other: any): boolean {
constructor(
public line: number,
public character: number,
) {}
isEqual(other: any) {
return this.line === other.line && this.character === other.character;
}
},
Range: class {
start: any;
end: any;
constructor(
startLine: number,
startChar: number,
endLine: number,
endChar: number,
) {
this.start = { line: startLine, character: startChar };
this.end = { line: endLine, character: endChar };
}
},
Selection: class {
anchor: any;
active: any;
constructor(anchor: any, active: any) {
this.anchor = anchor;
this.active = active;
}
constructor(
public anchor: any,
public active: any,
) {}
},
TextEditorDecorationType: class {
dispose: () => void;
constructor() {
this.dispose = vi.fn();
}
Range: class {
constructor(
public start: any,
public end: any,
) {}
},
TextEditorRevealType: {
InCenter: "inCenter",
InCenter: 2,
},
ThemeColor: class {
id: string;
constructor(id: string) {
this.id = id;
}
constructor(public id: string) {}
},
commands: {
executeCommand: vi.fn(),
registerCommand: vi.fn().mockReturnValue({
dispose: vi.fn(),
}),
},
};
});
@ -153,6 +141,7 @@ const createMockNextEditOutcome = (
accepted: true,
editableRegionStartLine: 1,
editableRegionEndLine: 3,
diffLines: [],
// Apply any overrides
...overrides,
@ -166,6 +155,19 @@ describe("JumpManager", () => {
// Reset mocks
vi.resetAllMocks();
// Re-setup the lineAt mock after reset
const mockLineAt = vi.fn().mockReturnValue({
text: "Sample line text",
lineNumber: 0,
});
// Ensure our mock is properly set up after reset
if (vscode.window.activeTextEditor?.document) {
vi.mocked(
vscode.window.activeTextEditor.document.lineAt,
).mockImplementation(mockLineAt);
}
// Clear any existing instance
JumpManager.clearInstance();
@ -216,18 +218,26 @@ describe("JumpManager", () => {
const completionContent = "Test line content";
// Mock document content to match the completion content
vscode.window.activeTextEditor!.document.lineAt = vi.fn(() => ({
const mockLineAt = vi.fn().mockReturnValue({
text: "Test line content",
lineNumber: 3,
})) as any;
});
await jumpManager.suggestJump(
// Override the mock for this specific test
vi.mocked(
vscode.window.activeTextEditor!.document.lineAt,
).mockImplementation(mockLineAt);
const result = await jumpManager.suggestJump(
currentPosition,
nextJumpLocation,
completionContent,
);
// Jump should not be suggested, so decorations should not be created
// Jump should not be suggested
expect(result).toBe(false);
expect(jumpManager.isJumpInProgress()).toBe(false);
// Decorations should not be created
expect(
vscode.window.createTextEditorDecorationType,
).not.toHaveBeenCalled();
@ -260,10 +270,11 @@ describe("JumpManager", () => {
it("should render decoration for jump location outside visible range (above)", async () => {
// Set visible range to be below the jump target
// @ts-ignore
vscode.window.activeTextEditor!.visibleRanges = [
{ start: { line: 5 }, end: { line: 10 } },
];
const mockEditor = vscode.window.activeTextEditor!;
Object.defineProperty(mockEditor, "visibleRanges", {
value: [{ start: { line: 5 }, end: { line: 10 } }],
writable: true,
});
const currentPosition = new vscode.Position(6, 0);
const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above)
@ -273,21 +284,30 @@ describe("JumpManager", () => {
// Should create decoration
expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled();
});
it("should render decoration for jump location within visible range", async () => {
const currentPosition = new vscode.Position(1, 0);
const nextJumpLocation = new vscode.Position(2, 0); // Within visible range (0-4)
await jumpManager.suggestJump(currentPosition, nextJumpLocation);
// Should create decoration
expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled();
// Should reveal range
expect(vscode.window.activeTextEditor!.revealRange).toHaveBeenCalled();
});
});
describe("registerKeyListeners", () => {
it("should register acceptJump command that moves cursor", async () => {
// Setup private method access (this is a bit of a hack for testing private methods)
// Setup private method access
const privateJumpManager = jumpManager as any;
// Mock context
privateJumpManager._jumpDecorationVisible = true;
// Create editor mock
const editor = {
selection: null,
setSelection: vi.fn(),
};
// Create editor mock that matches the expected interface
const editor = vscode.window.activeTextEditor!;
// Create jump position
const jumpPosition = new vscode.Position(3, 5);
@ -296,11 +316,14 @@ describe("JumpManager", () => {
await privateJumpManager.registerKeyListeners(editor, jumpPosition);
// Find the command handler
//@ts-ignore
const commandArgs = vscode.commands.registerCommand.mock.calls.find(
(call: any) => call[0] === "continue.acceptJump",
);
const acceptJumpHandler = commandArgs[1];
const commandArgs = vi
.mocked(vscode.commands.registerCommand)
.mock.calls.find((call: any) => call[0] === "continue.acceptJump");
expect(commandArgs).toBeDefined();
const acceptJumpHandler = commandArgs![1];
// Clear previous executeCommand calls
vi.mocked(vscode.commands.executeCommand).mockClear();
// Call the handler
await acceptJumpHandler();
@ -315,6 +338,10 @@ describe("JumpManager", () => {
"continue.jumpDecorationVisible",
false,
);
// Expect inline suggest to be triggered
expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
"editor.action.inlineSuggest.trigger",
);
});
it("should register rejectJump command that deletes the chain", async () => {
@ -332,17 +359,16 @@ describe("JumpManager", () => {
// Call the private method
await privateJumpManager.registerKeyListeners(
{} as vscode.TextEditor,
vscode.window.activeTextEditor!,
new vscode.Position(0, 0),
);
// Find the command handler
//@ts-ignore
const commandArgs = vscode.commands.registerCommand.mock.calls.find(
(call: any) => call[0] === "continue.rejectJump",
);
const commandArgs = vi
.mocked(vscode.commands.registerCommand)
.mock.calls.find((call: any) => call[0] === "continue.rejectJump");
expect(commandArgs).toBeDefined();
const rejectJumpHandler = commandArgs?.[1];
const rejectJumpHandler = commandArgs![1];
expect(rejectJumpHandler).toBeDefined();
// Reset executeCommand mock
@ -351,9 +377,6 @@ describe("JumpManager", () => {
// Call the handler
await rejectJumpHandler();
// Debug: Log state after calling handler
console.log("mockDeleteChain called:", mockDeleteChain.mock.calls.length);
// Expect NextEditProvider.deleteChain to be called
expect(mockDeleteChain).toHaveBeenCalled();
@ -364,6 +387,44 @@ describe("JumpManager", () => {
false,
);
});
it("should register selection change listener that rejects jump on cursor movement", async () => {
const privateJumpManager = jumpManager as any;
privateJumpManager._jumpDecorationVisible = true;
privateJumpManager._oldCursorPosition = new vscode.Position(1, 0);
const jumpPosition = new vscode.Position(3, 0);
await privateJumpManager.registerKeyListeners(
vscode.window.activeTextEditor!,
jumpPosition,
);
// Find the selection change listener
expect(vscode.window.onDidChangeTextEditorSelection).toHaveBeenCalled();
const selectionChangeListener = vi.mocked(
vscode.window.onDidChangeTextEditorSelection,
).mock.calls[0][0];
// Mock a selection change event that moves cursor away from both old and jump positions
const newPosition = new vscode.Position(5, 0);
const mockEvent = {
textEditor: vscode.window.activeTextEditor!,
kind: undefined, // Can be undefined according to VSCode API
selections: [new vscode.Selection(newPosition, newPosition)], // Use proper Selection object
};
// Reset executeCommand mock
vi.mocked(vscode.commands.executeCommand).mockClear();
// Call the selection change listener
selectionChangeListener(mockEvent);
// Should trigger reject jump
expect(vscode.commands.executeCommand).toHaveBeenCalledWith(
"continue.rejectJump",
);
});
});
describe("setCompletionAfterJump", () => {

View file

@ -10,6 +10,10 @@ import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { getThemeString } from "../util/getTheme";
import {
HandlerPriority,
SelectionChangeManager,
} from "./SelectionChangeManager";
export interface TextApplier {
applyText(
@ -125,6 +129,8 @@ export class NextEditWindowManager {
private finalCursorPos: vscode.Position | null = null;
private isLineDelete: boolean = false;
private context: vscode.ExtensionContext | null = null;
public static getInstance(): NextEditWindowManager {
@ -269,19 +275,45 @@ export class NextEditWindowManager {
newEditRangeSlice: string,
diffLines: DiffLine[],
) {
if (!newEditRangeSlice || !this.shouldRenderTip(editor.document.uri)) {
if (!this.shouldRenderTip(editor.document.uri)) {
return;
}
// Clear any existing decorations first (very important to prevent overlapping).
await this.hideAllNextEditWindows();
this.activeEditor = editor;
this.editableRegionStartLine = editableRegionStartLine;
this.editableRegionEndLine = editableRegionEndLine;
// Store the current tooltip text for accepting later.
this.currentTooltipText = newEditRangeSlice;
// Determine if this is a line deletion case
// NOTE: A simpler approach might be to just delete the line when newEditRangeSlice is "".
// But we opt for the below in case the above note is too naive.
this.isLineDelete = false;
if (
newEditRangeSlice === "" &&
editableRegionStartLine === editableRegionEndLine
) {
// Check if diffLines contains only deletions (no additions).
const onlyDeletions = diffLines.every(
(diff) => diff.type === "old" || diff.type === "same",
);
const hasDeletedLine = diffLines.some((diff) => diff.type === "old");
if (onlyDeletions && hasDeletedLine) {
// Check if the entire line is being deleted (not just characters).
const line = editor.document.lineAt(editableRegionStartLine).text;
const oldLine = oldEditRangeSlice.trim();
if (line.trim() === oldLine || line.trim() === "") {
this.isLineDelete = true;
}
}
}
// How far away is the current line from the start of the editable region?
const lineOffsetAtCursorPos =
currCursorPos.line - this.editableRegionStartLine;
@ -296,22 +328,40 @@ export class NextEditWindowManager {
lineOffsetAtCursorPos,
);
// Calculate the actual line number in the editor by adding the startPos offset
// to the line number from the diff calculation.
this.finalCursorPos = new vscode.Position(
this.editableRegionStartLine + offset.line,
offset.character,
);
// Calculate the final cursor position.
if (this.isLineDelete) {
// For line deletion, position cursor at the end of the previous line.
if (this.editableRegionStartLine > 0) {
const prevLine = editor.document.lineAt(
this.editableRegionStartLine - 1,
);
this.finalCursorPos = new vscode.Position(
this.editableRegionStartLine - 1,
prevLine.text.length,
);
} else {
// If we're deleting the first line, position at the start of the document.
this.finalCursorPos = new vscode.Position(0, 0);
}
} else {
// For normal edits, use the standard calculation.
this.finalCursorPos = new vscode.Position(
this.editableRegionStartLine + offset.line,
offset.character,
);
}
// Create and apply decoration with the text.
await this.renderWindow(
editor,
currCursorPos,
oldEditRangeSlice,
newEditRangeSlice,
this.editableRegionStartLine,
diffLines,
);
if (newEditRangeSlice !== "") {
await this.renderWindow(
editor,
currCursorPos,
oldEditRangeSlice,
newEditRangeSlice,
this.editableRegionStartLine,
diffLines,
);
}
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
@ -343,12 +393,14 @@ export class NextEditWindowManager {
this.currentDecoration.dispose();
this.currentDecoration = null;
this.disposables.forEach((d) => d.dispose());
this.disposables = [];
// Clear the current tooltip text.
this.currentTooltipText = null;
}
if (this.disposables.length > 0) {
this.disposables.forEach((d) => d.dispose());
this.disposables = [];
}
}
public async hideAllNextEditWindowsAndResetCompletionId() {
@ -364,11 +416,14 @@ export class NextEditWindowManager {
this.mostRecentCompletionId = null;
}
/**
* Accept the current next edit suggestion by inserting it at cursor position.
*/
/**
* Accept the current next edit suggestion by inserting it at cursor position.
*/
private async acceptNextEdit() {
if (!this.activeEditor || !this.currentTooltipText) {
if (this.activeEditor === null || this.currentTooltipText === null) {
return;
}
this.accepted = true;
@ -401,16 +456,26 @@ export class NextEditWindowManager {
);
const editRange = new vscode.Range(startPos, endPos);
success = await editor.edit((editBuilder) => {
editBuilder.replace(editRange, text);
});
if (this.isLineDelete) {
// Handle line deletion - extend the range to include the newline.
let lineDeleteRange = editRange;
// Disable inline suggestions temporarily.
// This prevents the race condition between vscode's inline completion provider
// and the next edit window manager's cursor repositioning logic.
// await vscode.workspace
// .getConfiguration()
// .update("editor.inlineSuggest.enabled", false, true);
// If this isn't the last line, extend to include the newline character.
if (this.editableRegionStartLine < editor.document.lineCount - 1) {
lineDeleteRange = new vscode.Range(
startPos,
new vscode.Position(this.editableRegionStartLine + 1, 0),
);
}
success = await editor.edit((editBuilder) => {
editBuilder.delete(lineDeleteRange);
});
} else {
success = await editor.edit((editBuilder) => {
editBuilder.replace(editRange, text);
});
}
}
if (success && this.finalCursorPos) {
@ -421,11 +486,6 @@ export class NextEditWindowManager {
);
}
// Reenable inline suggestions after we move the cursor.
// await vscode.workspace
// .getConfiguration()
// .update("editor.inlineSuggest.enabled", true, true);
// Log with accept = true.
await vscode.commands.executeCommand(
"continue.logNextEditOutcomeAccept",
@ -755,7 +815,6 @@ export class NextEditWindowManager {
// Store the decoration and editor.
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.
const decorationOffsetPosition = this.getDecorationOffsetPosition(
@ -848,6 +907,24 @@ export class NextEditWindowManager {
public hasAccepted() {
return this.accepted;
}
public registerSelectionChangeHandler(): void {
const manager = SelectionChangeManager.getInstance();
manager.registerListener(
"nextEditWindowManager",
async (e, state) => {
if (state.nextEditWindowAccepted) {
console.log(
"NextEditWindowManager: Edit was just accepted, preserving chain",
);
return true;
}
return false;
},
HandlerPriority.CRITICAL,
);
}
}
export default async function setupNextEditWindowManager(

View file

@ -0,0 +1,347 @@
import {
EditableRegionStrategy,
getNextEditableRegion,
} from "core/nextEdit/NextEditEditableRegionCalculator";
import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { localPathOrUriToPath } from "core/util/pathToUri";
import * as vscode from "vscode";
import { VsCodeIde } from "../VsCodeIde";
import { JumpManager } from "./JumpManager";
import { NextEditWindowManager } from "./NextEditWindowManager";
export enum HandlerPriority {
CRITICAL = 5,
HIGH = 4,
NORMAL = 3,
LOW = 2,
FALLBACK = 1,
}
interface StateSnapshot {
nextEditWindowAccepted: boolean;
jumpInProgress: boolean;
jumpJustAccepted: boolean;
lastDocumentChangeTime: number;
isTypingSession: boolean;
document?: vscode.TextDocument;
cursorPosition?: vscode.Position;
}
type SelectionChangeHandler = (
e: vscode.TextEditorSelectionChangeEvent,
state: StateSnapshot,
) => Promise<boolean>;
interface HandlerRegistration {
id: string;
priority: number;
handler: SelectionChangeHandler;
}
/**
* SelectionChangeManager handles cursor movement events in a coordinated way
* to prevent race conditions and ensure consistent behavior across features.
*
* Case 1: User just moves the cursor around.
* - vscode fires onDidChangeTextEditorSelection.
* - State is captured. All fields in StateSnapshot are false.
* - All registered handlers return false.
* - Fallback handler runs, deleting the chain.
*
* Case 2: User accepts a next edit suggestion from a window.
* - vscode fires onDidChangeTextEditorSelection.
* - State is captured. nextEditWindowAccepted is true.
* - NextEditWindowManager's handler returns true.
* - No other handlers run, and edit chain is preserved.
*
* Case 3: User accepts a next edit suggestion from a ghost text.
* - vscode fires onDidChangeTextEditorSelection.
* - State is captured with document and cursorPosition.
* - GhostTextTracker's handler checks if ghost text was accepted at that position.
* - If accepted, handler returns true and edit chain is preserved.
*
* Case 4: User is actively typing code.
* - Each keystroke triggers documentChanged() to update lastDocumentChangeTime.
* - When cursor moves due to typing, onDidChangeTextEditorSelection fires.
* - State is captured with isTypingSession=true and recent lastDocumentChangeTime.
* - Typing session handler detects time since last edit is < TYPING_DELAY.
* - Handler returns true, preserving the edit chain during typing.
*
* Case 5: User performs a jump operation.
* - Jump is initiated, setting jumpInProgress to true.
* - When cursor position changes due to jump, onDidChangeTextEditorSelection fires.
* - State is captured with jumpInProgress=true.
* - JumpManager's handler returns true, preserving the edit chain.
*
* Case 6: User just completed a jump operation.
* - Jump completes, setting jumpJustAccepted to true.
* - onDidChangeTextEditorSelection fires for the final position.
* - State is captured with jumpJustAccepted=true.
* - JumpManager's handler returns true, preserving the edit chain.
*
* Case 7: Rapid cursor movements (debouncing).
* - User rapidly moves cursor (e.g., holding an arrow key).
* - Multiple onDidChangeTextEditorSelection events fire in quick succession.
* - Events within DEBOUNCE_DELAY of each other are queued.
* - Only the most recent event in a rapid sequence gets processed.
* - Prevents performance issues from too many events.
*
* Case 8: Event processing timeout.
* - An event handler takes longer than PROCESSING_TIMEOUT.
* - The timeout promise resolves first, throwing an error.
* - Error is caught, processing state is reset to prevent deadlocks.
* - System can continue processing the next event.
* - NOTE: At the current moment, there should not be any deadlocks, but I'm just making sure.
*
* Case 9: Error in handler.
* - One of the handlers throws an exception.
* - The error is caught and logged.
* - Processing continues with the next handler rather than failing completely.
* - Ensures stability even when individual handlers have problems.
*
* Case 10: Multiple queued events.
* - An event is being processed when new events arrive.
* - New events are added to eventQueue.
* - After current event is processed, queued events are handled sequentially.
* - Ensures all events are processed in the order they were received.
* - NOTE: I'm not sure if we even want to queue these events...
*/
export class SelectionChangeManager {
private static instance: SelectionChangeManager;
private listeners: HandlerRegistration[] = [];
private ide: VsCodeIde | null = null;
private usingFullFileDiff: boolean = true;
// Event bus-related attributes.
private eventQueue: vscode.TextEditorSelectionChangeEvent[] = [];
private lastEventTime = 0;
private isProcessingEvent = false;
private processingTimeout: NodeJS.Timeout | null = null;
// Debounce settings.
private readonly DEBOUNCE_DELAY = 50;
private readonly PROCESSING_TIMEOUT = 500;
// Track typing session state.
private isTypingSession = false;
private typingTimer: NodeJS.Timeout | null = null;
private lastDocumentChangeTime = 0;
private readonly TYPING_SESSION_TIMEOUT = 2000; // ms
private constructor() {}
public static getInstance() {
if (!SelectionChangeManager.instance) {
SelectionChangeManager.instance = new SelectionChangeManager();
}
return SelectionChangeManager.instance;
}
public initialize(ide: VsCodeIde, usingFullFileDiff: boolean): void {
this.ide = ide;
this.usingFullFileDiff = usingFullFileDiff;
// After handling all other listeners, this will delete the chain.
this.registerListener(
"defaultFallbackHandler",
this.defaultFallbackHandler.bind(this),
HandlerPriority.FALLBACK,
);
}
public documentChanged(): void {
this.isTypingSession = true;
this.lastDocumentChangeTime = Date.now();
this.resetTypingSession();
}
private resetTypingSession(): void {
if (this.typingTimer) {
clearTimeout(this.typingTimer);
}
this.typingTimer = setTimeout(() => {
this.isTypingSession = false;
}, this.TYPING_SESSION_TIMEOUT);
}
/**
* Register a listener for the selection change event.
* @param id Unique id for this handler.
* @param handler Function to handle the event.
* @param priority Higher priority runs first.
* @returns Function to unregister this listener.
*/
public registerListener(
id: string,
handler: SelectionChangeHandler,
priority: HandlerPriority = HandlerPriority.NORMAL,
): () => void {
// Remove any existing handler with the same id.
this.listeners = this.listeners.filter((l) => l.id !== id);
// Add the new handler.
this.listeners.push({ id, priority, handler });
// Sort by desc priority.
this.listeners.sort((a, b) => b.priority - a.priority);
// Return the unregister function.
return () => {
this.listeners = this.listeners.filter((l) => l.id !== id);
};
}
/**
* Handle a given selection change event.
* @param e THe selection change event.
*/
public async handleSelectionChange(
e: vscode.TextEditorSelectionChangeEvent,
): Promise<void> {
const now = Date.now();
// Simple debouncing logic.
// Ignore events that come too quickly after the previous one.
// TODO: test this.
if (now - this.lastEventTime < this.DEBOUNCE_DELAY) {
// Replace the queued event with the most recent one.
if (this.eventQueue.length > 0) {
this.eventQueue[this.eventQueue.length - 1] = e;
} else {
this.eventQueue.push(e);
}
return;
}
this.lastEventTime = now;
// Queue this event for later if the manager is already processing an event.
// NOTE: Depending on if we want an event bus or not, do an early return instead.
if (this.isProcessingEvent) {
this.eventQueue.push(e);
return;
}
try {
// Process this event first.
await this.processEventWithTimeout(e);
// Process remaining queued events sequentially.
// NOTE: Depending on if we want an event bus or not, skip this.
while (this.eventQueue.length > 0) {
const nextEvent = this.eventQueue.shift()!;
await this.processEventWithTimeout(nextEvent);
}
} catch (err) {
console.error("Error processing selection change event:", err);
this.isProcessingEvent = false;
if (this.processingTimeout) {
clearTimeout(this.processingTimeout);
this.processingTimeout = null;
}
}
}
/**
* Process a given event with a timeout.
* This is in attempt to prevent deadlocks between events.
* @param e The selection change event.
*/
private async processEventWithTimeout(
e: vscode.TextEditorSelectionChangeEvent,
): Promise<void> {
this.isProcessingEvent = true;
// Set up a timeout to prevent deadlocks.
const timeoutPromise = new Promise<void>((_, reject) => {
this.processingTimeout = setTimeout(() => {
reject(new Error("Selection change event processing timed out"));
}, this.PROCESSING_TIMEOUT);
});
try {
await Promise.race([this.processEvent(e), timeoutPromise]);
} finally {
// Clean up.
if (this.processingTimeout) {
clearTimeout(this.processingTimeout);
this.processingTimeout = null;
}
this.isProcessingEvent = false;
}
}
/**
* Core event processing logic.
* @param e The selection change event.
*/
private async processEvent(
e: vscode.TextEditorSelectionChangeEvent,
): Promise<void> {
const snapshot = this.captureState(e);
for (const { handler } of this.listeners) {
try {
if (await handler(e, snapshot)) {
return;
}
} catch (err) {
console.error("Error in selection change handler:", err);
// Don't break just yet -- go to next handler.
}
}
}
private captureState(
e: vscode.TextEditorSelectionChangeEvent,
): StateSnapshot {
return {
nextEditWindowAccepted:
NextEditWindowManager.isInstantiated() &&
NextEditWindowManager.getInstance().hasAccepted(),
jumpInProgress: JumpManager.getInstance().isJumpInProgress(),
jumpJustAccepted: JumpManager.getInstance().wasJumpJustAccepted(),
lastDocumentChangeTime: this.lastDocumentChangeTime,
isTypingSession: this.isTypingSession,
document: e.textEditor.document,
cursorPosition: e.selections[0].active,
};
}
private async defaultFallbackHandler(
e: vscode.TextEditorSelectionChangeEvent,
state: StateSnapshot,
): Promise<boolean> {
if (!this.ide) {
console.error("IDE not initialized in SelectionChangeManager");
return false;
}
console.log(
"defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection",
);
await NextEditProvider.getInstance().deleteChain();
if (!this.usingFullFileDiff) {
const nextEditableRegions =
(await getNextEditableRegion(EditableRegionStrategy.Static, {
cursorPosition: e.selections[0].anchor,
filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()),
ide: this.ide,
})) ?? [];
// (await getNextEditableRegion(EditableRegionStrategy.Sliding, {
// filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()),
// fileLines: e.textEditor.document.getText().split("\n"),
// })) ?? [];
nextEditableRegions.forEach((region) => {
PrefetchQueue.getInstance().enqueueUnprocessed(region);
});
}
return true;
}
}

View file

@ -0,0 +1,899 @@
import {
EditableRegionStrategy,
getNextEditableRegion,
} from "core/nextEdit/NextEditEditableRegionCalculator";
import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as vscode from "vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { JumpManager } from "./JumpManager";
import { NextEditWindowManager } from "./NextEditWindowManager";
import {
HandlerPriority,
SelectionChangeManager,
} from "./SelectionChangeManager";
// Mock VSCode API
vi.mock("vscode", () => ({
window: {
activeTextEditor: {
document: {
uri: {
toString: vi.fn().mockReturnValue("file:///test/file.ts"),
},
getText: vi.fn().mockReturnValue("Sample document text"),
lineCount: 10,
lineAt: vi.fn((line) => ({
text: "sample line text",
range: {
start: { line, character: 0 },
end: { line, character: 16 },
},
})),
},
selections: [
{
active: { line: 2, character: 5 },
anchor: { line: 2, character: 5 },
},
],
},
},
Position: class {
constructor(
public line: number,
public character: number,
) {}
},
Selection: class {
constructor(
public anchor: any,
public active: any,
) {}
},
}));
// Mock core dependencies
vi.mock("core/nextEdit/NextEditProvider", () => ({
NextEditProvider: {
getInstance: vi.fn(() => ({
deleteChain: vi.fn(),
})),
},
}));
vi.mock("core/nextEdit/NextEditEditableRegionCalculator", () => ({
EditableRegionStrategy: {
Static: "static",
Sliding: "sliding",
},
getNextEditableRegion: vi.fn(),
}));
vi.mock("core/nextEdit/NextEditPrefetchQueue", () => ({
PrefetchQueue: {
getInstance: vi.fn(() => ({
enqueueUnprocessed: vi.fn(),
})),
},
}));
vi.mock("core/util/pathToUri", () => ({
localPathOrUriToPath: vi.fn((uri) => uri.replace("file://", "")),
}));
vi.mock("../VsCodeIde", () => ({
VsCodeIde: vi.fn(),
}));
vi.mock("./JumpManager", () => ({
JumpManager: {
getInstance: vi.fn(() => ({
isJumpInProgress: vi.fn().mockReturnValue(false),
wasJumpJustAccepted: vi.fn().mockReturnValue(false),
})),
},
}));
vi.mock("./NextEditWindowManager", () => ({
NextEditWindowManager: {
isInstantiated: vi.fn().mockReturnValue(false),
getInstance: vi.fn(() => ({
hasAccepted: vi.fn().mockReturnValue(false),
})),
},
}));
describe("SelectionChangeManager", () => {
let selectionChangeManager: SelectionChangeManager;
let mockIde: VsCodeIde;
let mockDeleteChain: ReturnType<typeof vi.fn>;
let mockEnqueueUnprocessed: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.resetAllMocks();
// Setup mock implementations
mockDeleteChain = vi.fn();
mockEnqueueUnprocessed = vi.fn();
vi.mocked(NextEditProvider.getInstance).mockReturnValue({
deleteChain: mockDeleteChain,
} as any);
vi.mocked(PrefetchQueue.getInstance).mockReturnValue({
enqueueUnprocessed: mockEnqueueUnprocessed,
} as any);
vi.mocked(getNextEditableRegion).mockResolvedValue([
{
filepath: "/test/file.ts",
range: {
start: { line: 0, character: 0 },
end: { line: 10, character: 0 },
},
// content: "test content",
// cursorPosition: { line: 2, character: 5 },
},
]);
// Create mock context and webview protocol promise
const mockContext = {
subscriptions: [],
workspaceState: {
get: vi.fn(),
update: vi.fn(),
keys: vi.fn().mockReturnValue([]),
},
globalState: {
get: vi.fn(),
update: vi.fn(),
keys: vi.fn().mockReturnValue([]),
setKeysForSync: vi.fn(),
},
secrets: {
get: vi.fn(),
store: vi.fn(),
delete: vi.fn(),
onDidChange: vi.fn(),
},
extensionUri: { fsPath: "/mock/extension/path" } as any,
extensionPath: "/mock/extension/path",
environmentVariableCollection: {} as any,
asAbsolutePath: vi.fn(),
storageUri: undefined,
storagePath: undefined,
globalStorageUri: { fsPath: "/mock/global/storage" } as any,
globalStoragePath: "/mock/global/storage",
logUri: { fsPath: "/mock/log" } as any,
logPath: "/mock/log",
extensionMode: 1, // Production mode
extension: {} as any,
} as vscode.ExtensionContext;
let resolveWebviewProtocol: any = undefined;
const webviewProtocolPromise = new Promise<VsCodeWebviewProtocol>(
(resolve) => {
resolveWebviewProtocol = resolve;
},
);
// Create VsCodeIde instance with proper constructor arguments
mockIde = new VsCodeIde(webviewProtocolPromise, mockContext);
// Get a fresh instance
selectionChangeManager = SelectionChangeManager.getInstance();
// Clear any existing listeners from previous tests
const privateManager = selectionChangeManager as any;
privateManager.listeners = [];
selectionChangeManager.initialize(mockIde, false);
});
afterEach(() => {
// Clear any timers
vi.clearAllTimers();
// Reset all private state to prevent test interference
const privateManager = selectionChangeManager as any;
privateManager.listeners = [];
privateManager.eventQueue = [];
privateManager.lastEventTime = 0;
privateManager.isProcessingEvent = false;
if (privateManager.processingTimeout) {
clearTimeout(privateManager.processingTimeout);
privateManager.processingTimeout = null;
}
privateManager.isTypingSession = false;
if (privateManager.typingTimer) {
clearTimeout(privateManager.typingTimer);
privateManager.typingTimer = null;
}
privateManager.lastDocumentChangeTime = 0;
});
describe("getInstance", () => {
it("should return the same instance on multiple calls", () => {
const instance1 = SelectionChangeManager.getInstance();
const instance2 = SelectionChangeManager.getInstance();
expect(instance1).toBe(instance2);
});
});
describe("initialize", () => {
it("should set up IDE and register default fallback handler", () => {
const newManager = new (SelectionChangeManager as any)();
const registerSpy = vi.spyOn(newManager, "registerListener");
newManager.initialize(mockIde, true);
expect(registerSpy).toHaveBeenCalledWith(
"defaultFallbackHandler",
expect.any(Function),
HandlerPriority.FALLBACK,
);
});
});
describe("documentChanged", () => {
it("should set typing session to true and update last document change time", () => {
const beforeTime = Date.now();
selectionChangeManager.documentChanged();
const afterTime = Date.now();
// Access private properties for testing
const privateManager = selectionChangeManager as any;
expect(privateManager.isTypingSession).toBe(true);
expect(privateManager.lastDocumentChangeTime).toBeGreaterThanOrEqual(
beforeTime,
);
expect(privateManager.lastDocumentChangeTime).toBeLessThanOrEqual(
afterTime,
);
});
it("should reset typing session timer", () => {
vi.useFakeTimers();
selectionChangeManager.documentChanged();
const privateManager = selectionChangeManager as any;
expect(privateManager.isTypingSession).toBe(true);
// Fast-forward past the typing session timeout
vi.advanceTimersByTime(2100); // TYPING_SESSION_TIMEOUT is 2000ms
expect(privateManager.isTypingSession).toBe(false);
vi.useRealTimers();
});
});
describe("registerListener", () => {
it("should register a handler with correct priority", () => {
const mockHandler = vi.fn();
const unregister = selectionChangeManager.registerListener(
"testHandler",
mockHandler,
HandlerPriority.HIGH,
);
// Access private listeners array
const privateManager = selectionChangeManager as any;
const testHandler = privateManager.listeners.find(
(l: any) => l.id === "testHandler",
);
expect(testHandler).toBeDefined();
expect(testHandler.priority).toBe(HandlerPriority.HIGH);
expect(testHandler.handler).toBe(mockHandler);
// Test unregister function
unregister();
const afterUnregister = privateManager.listeners.find(
(l: any) => l.id === "testHandler",
);
expect(afterUnregister).toBeUndefined();
});
it("should replace existing handler with same id", () => {
const firstHandler = vi.fn();
const secondHandler = vi.fn();
selectionChangeManager.registerListener(
"testHandler",
firstHandler,
HandlerPriority.NORMAL,
);
selectionChangeManager.registerListener(
"testHandler",
secondHandler,
HandlerPriority.HIGH,
);
const privateManager = selectionChangeManager as any;
const handlers = privateManager.listeners.filter(
(l: any) => l.id === "testHandler",
);
expect(handlers).toHaveLength(1);
expect(handlers[0].handler).toBe(secondHandler);
expect(handlers[0].priority).toBe(HandlerPriority.HIGH);
});
it("should sort handlers by priority in descending order", () => {
selectionChangeManager.registerListener(
"low",
vi.fn(),
HandlerPriority.LOW,
);
selectionChangeManager.registerListener(
"critical",
vi.fn(),
HandlerPriority.CRITICAL,
);
selectionChangeManager.registerListener(
"normal",
vi.fn(),
HandlerPriority.NORMAL,
);
const privateManager = selectionChangeManager as any;
const priorities = privateManager.listeners.map((l: any) => l.priority);
// Should be sorted in descending order (CRITICAL=5, NORMAL=3, LOW=2, FALLBACK=1)
expect(priorities[0]).toBe(HandlerPriority.CRITICAL);
expect(priorities[1]).toBe(HandlerPriority.NORMAL);
expect(priorities[2]).toBe(HandlerPriority.LOW);
expect(priorities[3]).toBe(HandlerPriority.FALLBACK);
});
});
describe("handleSelectionChange", () => {
let mockEvent: vscode.TextEditorSelectionChangeEvent;
let mockEvent1: vscode.TextEditorSelectionChangeEvent;
let mockEvent2: vscode.TextEditorSelectionChangeEvent;
let mockEvent3: vscode.TextEditorSelectionChangeEvent;
beforeEach(() => {
mockEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
mockEvent1 = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(0, 0),
new vscode.Position(0, 1),
),
],
kind: undefined,
};
mockEvent2 = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(1, 0),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
mockEvent3 = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 0),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
});
it("should queue event if already processing", async () => {
vi.useFakeTimers();
// Mock Date.now to work with fake timers
const mockDateNow = vi.spyOn(Date, "now");
let currentTime = 1000; // Start at some arbitrary time
mockDateNow.mockImplementation(() => currentTime);
let firstHandlerResolve: (value: boolean) => void;
let handlerCallCount = 0;
const slowHandler = vi.fn().mockImplementation(() => {
handlerCallCount++;
if (handlerCallCount === 1) {
return new Promise<boolean>((resolve) => {
firstHandlerResolve = resolve;
});
} else {
return Promise.resolve(true);
}
});
selectionChangeManager.registerListener(
"slowHandler",
slowHandler,
HandlerPriority.HIGH,
);
// First event - should bypass debouncing and start processing immediately
const firstEventPromise =
selectionChangeManager.handleSelectionChange(mockEvent1);
// Advance time to simulate the first event being processed
currentTime += 10; // Small increment to simulate processing start
vi.advanceTimersByTime(10);
expect(slowHandler).toHaveBeenCalledTimes(1);
// Second event comes quickly (within DEBOUNCE_DELAY of 50ms)
currentTime += 10; // Total elapsed: 10ms (< 50ms DEBOUNCE_DELAY)
const secondEventPromise =
selectionChangeManager.handleSelectionChange(mockEvent2);
// The second event should be queued due to isProcessingEvent = true, not debouncing
expect(slowHandler).toHaveBeenCalledTimes(1); // Still only called once
// Third event comes within debounce window, replacing the second event.
currentTime += 10; // Total elapsed: 30ms (< 50ms DEBOUNCE_DELAY)
const thirdEventPromise =
selectionChangeManager.handleSelectionChange(mockEvent3);
// Still should only be called once
expect(slowHandler).toHaveBeenCalledTimes(1);
// Now resolve the first handler to allow queued events to process
firstHandlerResolve!(true);
// Advance time to allow any pending timers to resolve
vi.advanceTimersByTime(100);
// Wait for all events to complete
await Promise.all([
firstEventPromise,
secondEventPromise,
thirdEventPromise,
]);
// Should have been called twice total:
// - Once for the first event
// - Once for the last queued event (debouncing replaces earlier queued events)
expect(slowHandler).toHaveBeenCalledTimes(2);
mockDateNow.mockRestore();
vi.useRealTimers();
});
it("should implement debouncing for rapid events", async () => {
vi.useFakeTimers();
const mockHandler = vi.fn().mockResolvedValue(true);
selectionChangeManager.registerListener(
"testHandler",
mockHandler,
HandlerPriority.HIGH,
);
// Fire multiple events rapidly
selectionChangeManager.handleSelectionChange(mockEvent);
selectionChangeManager.handleSelectionChange(mockEvent);
selectionChangeManager.handleSelectionChange(mockEvent);
// Only the last event should be queued due to debouncing
const privateManager = selectionChangeManager as any;
expect(privateManager.eventQueue).toHaveLength(1);
vi.useRealTimers();
});
it("should handle timeout for slow processing", async () => {
vi.useFakeTimers();
const slowHandler = vi.fn().mockImplementation(
() =>
new Promise((resolve) =>
setTimeout(() => {
console.log("Slow handler resolving");
resolve(true);
}, 1000),
),
);
selectionChangeManager.registerListener(
"slowHandler",
slowHandler,
HandlerPriority.HIGH,
);
const consoleErrorSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
// Start processing and advance past timeout
console.log("Starting event processing");
const eventPromise =
selectionChangeManager.handleSelectionChange(mockEvent);
console.log("Advancing timers by 600ms");
vi.advanceTimersByTime(700); // PROCESSING_TIMEOUT is 500ms
try {
await eventPromise;
console.log("Event promise resolved successfully");
} catch (error) {
console.log("Event promise rejected:", error);
}
console.log("Console error calls:", consoleErrorSpy.mock.calls);
expect(consoleErrorSpy).toHaveBeenCalled();
consoleErrorSpy.mockRestore();
vi.useRealTimers();
});
it("should handle errors in handlers gracefully", async () => {
const errorHandler = vi
.fn()
.mockRejectedValue(new Error("Handler error"));
const goodHandler = vi.fn().mockResolvedValue(true);
selectionChangeManager.registerListener(
"errorHandler",
errorHandler,
HandlerPriority.HIGH,
);
selectionChangeManager.registerListener(
"goodHandler",
goodHandler,
HandlerPriority.NORMAL,
);
const consoleErrorSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
await selectionChangeManager.handleSelectionChange(mockEvent);
expect(errorHandler).toHaveBeenCalled();
expect(goodHandler).toHaveBeenCalled();
expect(consoleErrorSpy).toHaveBeenCalledWith(
"Error in selection change handler:",
expect.any(Error),
);
consoleErrorSpy.mockRestore();
});
});
describe("captureState", () => {
beforeEach(() => {
vi.resetAllMocks();
// Explicitly set up the mocks. For some reason the toplevel mock leaves these as undefined.
vi.mocked(NextEditWindowManager.isInstantiated).mockReturnValue(false);
vi.mocked(NextEditWindowManager.getInstance).mockReturnValue({
hasAccepted: vi.fn().mockReturnValue(false),
} as any);
vi.mocked(JumpManager.getInstance).mockReturnValue({
isJumpInProgress: vi.fn().mockReturnValue(false),
wasJumpJustAccepted: vi.fn().mockReturnValue(false),
} as any);
});
it("should capture current state snapshot", () => {
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
// Setup some state
selectionChangeManager.documentChanged();
const privateManager = selectionChangeManager as any;
const state = privateManager.captureState(mockEvent);
expect(state).toEqual({
nextEditWindowAccepted: false,
jumpInProgress: false,
jumpJustAccepted: false,
lastDocumentChangeTime: expect.any(Number),
isTypingSession: true,
document: mockEvent.textEditor.document,
cursorPosition: mockEvent.selections[0].active,
});
});
it("should reflect NextEditWindowManager acceptance state", () => {
vi.mocked(NextEditWindowManager.isInstantiated).mockReturnValue(true);
vi.mocked(NextEditWindowManager.getInstance).mockReturnValue({
hasAccepted: vi.fn().mockReturnValue(true),
} as any);
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
const privateManager = selectionChangeManager as any;
const state = privateManager.captureState(mockEvent);
expect(state.nextEditWindowAccepted).toBe(true);
});
it("should reflect JumpManager state", () => {
vi.mocked(JumpManager.getInstance).mockReturnValue({
isJumpInProgress: vi.fn().mockReturnValue(true),
wasJumpJustAccepted: vi.fn().mockReturnValue(true),
} as any);
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
const privateManager = selectionChangeManager as any;
const state = privateManager.captureState(mockEvent);
expect(state.jumpInProgress).toBe(true);
expect(state.jumpJustAccepted).toBe(true);
});
});
describe("defaultFallbackHandler", () => {
it("should call deleteChain on NextEditProvider", async () => {
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: {
...vscode.window.activeTextEditor!,
document: {
//@ts-ignore
uri: {
toString: vi.fn().mockReturnValue("file:///test/file.ts"),
},
},
},
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
const mockState = {
nextEditWindowAccepted: false,
jumpInProgress: false,
jumpJustAccepted: false,
lastDocumentChangeTime: Date.now(),
isTypingSession: false,
document: mockEvent.textEditor.document,
cursorPosition: mockEvent.selections[0].active,
};
const privateManager = selectionChangeManager as any;
const result = await privateManager.defaultFallbackHandler(
mockEvent,
mockState,
);
expect(mockDeleteChain).toHaveBeenCalled();
expect(result).toBe(true);
});
it("should handle missing IDE gracefully", async () => {
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
const mockState = {
nextEditWindowAccepted: false,
jumpInProgress: false,
jumpJustAccepted: false,
lastDocumentChangeTime: Date.now(),
isTypingSession: false,
document: mockEvent.textEditor.document,
cursorPosition: mockEvent.selections[0].active,
};
const privateManager = selectionChangeManager as any;
privateManager.ide = null;
const consoleErrorSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
const result = await privateManager.defaultFallbackHandler(
mockEvent,
mockState,
);
expect(consoleErrorSpy).toHaveBeenCalledWith(
"IDE not initialized in SelectionChangeManager",
);
expect(result).toBe(false);
consoleErrorSpy.mockRestore();
});
it("should prefetch editable regions when not using full file diff", async () => {
// Initialize with usingFullFileDiff = false
const newManager = SelectionChangeManager.getInstance();
newManager.initialize(mockIde, false);
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: {
...vscode.window.activeTextEditor!,
document: {
//@ts-ignore
uri: {
toString: vi.fn().mockReturnValue("file:///test/file.ts"),
},
},
},
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
const mockState = {
nextEditWindowAccepted: false,
jumpInProgress: false,
jumpJustAccepted: false,
lastDocumentChangeTime: Date.now(),
isTypingSession: false,
document: mockEvent.textEditor.document,
cursorPosition: mockEvent.selections[0].active,
};
const mockRegions = [
{
filepath: "/test/file.ts",
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
// content: "test content",
// cursorPosition: { line: 2, character: 5 },
},
];
vi.mocked(getNextEditableRegion).mockResolvedValue(mockRegions);
const privateManager = newManager as any;
await privateManager.defaultFallbackHandler(mockEvent, mockState);
expect(getNextEditableRegion).toHaveBeenCalledWith(
EditableRegionStrategy.Static,
{
cursorPosition: mockEvent.selections[0].anchor,
filepath: "/test/file.ts",
ide: mockIde,
},
);
expect(mockEnqueueUnprocessed).toHaveBeenCalledWith(mockRegions[0]);
});
it("should skip prefetching when using full file diff", async () => {
// Initialize with usingFullFileDiff = true
const newManager = SelectionChangeManager.getInstance();
newManager.initialize(mockIde, true);
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
const mockState = {
nextEditWindowAccepted: false,
jumpInProgress: false,
jumpJustAccepted: false,
lastDocumentChangeTime: Date.now(),
isTypingSession: false,
document: mockEvent.textEditor.document,
cursorPosition: mockEvent.selections[0].active,
};
const privateManager = newManager as any;
await privateManager.defaultFallbackHandler(mockEvent, mockState);
expect(getNextEditableRegion).not.toHaveBeenCalled();
expect(mockEnqueueUnprocessed).not.toHaveBeenCalled();
});
});
describe("handler execution order", () => {
it("should execute handlers in priority order and stop on first true return", async () => {
const handler1 = vi.fn().mockResolvedValue(false);
const handler2 = vi.fn().mockResolvedValue(true);
const handler3 = vi.fn().mockResolvedValue(false);
const fallbackHandler = vi.fn().mockResolvedValue(true);
selectionChangeManager.registerListener(
"handler1",
handler1,
HandlerPriority.CRITICAL,
);
selectionChangeManager.registerListener(
"handler2",
handler2,
HandlerPriority.HIGH,
);
selectionChangeManager.registerListener(
"handler3",
handler3,
HandlerPriority.NORMAL,
);
const mockEvent: vscode.TextEditorSelectionChangeEvent = {
textEditor: vscode.window.activeTextEditor!,
selections: [
new vscode.Selection(
new vscode.Position(2, 5),
new vscode.Position(2, 5),
),
],
kind: undefined,
};
await selectionChangeManager.handleSelectionChange(mockEvent);
expect(handler1).toHaveBeenCalled();
expect(handler2).toHaveBeenCalled();
expect(handler3).not.toHaveBeenCalled(); // Should not be called because handler2 returned true
expect(mockDeleteChain).not.toHaveBeenCalled(); // Fallback should not run
});
});
});

View file

@ -1,4 +1,8 @@
import * as vscode from "vscode";
import {
HandlerPriority,
SelectionChangeManager,
} from "../activation/SelectionChangeManager";
export interface ExpectedGhostTextAcceptance {
documentUri: string;
@ -114,4 +118,32 @@ export class GhostTextAcceptanceTracker {
return false;
}
public registerSelectionChangeHandler(): void {
const manager = SelectionChangeManager.getInstance();
manager.registerListener(
"ghostTextTracker",
async (e, state) => {
if (!state.document || !state.cursorPosition) {
return false;
}
const wasGhostTextAccepted = this.checkGhostTextWasAccepted(
state.document,
state.cursorPosition,
);
if (wasGhostTextAccepted) {
console.log(
"GhostTextAcceptanceTracker: ghost text was accepted, preserving chain",
);
return true;
}
return false;
},
HandlerPriority.HIGH,
);
}
}

View file

@ -13,13 +13,9 @@ import { handleLLMError } from "../util/errorHandling";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { myersDiff } from "core/diff/myers";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "core/nextEdit/constants";
import { checkFim } from "core/nextEdit/diff/diff";
import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { NextEditOutcome } from "core/nextEdit/types";
import { JumpManager } from "../activation/JumpManager";
@ -67,10 +63,13 @@ export class ContinueCompletionProvider
private nextEditProvider: NextEditProvider;
private nextEditLoggingService: NextEditLoggingService;
private jumpManager: JumpManager;
private prefetchQueue: PrefetchQueue;
public recentlyVisitedRanges: RecentlyVisitedRangesService;
public recentlyEditedTracker: RecentlyEditedTracker;
private isNextEditActive: boolean = false;
private usingFullFileDiff: boolean = true;
public activateNextEdit() {
this.isNextEditActive = true;
@ -84,7 +83,9 @@ export class ContinueCompletionProvider
private readonly configHandler: ConfigHandler,
private readonly ide: VsCodeIde,
private readonly webviewProtocol: VsCodeWebviewProtocol,
usingFullFileDiff: boolean,
) {
this.usingFullFileDiff = usingFullFileDiff;
this.recentlyEditedTracker = new RecentlyEditedTracker(ide.ideUtils);
async function getAutocompleteModel() {
@ -115,6 +116,8 @@ export class ContinueCompletionProvider
);
this.jumpManager = JumpManager.getInstance();
this.prefetchQueue = PrefetchQueue.getInstance();
this.prefetchQueue.initialize(this.usingFullFileDiff);
this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide);
}
@ -136,6 +139,12 @@ export class ContinueCompletionProvider
token: vscode.CancellationToken,
//@ts-ignore
): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
// This method is triggered on every keystroke, tab keypress, and cursor move.
// We need to determine why it was triggered:
// 1. Typing (chain doesn't exist)
// 2. Jumping (chain exists, jump was taken)
// 3. Accepting (chain exists, jump is not taken)
const enableTabAutocomplete =
getStatusBarStatus() === StatusBarStatus.Enabled;
if (token.isCancellationRequested || !enableTabAutocomplete) {
@ -146,8 +155,11 @@ export class ContinueCompletionProvider
return null;
}
// Don't autocomplete with multi-cursor
const editor = vscode.window.activeTextEditor;
if (!editor) {
return undefined;
}
// Don't autocomplete with multi-cursor
if (editor && editor.selections.length > 1) {
return null;
}
@ -173,6 +185,8 @@ export class ContinueCompletionProvider
}
let injectDetails: string | undefined = undefined;
const currCursorPos = editor.selection.active;
try {
const abortController = new AbortController();
const signal = abortController.signal;
@ -229,90 +243,166 @@ export class ContinueCompletionProvider
const wasManuallyTriggered =
context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
const completionId = uuidv4();
const filepath = document.uri.toString();
const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets();
let recentlyEditedRanges =
await this.recentlyEditedTracker.getRecentlyEditedRanges();
console.log(
"chain exists?",
this.nextEditProvider.chainExists(),
", length:",
this.nextEditProvider.getChainLength(),
", next regions queue:",
this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(),
);
const ctx = {
completionId,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
isUntitledFile: document.isUntitled,
recentlyVisitedRanges,
recentlyEditedRanges,
};
if (this.nextEditProvider.chainExists()) {
// The chain of edits is alive because the user has accepted the previous completion.
// Get the next editable region and set the pos to be within that range.
outcome =
await this.nextEditProvider.provideInlineCompletionItemsWithChain(
{
completionId,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
isUntitledFile: document.isUntitled,
recentlyVisitedRanges,
recentlyEditedRanges,
},
signal,
let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
// console.log(
// "chain exists?",
// this.nextEditProvider.chainExists(),
// ", length:",
// this.nextEditProvider.getChainLength(),
// ", next regions queue:",
// this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(),
// );
// Determine why this method was triggered.
const isJumping = this.jumpManager.isJumpInProgress();
const chainExists = this.nextEditProvider.chainExists();
if (isJumping && chainExists) {
// Case 2: Jumping (chain exists, jump was taken)
console.log("trigger reason: jumping");
// Reset jump state.
this.jumpManager.setJumpInProgress(false);
// Use the saved completion from JumpManager instead of dequeuing.
const savedCompletion = this.jumpManager.completionAfterJump;
if (savedCompletion) {
outcome = savedCompletion.outcome;
this.jumpManager.clearCompletionAfterJump();
} else {
// Fall back to prefetch queue. This technically should not happen.
console.error(
"Fell back to prefetch queue even after jump was taken",
);
outcome = this.prefetchQueue.dequeueProcessed()?.outcome;
// Fill in the spot after dequeuing.
if (!this.usingFullFileDiff) {
this.prefetchQueue.process({
...ctx,
recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
recentlyEditedRanges:
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
});
}
}
} else if (chainExists) {
// Case 3: Accepting next edit outcome (chain exists, jump is not taken).
console.log("trigger reason: accepting");
// Try suggesting jump for each location.
let isJumpSuggested = false;
while (this.prefetchQueue.processedCount > 0 && !isJumpSuggested) {
const nextItemInQueue = this.prefetchQueue.dequeueProcessed();
if (!nextItemInQueue) continue;
// Fill in the spot after dequeuing.
if (!this.usingFullFileDiff) {
this.prefetchQueue.process({
...ctx,
recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
recentlyEditedRanges:
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
});
}
const nextLocation = nextItemInQueue.location;
outcome = nextItemInQueue.outcome;
const jumpPosition = new vscode.Position(
nextLocation.range.start.line,
nextLocation.range.start.character,
);
isJumpSuggested = await this.jumpManager.suggestJump(
currCursorPos,
jumpPosition,
outcome.completion,
);
if (isJumpSuggested) {
// Store completion to be rendered after a jump.
// TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location.
this.jumpManager.setCompletionAfterJump({
completionId: completionId,
outcome,
currentPosition: jumpPosition,
});
// Don't display anything yet.
// This will be handled in Case 2.
return undefined;
}
}
if (!isJumpSuggested) {
console.log(
"No suitable jump location found after trying all positions",
);
this.nextEditProvider.deleteChain();
return undefined;
}
} else {
// If the user has rejected, then we start a new chain of edits.
// Case 1: Typing (chain does not exist).
this.nextEditProvider.startChain();
const input: AutocompleteInput = {
pos,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
injectDetails,
isUntitledFile: document.isUntitled,
completionId,
filepath,
recentlyVisitedRanges,
recentlyEditedRanges,
...ctx,
};
setupStatusBar(undefined, true);
// Check if editChainId exists or needs to be refreshed.
// Get initial completion.
if (this.isNextEditActive) {
outcome = await this.nextEditProvider.provideInlineCompletionItems(
input,
signal,
{ withChain: false },
{ withChain: false, usingFullFileDiff: this.usingFullFileDiff },
);
if (!outcome || !outcome.completion) {
// Hitting this condition means that the model could not predict a next edit action.
// That happens when the user's recent edit is good enough, or if the model is totally lost.
// At this point we assume that the user typed something good enough to maintain a chain of edits.
// All we need to do here is to calculate next editable region.
// We also need to use the user's edits to create a user edits section in renderPrompt.
recentlyEditedRanges =
await this.recentlyEditedTracker.getRecentlyEditedRanges();
// Start prefetching next edits.
// NOTE: this might be better off not awaited.
if (!this.usingFullFileDiff) {
this.prefetchQueue.process(ctx);
}
outcome =
await this.nextEditProvider.provideInlineCompletionItemsWithChain(
{
completionId,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
isUntitledFile: document.isUntitled,
recentlyVisitedRanges,
recentlyEditedRanges,
},
signal,
);
// If initial outcome is null, suggest a jump instead.
// Calling this method again will call it with
// chain active but jump not suggested yet.
if (
!outcome ||
(!outcome.completion && outcome.diffLines.length === 0)
) {
return this.provideInlineCompletionItems(
document,
position,
context,
token,
);
}
} else {
// Handle autocomplete request.
// Handle regular autocomplete request.
outcome = await this.completionProvider.provideInlineCompletionItems(
input,
signal,
@ -321,9 +411,15 @@ export class ContinueCompletionProvider
}
}
// If the model cannot predict a completion or a next edit,
// then it's safe to assume that there are no more changes to be made.
if (!outcome || !outcome.completion) {
// Return early if no valid outcome was found.
if (
!outcome ||
(!this.isNextEditActive &&
!(outcome as AutocompleteOutcome).completion) ||
(this.isNextEditActive &&
!(outcome as NextEditOutcome).completion &&
(outcome as NextEditOutcome).diffLines.length === 0)
) {
return null;
}
@ -415,186 +511,116 @@ export class ContinueCompletionProvider
(autocompleteCompletionItem as any).completeBracketPairs = true;
const editor = vscode.window.activeTextEditor;
if (!editor) {
return undefined;
}
const currCursorPos = editor.selection.active;
if (this.isNextEditActive) {
if (!this.nextEditProvider.isStartOfChain()) {
// Try suggesting jumps for each location in the queue.
let jumpSuccessful = false;
while (
this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength() >
0 &&
!jumpSuccessful
) {
// NOTE: Outcome has to be re-computed for each next editable location.
const nextRegion =
this.nextEditProvider.getNextEditableRegionsInTheCurrentChain()[0];
if (!nextRegion) continue;
// Getting the outcome shifts the next editable region queue,
// deleting the item denoted by nextRegion above.
outcome =
await this.nextEditProvider.provideInlineCompletionItemsWithChain(
{
completionId,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
isUntitledFile: document.isUntitled,
recentlyVisitedRanges,
recentlyEditedRanges,
},
signal,
);
if (!outcome) continue;
const jumpPosition = new vscode.Position(
nextRegion.range.start.line,
nextRegion.range.start.character,
);
// Try to suggest a jump to this location.
jumpSuccessful = await this.jumpManager.suggestJump(
currCursorPos,
jumpPosition,
outcome.completion,
);
if (jumpSuccessful) {
// Store completion to be rendered after jump.
this.jumpManager.setCompletionAfterJump({
completionId: completionId,
outcome: outcome as NextEditOutcome,
currentPosition: jumpPosition,
});
return undefined; // Don't show anything yet!
}
}
// If no jump was successful after trying multiple locations,
// proceed with other completion display logic or return undefined.
if (!jumpSuccessful) {
console.log(
"No suitable jump location found after trying multiple positions",
);
return undefined;
}
}
// Check the diff between old and new editable region.
const newEditRangeSlice = completionText;
// We don't need to show the next edit window if the predicted edits is empty.
if (newEditRangeSlice === "") {
this.nextEditLoggingService.cancelRejectionTimeout(completionId);
return undefined;
}
// Get the contents of the old (current) editable region.
const editableRegionStartLine = Math.max(
currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
0,
);
const editableRegionEndLine = Math.min(
currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
editor.document.lineCount - 1,
);
const oldEditRangeSlice = editor.document
.getText()
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
// We don't need to show the next edit window if the predicted edits are identical to the previous version.
if (oldEditRangeSlice === newEditRangeSlice) {
this.nextEditLoggingService.cancelRejectionTimeout(completionId);
return undefined;
}
// Create a cursor position relative to the edit range slice.
const relativeCursorPos = {
line: currCursorPos.line - editableRegionStartLine,
character: currCursorPos.character,
};
// If the diff is a FIM, render a ghost text.
const { isFim, fimText } = checkFim(
oldEditRangeSlice,
newEditRangeSlice,
relativeCursorPos,
);
if (isFim) {
if (!fimText) {
console.log("deleteChain from completionProvider.ts: !fimText");
this.nextEditProvider.deleteChain();
return undefined;
}
// Track this ghost text for acceptance detection.
// Ghost text acceptance can *technically* be acted upon in
// the command handler for "continue.logNextEditOutcomeAccept",
// but there is a substantial delay between accepting and logging,
// which introduces a lot of race conditions with different event handlers.
// Plus, separating these concerns seems to make sense logically as well.
GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance(
document,
fimText,
new vscode.Position(currCursorPos.line, currCursorPos.character),
);
const nextEditCompletionItem = new vscode.InlineCompletionItem(
fimText,
new vscode.Range(
new vscode.Position(currCursorPos.line, currCursorPos.character),
new vscode.Position(currCursorPos.line, currCursorPos.character),
),
{
title: "Log Next Edit Outcome",
command: "continue.logNextEditOutcomeAccept",
arguments: [completionId, this.nextEditLoggingService],
},
);
return [nextEditCompletionItem];
}
// Else, render a next edit window.
const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice);
if (diffLines.length === 0) {
console.log(
"deleteChain from completionProvider.ts: diffLines.length === 0",
);
NextEditProvider.getInstance().deleteChain();
}
if (NextEditWindowManager.isInstantiated()) {
NextEditWindowManager.getInstance().updateCurrentCompletionId(
completionId,
);
await NextEditWindowManager.getInstance().showNextEditWindow(
editor,
currCursorPos,
editableRegionStartLine,
editableRegionEndLine,
oldEditRangeSlice,
newEditRangeSlice,
diffLines,
);
}
return undefined;
} else {
// Handle autocomplete request.
if (!this.isNextEditActive) {
return [autocompleteCompletionItem];
}
// Check the diff between old and new editable region.
const newEditRangeSlice = completionText;
// Get the contents of the old (current) editable region.
// const editableRegionStartLine = Math.max(
// currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
// 0,
// );
// const editableRegionEndLine = Math.min(
// currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
// editor.document.lineCount - 1,
// );
const editableRegionStartLine = (outcome as NextEditOutcome)
.editableRegionStartLine;
const editableRegionEndLine = (outcome as NextEditOutcome)
.editableRegionEndLine;
const oldEditRangeSlice = editor.document
.getText()
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
// We don't need to show the next edit window if the predicted edits are identical to the previous version.
if (oldEditRangeSlice === newEditRangeSlice) {
this.nextEditLoggingService.cancelRejectionTimeout(completionId);
return undefined;
}
// Create a cursor position relative to the edit range slice.
const relativeCursorPos = {
line: currCursorPos.line - editableRegionStartLine,
character: currCursorPos.character,
};
// If the diff is a FIM, render a ghost text.
const { isFim, fimText } = checkFim(
oldEditRangeSlice,
newEditRangeSlice,
relativeCursorPos,
);
if (isFim) {
if (!fimText) {
console.log("deleteChain from completionProvider.ts: !fimText");
this.nextEditProvider.deleteChain();
return undefined;
}
// Track this ghost text for acceptance detection.
// Ghost text acceptance can *technically* be acted upon in
// the command handler for "continue.logNextEditOutcomeAccept",
// but there is a substantial delay between accepting and logging,
// which introduces a lot of race conditions with different event handlers.
// Plus, separating these concerns seems to make sense logically as well.
GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance(
document,
fimText,
new vscode.Position(currCursorPos.line, currCursorPos.character),
);
const nextEditCompletionItem = new vscode.InlineCompletionItem(
fimText,
new vscode.Range(
new vscode.Position(currCursorPos.line, currCursorPos.character),
new vscode.Position(currCursorPos.line, currCursorPos.character),
),
{
title: "Log Next Edit Outcome",
command: "continue.logNextEditOutcomeAccept",
arguments: [completionId, this.nextEditLoggingService],
},
);
return [nextEditCompletionItem];
}
// Handle non-FIM cases with the NextEditWindowManager.
const diffLines = (outcome as NextEditOutcome).diffLines;
if (diffLines.length === 0) {
// At this point, there is no way that diffLines.length === 0.
// Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse.
// In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place.
// In case of initial response, we suggested a jump.
console.log(
"deleteChain from completionProvider.ts: diffLines.length === 0",
);
NextEditProvider.getInstance().deleteChain();
}
if (NextEditWindowManager.isInstantiated()) {
NextEditWindowManager.getInstance().updateCurrentCompletionId(
completionId,
);
await NextEditWindowManager.getInstance().showNextEditWindow(
editor,
currCursorPos,
editableRegionStartLine,
editableRegionEndLine,
oldEditRangeSlice,
newEditRangeSlice,
diffLines,
);
}
return undefined;
} finally {
stopStatusBarLoading();
}

View file

@ -17,16 +17,7 @@ import * as YAML from "yaml";
import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist";
import { myersDiff } from "core/diff/myers";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "core/nextEdit/constants";
import { checkFim } from "core/nextEdit/diff/diff";
import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { CompletionDataForAfterJump } from "./activation/JumpManager";
import { NextEditWindowManager } from "./activation/NextEditWindowManager";
import {
getAutocompleteStatusBarDescription,
getAutocompleteStatusBarTitle,
@ -814,125 +805,6 @@ const getCommandsMap: (
"editor.action.inlineSuggest.trigger",
);
},
"continue.showNextEditAfterJump": async (
data: CompletionDataForAfterJump,
) => {
// NOTE: This could use some cleanup or abstraction.
// The logic is largely similar to that of completionProvider.ts
// but we don't have access to the class.
const { completionId, outcome, currentPosition } = data;
const editor = vscode.window.activeTextEditor;
if (!editor) {
console.log("No active editor when trying to show next edit");
return;
}
const documentContent = editor.document.getText();
// Calculate the editable region boundaries around the current cursor position/
const editableRegionStartLine = Math.max(
currentPosition.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
0,
);
const editableRegionEndLine = Math.min(
currentPosition.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
editor.document.lineCount - 1,
);
// Get the current text in the editable region.
const oldEditRangeSlice = documentContent
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
// Get the suggested new text from the completion outcome.
const newEditRangeSlice = outcome.completion;
// Skip showing edit if the suggestion is empty.
if (newEditRangeSlice === "") {
const loggingService = NextEditLoggingService.getInstance();
loggingService.cancelRejectionTimeout(completionId);
return;
}
// Skip showing edit if the suggestion is identical to current text.
if (oldEditRangeSlice === newEditRangeSlice) {
const loggingService = NextEditLoggingService.getInstance();
loggingService.cancelRejectionTimeout(completionId);
return;
}
// Create a cursor position relative to the edit range slice
const relativeCursorPos = {
line: currentPosition.line - editableRegionStartLine,
character: currentPosition.character,
};
const { isFim, fimText } = checkFim(
oldEditRangeSlice,
newEditRangeSlice,
relativeCursorPos,
);
if (isFim) {
if (!fimText) {
console.log("deleteChain from commands.ts: !fimText");
await NextEditProvider.getInstance().deleteChain();
}
// For FIM edits, create an inline completion item.
const nextEditCompletionItem = new vscode.InlineCompletionItem(
fimText,
new vscode.Range(
new vscode.Position(
currentPosition.line,
currentPosition.character,
),
new vscode.Position(
currentPosition.line,
currentPosition.character,
),
),
{
title: "Log Next Edit Outcome",
command: "continue.logNextEditOutcomeAccept",
arguments: [completionId, NextEditLoggingService.getInstance()],
},
);
// Show the ghost text using VS Code's inline completion API.
// We need to trigger this manually since we're not in the completion provider.
await vscode.commands.executeCommand(
"editor.action.inlineSuggest.trigger",
{
completions: [nextEditCompletionItem],
position: currentPosition,
},
);
} else {
// For more complex edits, we display a diff inside a window.
const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice);
if (diffLines.length === 0) {
console.log("deleteChain from commands.ts: diffLines.length === 0");
await NextEditProvider.getInstance().deleteChain();
}
if (NextEditWindowManager.isInstantiated()) {
const windowManager = NextEditWindowManager.getInstance();
windowManager.updateCurrentCompletionId(completionId);
await windowManager.showNextEditWindow(
editor,
currentPosition,
editableRegionStartLine,
editableRegionEndLine,
oldEditRangeSlice,
newEditRangeSlice,
diffLines,
);
}
}
},
};
};

View file

@ -43,18 +43,19 @@ import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider
import { VsCodeMessenger } from "./VsCodeMessenger";
import { getAst } from "core/autocomplete/util/ast";
import { modelSupportsNextEdit } from "core/llm/autodetect";
import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker";
import {
EditableRegionStrategy,
getNextEditableRegion,
} from "core/nextEdit/NextEditEditableRegionCalculator";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { isModelCapableOfNextEdit } from "core/nextEdit/utils";
import { isNextEditTest } from "core/nextEdit/utils";
import { localPathOrUriToPath } from "core/util/pathToUri";
import { JumpManager } from "../activation/JumpManager";
import setupNextEditWindowManager, {
NextEditWindowManager,
} from "../activation/NextEditWindowManager";
import {
HandlerPriority,
SelectionChangeManager,
} from "../activation/SelectionChangeManager";
import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker";
import { getDefinitionsFromLsp } from "../autocomplete/lsp";
import { handleTextDocumentChange } from "../util/editLoggingUtils";
@ -79,18 +80,8 @@ export class VsCodeExtension {
private fileSearch: FileSearch;
private uriHandler = new UriEventHandler();
private completionProvider: ContinueCompletionProvider;
// Track whether the user is currently typing
private isTypingSession = false;
private typingTimer: NodeJS.Timeout | null = null;
private lastDocumentChangeTime = 0;
// Reset typing session after a delay
resetTypingSession = () => {
if (this.typingTimer) clearTimeout(this.typingTimer);
this.typingTimer = setTimeout(() => {
this.isTypingSession = false;
}, 2000); // Typing session considered over after 2 seconds of inactivity
};
private ARBITRARY_TYPING_DELAY = 2000;
constructor(context: vscode.ExtensionContext) {
// Register auth provider
@ -111,6 +102,28 @@ export class VsCodeExtension {
this.extensionContext = context;
this.windowId = uuidv4();
const usingFullFileDiff = true;
const selectionManager = SelectionChangeManager.getInstance();
selectionManager.initialize(this.ide, usingFullFileDiff);
selectionManager.registerListener(
"typing",
async (e, state) => {
const timeSinceLastDocChange =
Date.now() - state.lastDocumentChangeTime;
if (
state.isTypingSession &&
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY
) {
console.log("VsCodeExtension: typing in progress, preserving chain");
return true;
}
return false;
},
HandlerPriority.NORMAL,
);
// Dependencies of core
let resolveVerticalDiffManager: any = undefined;
const verticalDiffManagerPromise = new Promise<VerticalDiffManager>(
@ -190,16 +203,28 @@ export class VsCodeExtension {
async ({ config: newConfig, configLoadInterrupted }) => {
const autocompleteModel = newConfig?.selectedModelByRole.autocomplete;
if (
autocompleteModel &&
isModelCapableOfNextEdit(autocompleteModel.model)
(autocompleteModel &&
modelSupportsNextEdit(
autocompleteModel.capabilities,
autocompleteModel.model,
autocompleteModel.title,
)) ||
isNextEditTest()
) {
// Set up next edit window manager only for Continue team members
await setupNextEditWindowManager(context);
this.activateNextEdit();
await NextEditWindowManager.freeTabAndEsc();
JumpManager.getInstance();
GhostTextAcceptanceTracker.getInstance();
const jumpManager = JumpManager.getInstance();
jumpManager.registerSelectionChangeHandler();
const ghostTextAcceptanceTracker =
GhostTextAcceptanceTracker.getInstance();
ghostTextAcceptanceTracker.registerSelectionChangeHandler();
const nextEditWindowManager = NextEditWindowManager.getInstance();
nextEditWindowManager.registerSelectionChangeHandler();
} else {
NextEditWindowManager.clearInstance();
this.deactivateNextEdit();
@ -236,6 +261,7 @@ export class VsCodeExtension {
this.configHandler,
this.ide,
this.sidebar.webviewProtocol,
usingFullFileDiff,
);
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider(
@ -345,9 +371,7 @@ export class VsCodeExtension {
vscode.workspace.onDidChangeTextDocument(async (event) => {
if (event.contentChanges.length > 0) {
this.isTypingSession = true;
this.lastDocumentChangeTime = Date.now();
this.resetTypingSession();
selectionManager.documentChanged();
}
const editInfo = await handleTextDocumentChange(
@ -433,60 +457,7 @@ export class VsCodeExtension {
// Listen for selection changes to hide tooltip when cursor moves.
vscode.window.onDidChangeTextEditorSelection(async (e) => {
// Don't delete the chain of edits if:
// 1. A next edit window was just accepted.
if (
NextEditWindowManager.isInstantiated() &&
NextEditWindowManager.getInstance().hasAccepted()
) {
return;
}
// 2. A jump is in progress.
if (
JumpManager.getInstance().isJumpInProgress() ||
JumpManager.getInstance().wasJumpJustAccepted()
) {
return;
}
// 3. A ghost text was just accepted.
// Check if this selection change matches our expected ghost text acceptance.
const wasGhostTextAccepted =
GhostTextAcceptanceTracker.getInstance().checkGhostTextWasAccepted(
e.textEditor.document,
e.selections[0].active,
);
if (wasGhostTextAccepted) {
// Ghost text was accepted - don't delete the chain.
return;
}
// 4. The selection change is part of a typing session
// Check if this selection change is close enough to a document change to be considered typing.
const timeSinceLastDocChange = Date.now() - this.lastDocumentChangeTime;
const ARBITRARY_TYPING_DELAY = 500;
if (
this.isTypingSession &&
timeSinceLastDocChange < ARBITRARY_TYPING_DELAY
) {
// This selection change is likely due to typing, don't delete the chain.
return;
}
// Otherwise, delete the chain (for rejection or unrelated movement).
console.log("deleteChain called from onDidChangeTextEditorSelection");
await NextEditProvider.getInstance().deleteChain();
NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain(
(await getNextEditableRegion(EditableRegionStrategy.Static, {
cursorPosition: e.selections[0].anchor,
filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()),
ide: this.ide,
})) ?? [],
);
await selectionManager.handleSelectionChange(e);
});
// Refresh index when branch is changed

View file

@ -1,12 +1,12 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { TrashIcon } from "@heroicons/react/24/outline";
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { ChatHistoryItem } from "core";
import { useState } from "react";
import { AnimatedEllipsis } from "../AnimatedEllipsis";
import { useAppSelector } from "../../redux/hooks";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useDeleteCompaction } from "../../util/compactConversation";
import { AnimatedEllipsis } from "../AnimatedEllipsis";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
interface ConversationSummaryProps {
item: ChatHistoryItem;
@ -14,7 +14,7 @@ interface ConversationSummaryProps {
}
export default function ConversationSummary(props: ConversationSummaryProps) {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(true);
const isLoading = useAppSelector(
(state) => state.session.compactionLoading[props.index] || false,
);

View file

@ -263,7 +263,7 @@ export function StepContainerPreToolbar({
}
return (
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mb-2 mt-2 flex min-w-0 flex-col outline outline-1">
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor !my-2 flex min-w-0 flex-col outline outline-1">
<div
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
style={{ fontSize: `${getFontSize() - 2}px` }}

View file

@ -245,12 +245,14 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
// Trigger warning message
ideMessenger.ide.showToast(
"warning",
fileSize > 0 ? "File exceeds context length" : "Can't load the file",
fileSize > 0
? "File exceeds model's context length"
: "Error loading file",
{
modal: true,
detail:
fileSize > 0
? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model`
? `'${item.title}' cannot be added because it exceeds the model's allowed context length. File size: ${formatFileSize(fileSize)}`
: `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`,
},
);

View file

@ -60,6 +60,9 @@ function PromptRow({
}
};
const canEdit =
prompt.promptFile && !prompt.promptFile.startsWith("builtin:");
return (
<div
className="hover:bg-list-active hover:text-list-active-foreground flex items-center justify-between gap-3 rounded-md px-2 py-1 hover:cursor-pointer"
@ -78,8 +81,9 @@ function PromptRow({
</div>
<div className="flex items-center gap-2">
<PencilIcon
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
onClick={handleEditClick}
className={`h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125 ${!canEdit ? "pointer-events-none cursor-not-allowed opacity-50" : ""}`}
onClick={canEdit ? handleEditClick : undefined}
aria-disabled={!canEdit}
/>
<div
onClick={handleBookmarkClick}

View file

@ -7,13 +7,14 @@ import {
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { MCPServerStatus } from "core";
import { useContext, useMemo } from "react";
import { Fragment, useContext, useMemo } from "react";
import { useAuth } from "../../../../../context/Auth";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { updateConfig } from "../../../../../redux/slices/configSlice";
import { fontSize } from "../../../../../util";
import { ToolTip } from "../../../../gui/Tooltip";
import { Button } from "../../../../ui";
import EditBlockButton from "../../EditBlockButton";
import { ExploreBlocksButton } from "../ExploreBlocksButton";
@ -68,9 +69,37 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
className={`h-3 w-3 ${server.status === "error" ? "text-red-500" : "text-yellow-500"}`}
data-tooltip-id={errorsTooltipId}
/>
<ToolTip id={errorsTooltipId} className="flex flex-col gap-0.5">
<ToolTip
clickable
id={errorsTooltipId}
delayHide={
server.errors.some((error) => error.length > 150) ? 1500 : 0
}
className="flex flex-col gap-0.5"
>
{server.errors.map((error, idx) => (
<code key={idx}>{error}</code>
<Fragment key={idx}>
<div>
{error.length > 150
? error.substring(0, 150) + "..."
: error}
</div>
{error.length > 150 && (
<Button
className="my-0"
size="sm"
variant="ghost"
onClick={() =>
void ideMessenger.ide.showVirtualFile(
server.name,
error,
)
}
>
View full error
</Button>
)}
</Fragment>
))}
</ToolTip>
</>

View file

@ -65,6 +65,11 @@ export const ToolPoliciesSection = () => {
</Alert>
</div>
)}
{toolsByGroup.length === 0 && (
<span className="text-description text-sm italic">
No tools available
</span>
)}
{toolsByGroup.map(([groupName, tools]) => {
const isGroupEnabled =
!allToolsOff && toolGroupSettings[groupName] !== "exclude";

View file

@ -181,7 +181,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
onKeyUp={handleKeyUp}
className={
!props.isMainInput && shouldHideToolbar
? "cursor-pointer hover:brightness-105"
? "cursor-pointer"
: "cursor-text"
}
onClick={() => {

View file

@ -87,6 +87,34 @@ export const models: { [key: string]: ModelPackage } = {
providerOptions: ["novita", "nebius"],
isOpenSource: true,
},
gptOss20B: {
title: "gpt-oss-20b",
description:
"OpenAI's 20B open-weight model with native tool use and reasoning for agentic tasks.",
refUrl: "https://huggingface.co/openai/gpt-oss-20b",
params: {
title: "gpt-oss-20b",
model: "openai/gpt-oss-20b",
contextLength: 128_000,
},
icon: "openai.png",
providerOptions: ["vllm"],
isOpenSource: true,
},
gptOss120B: {
title: "gpt-oss-120b",
description:
"OpenAI's 120B flagship open-weight model built for complex, high‑reasoning agentic workflows.",
refUrl: "https://huggingface.co/openai/gpt-oss-120b",
params: {
title: "gpt-oss-120b",
model: "openai/gpt-oss-120b",
contextLength: 128_000,
},
icon: "openai.png",
providerOptions: ["vllm"],
isOpenSource: true,
},
llama318BChat: {
title: "Llama 3.1 8B",
description: "A model from Meta, fine-tuned for chat",
@ -1067,6 +1095,18 @@ export const models: { [key: string]: ModelPackage } = {
icon: "cohere.png",
isOpenSource: false,
},
gpt5: {
title: "GPT-5",
description: "OpenAI's next-generation, high-intelligence flagship model",
params: {
model: "gpt-5",
contextLength: 400_000,
title: "GPT-5",
},
providerOptions: ["openai"],
icon: "openai.png",
isOpenSource: false,
},
gpt4turbo: {
title: "GPT-4 Turbo",
description:

View file

@ -52,12 +52,13 @@ export const providers: Partial<Record<string, ProviderInfo>> = {
openai: {
title: "OpenAI",
provider: "openai",
description: "Use gpt-4, gpt-3.5-turbo, or any other OpenAI model",
description: "Use gpt-5, gpt-4, or any other OpenAI model",
longDescription:
"Use gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.",
"Use gpt-5, gpt-4, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.",
icon: "openai.png",
tags: [ModelProviderTags.RequiresApiKey],
packages: [
models.gpt5,
models.gpt4o,
models.gpt4omini,
models.gpt4turbo,

View file

@ -80,7 +80,7 @@ export function ToolCallDiv({
if (shouldShowGroupedUI) {
return (
<div className="border-border rounded-lg border p-3">
<div className="border-border rounded-lg border p-3 pb-0">
<GroupedToolCallHeader
toolCallStates={toolCallStates}
activeCalls={activeCalls}
@ -103,7 +103,7 @@ export function ToolCallDiv({
}
return toolCallStates.map((toolCallState) => (
<div className="p-4 pb-1" key={toolCallState.toolCallId}>
<div className="px-4 py-1" key={toolCallState.toolCallId}>
{renderToolCall(toolCallState)}
</div>
));

View file

@ -14,6 +14,7 @@ import {
import { ThunkApiType } from "../store";
import { findToolCallById, logToolUsage } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
export const callToolById = createAsyncThunk<
void,
@ -36,9 +37,11 @@ export const callToolById = createAsyncThunk<
// Check if this is an auto-approved tool
const toolSettings = state.ui.toolSettings;
const isAutoApproved =
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission";
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
toolCallState.tool?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
const isAutoApproved = toolPolicy === "allowedWithoutPermission";
posthog.capture("gui_tool_call_decision", {
decision: isAutoApproved ? "auto_accept" : "accept",

View file

@ -25,9 +25,11 @@ import { constructMessages } from "../util/constructMessages";
import { modelSupportsNativeTools } from "core/llm/toolSupport";
import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage";
import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks";
import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
import { callToolById } from "./callToolById";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
/**
* Handles the execution of tool calls that may be automatically accepted.
* Sets all tools as generated first, then executes auto-approved tool calls.
@ -35,6 +37,7 @@ import { callToolById } from "./callToolById";
async function handleToolCallExecution(
dispatch: AppThunkDispatch,
getState: () => RootState,
activeTools: Tool[],
): Promise<void> {
const newState = getState();
const toolSettings = newState.ui.toolSettings;
@ -51,11 +54,15 @@ async function handleToolCallExecution(
}
// Check if ALL tool calls are auto-approved - if not, wait for user approval
const allAutoApproved = toolCallStates.every(
(toolCallState) =>
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission",
);
const allAutoApproved = toolCallStates.every((toolCallState) => {
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
activeTools.find(
(tool) => tool.function.name === toolCallState.toolCall.function.name,
)?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
return toolPolicy == "allowedWithoutPermission";
});
// Set all tools as generated first
toolCallStates.forEach((toolCallState) => {
@ -147,6 +154,9 @@ export const streamNormalInput = createAsyncThunk<
// Use the centralized selector to determine if system message tools should be used
const useSystemTools = selectUseSystemMessageTools(state);
const useNativeTools = !useSystemTools && supportsNativeTools;
const systemToolsFramework = useSystemTools
? new SystemMessageToolCodeblocksFramework()
: undefined;
// Construct completion options
let completionOptions: LLMFullCompletionOptions = {};
@ -169,10 +179,15 @@ export const streamNormalInput = createAsyncThunk<
const baseSystemMessage = getBaseSystemMessage(
state.session.mode,
selectedChatModel,
activeTools,
);
const systemMessage = useSystemTools
? addSystemMessageToolsToSystemMessage(baseSystemMessage, activeTools)
const systemMessage = systemToolsFramework
? addSystemMessageToolsToSystemMessage(
systemToolsFramework,
baseSystemMessage,
activeTools,
)
: baseSystemMessage;
const withoutMessageIds = state.session.history.map((item) => {
@ -185,7 +200,7 @@ export const streamNormalInput = createAsyncThunk<
systemMessage,
state.config.config.rules,
state.ui.ruleSettings,
!useNativeTools,
systemToolsFramework,
);
// TODO parallel tool calls will cause issues with this
@ -233,8 +248,8 @@ export const streamNormalInput = createAsyncThunk<
},
streamAborter.signal,
);
if (!useNativeTools && activeTools.length > 0) {
gen = interceptSystemToolCalls(gen, streamAborter);
if (systemToolsFramework && activeTools.length > 0) {
gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework);
}
let next = await gen.next();
@ -289,11 +304,16 @@ export const streamNormalInput = createAsyncThunk<
// Check if ALL generating tool calls are auto-approved
const allAutoApproved =
generatingToolCalls.length > 0 &&
generatingToolCalls.every(
(toolCallState) =>
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission",
);
generatingToolCalls.every((toolCallState) => {
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
activeTools.find(
(tool) =>
tool.function.name === toolCallState.toolCall.function.name,
)?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
return toolPolicy == "allowedWithoutPermission";
});
// Only set inactive if:
// 1. There are no tool calls, OR
@ -303,6 +323,6 @@ export const streamNormalInput = createAsyncThunk<
dispatch(setInactive());
}
await handleToolCallExecution(dispatch, getState);
await handleToolCallExecution(dispatch, getState, activeTools);
},
);

View file

@ -15,6 +15,7 @@ import {
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "core/tools/constants";
import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools";
import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types";
import { findLast, findLastIndex } from "core/util/findLast";
import {
normalizeToMessageParts,
@ -30,7 +31,7 @@ export function constructMessages(
baseSystemMessage: string | undefined,
availableRules: RuleWithSource[],
rulePolicies: RulePolicies,
useSystemMessageTools?: boolean,
useSystemToolsFramework?: SystemMessageToolsFramework,
): {
messages: ChatMessage[];
appliedRules: RuleWithSource[];
@ -95,11 +96,12 @@ export function constructMessages(
});
} else if (item.message.role === "assistant") {
// When using system message tools, convert tool calls/states to text content
if (item.toolCallStates?.length && useSystemMessageTools) {
if (item.toolCallStates?.length && useSystemToolsFramework) {
const { userMessage, assistantMessage } =
convertToolCallStatesToSystemCallsAndOutput(
item.message,
item.toolCallStates ?? [],
useSystemToolsFramework,
);
msgs.push({
message: assistantMessage,

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