Merge branch 'main' of github.com:continuedev/continue into jacob/con-3283

This commit is contained in:
Jacob Kim 2025-08-06 16:00:43 -07:00
commit 971eb861e6
25 changed files with 3516 additions and 997 deletions

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] : [];
});

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,
@ -41,7 +41,7 @@ export type NextEditModelName =
const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, 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:
@ -112,7 +112,7 @@ export async function renderPrompt(
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
CURSOR,
MERCURY_CURSOR,
);
const mercuryCtx: MercuryTemplateVars = {
@ -126,6 +126,7 @@ export async function renderPrompt(
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
@ -138,7 +139,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,14 +4,14 @@ 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,
@ -75,15 +75,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,7 +96,7 @@ describe("NextEditPromptEngine", () => {
expect(result.prompt.content).toContain("```ts");
expect(result.userEdits).toBe(ctx.userEdits);
expect(result.userExcerpts).toContain(USER_CURSOR_IS_HERE_TOKEN);
expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
});
it("should handle 'this field is not used' model name", async () => {
@ -229,7 +229,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

@ -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");
});
});

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

@ -45,10 +45,6 @@ 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 { isNextEditTest } from "core/nextEdit/utils";
import { localPathOrUriToPath } from "core/util/pathToUri";
@ -56,6 +52,10 @@ 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";
@ -80,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
@ -112,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>(
@ -204,8 +216,15 @@ export class VsCodeExtension {
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();
@ -242,6 +261,7 @@ export class VsCodeExtension {
this.configHandler,
this.ide,
this.sidebar.webviewProtocol,
usingFullFileDiff,
);
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider(
@ -351,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(
@ -439,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