fix: filter out markdown delimiters from next edit responses (#8056)

* fix: filter out markdown delimiters from next edit responses

* fix: silence noisy console logs (debug now) and capture accept/reject feedback

* fix: console.log -> debug

* fix: console.log -> debug

* fix feedback

* fix: respect Telemetry

* requestId

* fix: lint

* bump
This commit is contained in:
Nate Sesti 2025-10-01 22:52:18 -07:00 • committed by GitHub
parent a57eb8069a
commit 89826f0fea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 254 additions and 33 deletions

View file

@ -0,0 +1,118 @@
import { postprocessCompletion } from "./index";
describe("postprocessCompletion - removeBackticks", () => {
const mockLLM = { model: "test-model" } as any;
it("should remove first line starting with ``` and last line that is ```", () => {
const completion =
"```typescript\nfunction hello() {\n return 'world';\n}\n```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("function hello() {\n return 'world';\n}");
});
it("should remove only first line if it starts with ```", () => {
const completion = "```javascript\nconst x = 5;\nconsole.log(x);";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const x = 5;\nconsole.log(x);");
});
it("should remove only last line if it is ```", () => {
const completion = "const y = 10;\nconsole.log(y);\n```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const y = 10;\nconsole.log(y);");
});
it("should not modify completion without backticks", () => {
const completion = "function test() {\n return true;\n}";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("function test() {\n return true;\n}");
});
it("should handle completion with backticks in the middle", () => {
const completion = "const str = `template ${literal}`;\nconsole.log(str);";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe(
"const str = `template ${literal}`;\nconsole.log(str);",
);
});
it("should handle first line with leading whitespace before ```", () => {
const completion = " ```python\ndef hello():\n pass\n```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("def hello():\n pass");
});
it("should handle last line with whitespace around ```", () => {
const completion = "```\ncode here\n ``` ";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("code here");
});
it("should handle single line completion", () => {
const completion = "const x = 5;";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const x = 5;");
});
it("should handle empty completion", () => {
const completion = "";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBeUndefined();
});
it("should not remove ``` if it's not on its own line at the end", () => {
const completion = "```typescript\nconst x = 5; // end```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const x = 5; // end```");
});
});

View file

@ -52,6 +52,38 @@ function isBlank(completion: string): boolean {
return completion.trim().length === 0;
}
/**
* Removes markdown code block delimiters from completion.
* Removes the first line if it starts with "```" and the last line if it is exactly "```".
*/
function removeBackticks(completion: string): string {
const lines = completion.split("\n");
if (lines.length === 0) {
return completion;
}
let startIdx = 0;
let endIdx = lines.length;
// Remove first line if it starts with ```
if (lines[0].trimStart().startsWith("```")) {
startIdx = 1;
}
// Remove last line if it is exactly ```
if (lines.length > startIdx && lines[lines.length - 1].trim() === "```") {
endIdx = lines.length - 1;
}
// If we removed lines, return the modified completion
if (startIdx > 0 || endIdx < lines.length) {
return lines.slice(startIdx, endIdx).join("\n");
}
return completion;
}
export function postprocessCompletion({
completion,
llm,
@ -156,5 +188,8 @@ export function postprocessCompletion({
completion = completion.slice(1);
}
// Remove markdown code block delimiters
completion = removeBackticks(completion);
return completion;
}

View file

@ -78,8 +78,9 @@ declare global {
export interface ILLM extends LLMOptions {
get providerName(): string;
uniqueId: string;
lastRequestId?: string;
model: string;
title?: string;

View file

@ -929,7 +929,7 @@ export class Core {
});
on("files/closed", async ({ data }) => {
console.log("deleteChain called from files/closed");
console.debug("deleteChain called from files/closed");
await NextEditProvider.getInstance().deleteChain();
try {

2
core/index.d.ts vendored
View file

@ -99,6 +99,8 @@ export interface ILLM
autocompleteOptions?: Partial<TabAutocompleteOptions>;
lastRequestId?: string;
complete(
prompt: string,
signal: AbortSignal,

View file

@ -193,12 +193,15 @@ export abstract class BaseLLM implements ILLM {
isFromAutoDetect?: boolean;
lastRequestId: string | undefined;
private _llmOptions: LLMOptions;
protected openaiAdapter?: BaseLlmApi;
constructor(_options: LLMOptions) {
this._llmOptions = _options;
this.lastRequestId = undefined;
// Set default options
const options = {
@ -594,6 +597,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
this.lastRequestId = undefined;
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -623,6 +627,9 @@ export abstract class BaseLLM implements ILLM {
signal,
);
for await (const chunk of stream) {
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
this.lastRequestId = (chunk as any).id;
}
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
@ -706,6 +713,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
this.lastRequestId = undefined;
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -745,6 +753,7 @@ export abstract class BaseLLM implements ILLM {
{ ...toCompleteBody(prompt, completionOptions), stream: false },
signal,
);
this.lastRequestId = response.id ?? this.lastRequestId;
completion = response.choices[0]?.text ?? "";
yield completion;
} else {
@ -756,6 +765,9 @@ export abstract class BaseLLM implements ILLM {
},
signal,
)) {
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
this.lastRequestId = (chunk as any).id;
}
const content = chunk.choices[0]?.text ?? "";
completion += content;
interaction?.logItem({
@ -835,6 +847,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
this.lastRequestId = undefined;
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -876,6 +889,7 @@ export abstract class BaseLLM implements ILLM {
},
signal,
);
this.lastRequestId = result.id ?? this.lastRequestId;
completion = result.choices[0].text;
} else {
completion = await this._complete(prompt, signal, completionOptions);
@ -985,6 +999,7 @@ export abstract class BaseLLM implements ILLM {
options: LLMFullCompletionOptions = {},
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog> {
this.lastRequestId = undefined;
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -1054,6 +1069,7 @@ export abstract class BaseLLM implements ILLM {
{ ...body, stream: false },
signal,
);
this.lastRequestId = response.id ?? this.lastRequestId;
const msg = fromChatResponse(response);
yield msg;
completion = this._formatChatMessage(msg);
@ -1071,6 +1087,12 @@ export abstract class BaseLLM implements ILLM {
signal,
);
for await (const chunk of stream) {
if (
!this.lastRequestId &&
typeof (chunk as any).id === "string"
) {
this.lastRequestId = (chunk as any).id;
}
const result = fromChatCompletionChunk(chunk);
if (result) {
completion += this._formatChatMessage(result);

View file

@ -1,5 +1,7 @@
import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { getControlPlaneEnvSync } from "../control-plane/env";
import { DataLogger } from "../data/log";
import { Telemetry } from "../util/posthog";
import { NextEditOutcome } from "./types";
@ -93,6 +95,9 @@ export class NextEditLoggingService {
outcome.accepted = true;
outcome.aborted = false;
this.logNextEditOutcome(outcome);
if (outcome.requestId) {
void this.logAcceptReject(outcome.requestId, true);
}
this._outcomes.delete(completionId);
return outcome;
}
@ -111,6 +116,9 @@ export class NextEditLoggingService {
outcome.accepted = false;
outcome.aborted = false;
this.logNextEditOutcome(outcome);
if (outcome.requestId) {
void this.logAcceptReject(outcome.requestId, false);
}
this._outcomes.delete(completionId);
return outcome;
}
@ -121,6 +129,7 @@ export class NextEditLoggingService {
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
this._logRejectionTimeouts.delete(completionId);
}
if (this._outcomes.has(completionId)) {
this._outcomes.delete(completionId);
}
@ -142,6 +151,9 @@ export class NextEditLoggingService {
outcome.accepted = false;
outcome.aborted = false;
this.logNextEditOutcome(outcome);
if (outcome.requestId) {
void this.logAcceptReject(outcome.requestId, false);
}
this._logRejectionTimeouts.delete(completionId);
this._outcomes.delete(completionId);
}, COUNT_COMPLETION_REJECTED_AFTER);
@ -245,4 +257,30 @@ export class NextEditLoggingService {
// const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture("nextEditOutcome", outcome, true);
}
private async logAcceptReject(
requestId: string,
accepted: boolean,
): Promise<void> {
try {
if (!Telemetry.client) {
return;
}
const controlPlaneEnv = getControlPlaneEnvSync("production");
await fetchwithRequestOptions(
new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
requestId,
accepted,
}),
},
);
} catch (error) {}
}
}

View file

@ -309,6 +309,7 @@ export abstract class BaseNextEditModelProvider {
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await outcomeCtx.ide.getUniqueId(),
requestId: outcomeCtx.llm.lastRequestId,
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:

View file

@ -50,6 +50,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
completionId: string;
gitRepo?: string;
uniqueId: string;
requestId?: string;
timestamp: number;
// New for Next Edit.

View file

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

View file

@ -192,13 +192,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");
console.debug("completionContent is not null");
const editor = vscode.window.activeTextEditor;
if (editor) {
try {
const completionLines = completionContent.split("\n");
console.log("completionLines:", completionLines);
console.debug("completionLines:", completionLines);
// Get document content at jump location spanning multiple lines.
const document = editor.document;
@ -212,7 +212,7 @@ export class JumpManager {
if (endLine - startLine + 1 < completionLines.length) {
// Not enough lines in document, so content can't be identical.
// Proceed to jump!
console.log(
console.debug(
"Not enough lines in document to match completion content",
);
} else {
@ -224,12 +224,12 @@ export class JumpManager {
const lineText = document.lineAt(documentLine).text;
if (lineText !== completionLines[i]) {
contentMatches = false;
console.log(`Line ${i + 1} doesn't match`);
console.debug(`Line ${i + 1} doesn't match`);
}
}
if (contentMatches) {
console.log(
console.debug(
"Skipping jump as content is identical at jump location",
);
return false; // Exit early, don't suggest jump.
@ -242,20 +242,20 @@ export class JumpManager {
}
}
console.log("this._jumpInProgress");
console.debug("this._jumpInProgress");
this._jumpInProgress = true;
this._oldCursorPosition = currentPosition;
const editor = vscode.window.activeTextEditor;
if (!editor) {
console.log("No active editor, cannot suggest jump");
console.debug("No active editor, cannot suggest jump");
this._jumpInProgress = false;
return false;
}
const visibleRanges = editor.visibleRanges;
if (visibleRanges.length === 0) {
console.log("No visible ranges in editor, cannot suggest jump");
console.debug("No visible ranges in editor, cannot suggest jump");
this._jumpInProgress = false;
return false;
}
@ -375,7 +375,7 @@ export class JumpManager {
"continue.rejectJump",
async () => {
if (this._jumpDecorationVisible) {
console.log(
console.debug(
"deleteChain from JumpManager.ts: rejectJump and decoration visible",
);
NextEditProvider.getInstance().deleteChain();
@ -447,7 +447,7 @@ export class JumpManager {
"jumpManager",
async (e, state) => {
if (state.jumpInProgress || state.jumpJustAccepted) {
console.log(
console.debug(
"JumpManager: jump in progress or just accepted, preserving chain",
);
return true;

View file

@ -165,7 +165,7 @@ export class NextEditWindowManager {
private constructor() {
this.theme = getThemeString();
console.log(
console.debug(
"Next Edit Theme initialized:",
this.theme
? `Theme exists: ${JSON.stringify(this.theme)}`
@ -269,7 +269,7 @@ export class NextEditWindowManager {
// Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => {
console.log(
console.debug(
"deleteChain from NextEditWindowManager.ts: hide next edit command",
);
NextEditProvider.getInstance().deleteChain();
@ -616,7 +616,7 @@ export class NextEditWindowManager {
) {
this.theme = getThemeString();
await this.codeRenderer.setTheme(this.theme);
console.log(
console.debug(
"Theme updated:",
this.theme ? "Theme exists" : "Theme is undefined",
);
@ -630,7 +630,7 @@ export class NextEditWindowManager {
vscode.window.onDidChangeActiveColorTheme(async () => {
this.theme = getThemeString();
await this.codeRenderer.setTheme(this.theme);
console.log(
console.debug(
"Active theme changed:",
this.theme ? "Theme exists" : "Theme is undefined",
);
@ -792,7 +792,7 @@ export class NextEditWindowManager {
// Check if line numbers are valid.
if (range.start.line < 0 || range.start.line >= doc.lineCount) {
console.log(
console.debug(
"Invalid start line:",
range.start.line,
"doc lines:",
@ -802,7 +802,7 @@ export class NextEditWindowManager {
}
if (range.end.line < 0 || range.end.line >= doc.lineCount) {
console.log(
console.debug(
"Invalid end line:",
range.end.line,
"doc lines:",
@ -819,7 +819,7 @@ export class NextEditWindowManager {
range.start.character < 0 ||
range.start.character > startLine.text.length
) {
console.log(
console.debug(
"Invalid start character:",
range.start.character,
"line length:",
@ -829,7 +829,7 @@ export class NextEditWindowManager {
}
if (range.end.character < 0 || range.end.character > endLine.text.length) {
console.log(
console.debug(
"Invalid end character:",
range.end.character,
"line length:",
@ -884,7 +884,7 @@ export class NextEditWindowManager {
// Check if document changed during async operation.
if (editor.document.version !== docVersion) {
console.log("Document changed during decoration creation, aborting");
console.debug("Document changed during decoration creation, aborting");
decoration.dispose();
return;
}
@ -991,7 +991,7 @@ export class NextEditWindowManager {
"nextEditWindowManager",
async (e, state) => {
if (state.nextEditWindowAccepted) {
console.log(
console.debug(
"NextEditWindowManager: Edit was just accepted, preserving chain",
);
return true;

View file

@ -330,7 +330,7 @@ export class SelectionChangeManager {
return false;
}
console.log(
console.debug(
"defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection",
);
await NextEditProvider.getInstance().deleteChain();

View file

@ -333,7 +333,7 @@ export class ContinueCompletionProvider
let chainExists = this.nextEditProvider.chainExists();
const processedCount = this.prefetchQueue.processedCount;
const unprocessedCount = this.prefetchQueue.unprocessedCount;
console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
console.debug("isJumping:", isJumping, "/ chainExists:", chainExists);
this.prefetchQueue.peekThreeProcessed();
let resetChainInFullFileDiff = false;
@ -351,7 +351,7 @@ export class ContinueCompletionProvider
if (isJumping && chainExists) {
// Case 2: Jumping (chain exists, jump was taken)
console.log("trigger reason: jumping");
console.debug("trigger reason: jumping");
// Reset jump state.
this.jumpManager.setJumpInProgress(false);
@ -380,7 +380,7 @@ export class ContinueCompletionProvider
}
} else if (chainExists) {
// Case 3: Accepting next edit outcome (chain exists, jump is not taken).
console.log("trigger reason: accepting");
console.debug("trigger reason: accepting");
// Try suggesting jump for each location.
let isJumpSuggested = false;
@ -428,7 +428,7 @@ export class ContinueCompletionProvider
}
if (!isJumpSuggested) {
console.log(
console.debug(
"No suitable jump location found after trying all positions",
);
this.nextEditProvider.deleteChain();
@ -642,7 +642,7 @@ export class ContinueCompletionProvider
if (isFim) {
if (!fimText) {
console.log("deleteChain from completionProvider.ts: !fimText");
console.debug("deleteChain from completionProvider.ts: !fimText");
this.nextEditProvider.deleteChain();
return undefined;
}
@ -679,7 +679,7 @@ export class ContinueCompletionProvider
// 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(
console.debug(
"deleteChain from completionProvider.ts: diffLines.length === 0",
);
NextEditProvider.getInstance().deleteChain();
@ -718,7 +718,7 @@ export class ContinueCompletionProvider
if (selectedCompletionInfo) {
const { text, range } = selectedCompletionInfo;
if (!outcome.completion.startsWith(text)) {
console.log(
console.debug(
`Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
range,
);

View file

@ -234,7 +234,9 @@ export class VsCodeExtension {
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
!NextEditWindowManager.getInstance().hasAccepted()
) {
console.log("VsCodeExtension: typing in progress, preserving chain");
console.debug(
"VsCodeExtension: typing in progress, preserving chain",
);
return true;
}
@ -533,7 +535,6 @@ export class VsCodeExtension {
});
vscode.workspace.onDidOpenTextDocument(async (event) => {
console.log("onDidOpenTextDocument");
const ast = await getAst(event.fileName, event.getText());
if (ast) {
DocumentHistoryTracker.getInstance().addDocument(

View file

@ -5,6 +5,7 @@ export const nextEditOutcomeEventAllSchema = baseDevDataAllSchema.extend({
elapsed: z.number(),
completionOptions: z.any(),
completionId: z.string(),
requestId: z.string().optional(),
gitRepo: z.string().optional(),
uniqueId: z.string(),
timestamp: z.number(),

View file

@ -14,6 +14,7 @@ export const nextEditOutcomeEventSchema_0_2_0 =
elapsed: true,
completionOptions: true,
completionId: true,
requestId: true,
gitRepo: true,
uniqueId: true,
// timestamp: z.number(),