Merge pull request #5907 from continuedev/dallin/cancelable-apply-2

This commit is contained in:
Nate Sesti 2025-06-19 00:03:43 -07:00 • committed by GitHub
commit cf54304e01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 190 additions and 98 deletions

View file

@ -25,6 +25,7 @@ export function slashFromCustomCommand(
config,
selectedCode,
fetch,
abortController,
}) {
// Render prompt template
let renderedPrompt: string;
@ -63,7 +64,7 @@ export function slashFromCustomCommand(
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
abortController.signal,
completionOptions,
)) {
yield renderChatMessage(chunk);

View file

@ -4,7 +4,7 @@ import { renderChatMessage } from "../../util/messageContent.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",
description: "Generate a commit message for current changes",
run: async function* ({ ide, llm, params }) {
run: async function* ({ ide, llm, params, abortController }) {
const includeUnstaged = params?.includeUnstaged ?? false;
const diff = await ide.getDiff(includeUnstaged);
@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = {
const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
abortController.signal,
)) {
yield renderChatMessage(chunk);
}

View file

@ -24,7 +24,7 @@ Body:\n\n`;
const DraftIssueCommand: SlashCommand = {
name: "issue",
description: "Draft a GitHub issue",
run: async function* ({ input, llm, history, params }) {
run: async function* ({ input, llm, history, params, abortController }) {
if (params?.repositoryUrl === undefined) {
yield "This command requires a repository URL to be set in the config file.";
return;
@ -46,7 +46,7 @@ const DraftIssueCommand: SlashCommand = {
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
abortController.signal,
)) {
body += chunk.content;
yield renderChatMessage(chunk);

View file

@ -60,7 +60,7 @@ export function constructMcpSlashCommand(
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);

View file

@ -41,7 +41,7 @@ const MAX_EXPLORE_DEPTH = 2;
const OnboardSlashCommand: SlashCommand = {
name: "onboard",
description: "Familiarize yourself with the codebase",
run: async function* ({ llm, ide }) {
run: async function* ({ llm, ide, abortController }) {
const [workspaceDir] = await ide.getWorkspaceDirs();
const context = await gatherProjectContext(workspaceDir, ide);
@ -49,7 +49,7 @@ const OnboardSlashCommand: SlashCommand = {
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
abortController.signal,
)) {
yield renderChatMessage(chunk);
}

View file

@ -38,14 +38,14 @@ function getLastUserHistory(history: ChatMessage[]): string {
const ReviewMessageCommand: SlashCommand = {
name: "review",
description: "Review code and give feedback",
run: async function* ({ llm, history }) {
run: async function* ({ llm, history, abortController }) {
const reviewText = getLastUserHistory(history).replace("\\review", "");
const content = `${prompt} \r\n ${reviewText}`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: content }],
new AbortController().signal,
abortController.signal,
)) {
yield renderChatMessage(chunk);
}

View file

@ -58,6 +58,7 @@ import {
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { ApplyAbortManager } from "./edit/applyAbortManager";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
@ -67,7 +68,6 @@ import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { StreamAbortManager } from "./util/abortManager";
import { getUriPathBasename } from "./util/uri";
const hasRulesFiles = (uris: string[]): boolean => {
@ -512,6 +512,11 @@ export class Core {
throw new Error("No model selected");
}
const abortManager = ApplyAbortManager.getInstance();
const abortController = abortManager.get(
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
@ -525,13 +530,13 @@ export class Core {
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
abortController,
});
});
on("cancelApply", async (msg) => {
const abortManager = StreamAbortManager.getInstance();
abortManager.clear();
const abortManager = ApplyAbortManager.getInstance();
abortManager.clear(); // for now abort all streams
});
on("onboarding/complete", this.handleCompleteOnboarding.bind(this));

View file

@ -1,16 +1,16 @@
export class StreamAbortManager {
private static instance: StreamAbortManager;
export class ApplyAbortManager {
private static instance: ApplyAbortManager;
private controllers: Map<string, AbortController>;
private constructor() {
this.controllers = new Map();
}
public static getInstance(): StreamAbortManager {
if (!StreamAbortManager.instance) {
StreamAbortManager.instance = new StreamAbortManager();
public static getInstance(): ApplyAbortManager {
if (!ApplyAbortManager.instance) {
ApplyAbortManager.instance = new ApplyAbortManager();
}
return StreamAbortManager.instance;
return ApplyAbortManager.instance;
}
public get(id: string): AbortController {

View file

@ -16,6 +16,7 @@ export async function applyCodeBlock(
newLazyFile: string,
filename: string,
llm: ILLM,
abortController: AbortController,
): Promise<{
isInstantApply: boolean;
diffLinesGenerator: AsyncGenerator<DiffLine>;
@ -51,6 +52,12 @@ export async function applyCodeBlock(
return {
isInstantApply: false,
diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
diffLinesGenerator: streamLazyApply(
oldFile,
filename,
newLazyFile,
llm,
abortController,
),
};
}

View file

@ -59,6 +59,7 @@ export async function* getReplacementWithLlm(
linesBefore: string[],
linesAfter: string[],
llm: ILLM,
abortController: AbortController,
): AsyncGenerator<string> {
const userPrompt = dedent`
ORIGINAL CODE:
@ -88,7 +89,7 @@ export async function* getReplacementWithLlm(
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
],
new AbortController().signal,
abortController.signal,
);
let lines = streamLines(completion);

View file

@ -16,6 +16,7 @@ export async function* streamLazyApply(
filename: string,
newCode: string,
llm: ILLM,
abortController: AbortController,
): AsyncGenerator<DiffLine> {
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
if (!promptFactory) {
@ -23,10 +24,7 @@ export async function* streamLazyApply(
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(
promptMessages,
new AbortController().signal,
);
const lazyCompletion = llm.streamChat(promptMessages, abortController.signal);
// Do find and replace over the lazy edit response
async function* replacementFunction(
@ -39,6 +37,7 @@ export async function* streamLazyApply(
linesBefore,
linesAfter,
llm,
abortController,
)) {
yield line;
}

View file

@ -20,7 +20,6 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { StreamAbortManager } from "../util/abortManager";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@ -64,7 +63,7 @@ export async function* streamDiffLines({
highlighted,
suffix,
llm,
abortControllerId,
abortController,
input,
language,
onlyOneInsertion,
@ -75,15 +74,13 @@ export async function* streamDiffLines({
highlighted: string;
suffix: string;
llm: ILLM;
abortControllerId: string;
abortController: AbortController;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
const abortManager = StreamAbortManager.getInstance();
const abortController = abortManager.get(abortControllerId);
void Telemetry.capture(
"inlineEdit",
{

3
core/index.d.ts vendored
View file

@ -833,6 +833,7 @@ export interface ContinueSDK {
config: ContinueConfig;
fetch: FetchFunction;
completionOptions?: LLMFullCompletionOptions;
abortController: AbortController;
}
export interface SlashCommand {
@ -1280,7 +1281,7 @@ export interface HighlightedCodePayload {
}
export interface AcceptOrRejectDiffPayload {
filepath: string;
filepath?: string;
streamId?: string;
}

View file

@ -85,6 +85,7 @@ export async function* llmStreamChat(
config.requestOptions,
),
completionOptions,
abortController,
});
let next = await gen.next();
while (!next.done) {

View file

@ -79,7 +79,7 @@ export function slashCommandFromPromptFileV1(
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);

View file

@ -239,7 +239,7 @@ data class StreamDiffLinesPayload(
)
data class AcceptOrRejectDiffPayload(
val filepath: String,
val filepath: String? = null,
val streamId: String? = null
)

View file

@ -3,6 +3,7 @@ import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
import { getUriPathBasename } from "core/util/uri";
import * as vscode from "vscode";
import { ApplyAbortManager } from "core/edit/applyAbortManager";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
@ -116,11 +117,16 @@ export class ApplyManager {
return;
}
const fileUri = editor.document.uri.toString();
const abortManager = ApplyAbortManager.getInstance();
const abortController = abortManager.get(fileUri);
const { isInstantApply, diffLinesGenerator } = await applyCodeBlock(
editor.document.getText(),
text,
getUriPathBasename(editor.document.uri.toString()),
getUriPathBasename(fileUri),
llm,
abortController,
);
if (isInstantApply) {

View file

@ -28,6 +28,7 @@ import {
} from "./autocomplete/statusBar";
import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider";
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
import { processDiff } from "./diff/processDiff";
import { VerticalDiffManager } from "./diff/vertical/manager";
import EditDecorationManager from "./quickEdit/EditDecorationManager";
import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick";
@ -86,56 +87,6 @@ function hideGUI() {
}
}
async function processDiff(
action: "accept" | "reject",
sidebar: ContinueGUIWebviewViewProvider,
ide: VsCodeIde,
core: Core,
verticalDiffManager: VerticalDiffManager,
newFileUri?: string,
streamId?: string,
toolCallId?: string,
) {
captureCommandTelemetry(`${action}Diff`);
const currentFile = await ide.getCurrentFile();
let newOrCurrentUri = newFileUri;
if (!newOrCurrentUri) {
newOrCurrentUri = currentFile?.path;
}
if (!newOrCurrentUri) {
console.warn(
`No file provided or current file open while attempting to resolve diff`,
);
return;
}
await ide.openFile(newOrCurrentUri);
// Clear vertical diffs depending on action
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
if (action === "reject") {
core.invoke("cancelApply", undefined);
}
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: newOrCurrentUri,
streamId,
status: "closed",
numDiffs: 0,
toolCallId,
});
}
// Save the file
await ide.saveFile(newOrCurrentUri);
}
function waitForSidebarReady(
sidebar: ContinueGUIWebviewViewProvider,
timeout: number,
@ -226,8 +177,9 @@ const getCommandsMap: (
}
return {
"continue.acceptDiff": async (newFileUri?: string, streamId?: string) =>
processDiff(
"continue.acceptDiff": async (newFileUri?: string, streamId?: string) => {
captureCommandTelemetry("acceptDiff");
void processDiff(
"accept",
sidebar,
ide,
@ -235,10 +187,12 @@ const getCommandsMap: (
verticalDiffManager,
newFileUri,
streamId,
),
);
},
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
processDiff(
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) => {
captureCommandTelemetry("rejectDiff");
void processDiff(
"reject",
sidebar,
ide,
@ -246,7 +200,8 @@ const getCommandsMap: (
verticalDiffManager,
newFileUri,
streamId,
),
);
},
"continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
captureCommandTelemetry("acceptVerticalDiffBlock");
verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index);

View file

@ -0,0 +1,52 @@
import { Core } from "core/core";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
import { VsCodeIde } from "../VsCodeIde";
import { VerticalDiffManager } from "./vertical/manager";
export async function processDiff(
action: "accept" | "reject",
sidebar: ContinueGUIWebviewViewProvider,
ide: VsCodeIde,
core: Core,
verticalDiffManager: VerticalDiffManager,
newFileUri?: string,
streamId?: string,
toolCallId?: string,
) {
let newOrCurrentUri = newFileUri;
if (!newOrCurrentUri) {
const currentFile = await ide.getCurrentFile();
newOrCurrentUri = currentFile?.path;
}
if (!newOrCurrentUri) {
console.warn(
`No file provided or current file open while attempting to resolve diff`,
);
return;
}
await ide.openFile(newOrCurrentUri);
// Clear vertical diffs depending on action
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
if (action === "reject") {
// this is so that IDE reject diff command can also cancel apply
core.invoke("cancelApply", undefined);
}
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: newOrCurrentUri,
streamId,
status: "closed",
numDiffs: 0,
toolCallId,
});
}
// Save the file
await ide.saveFile(newOrCurrentUri);
}

View file

@ -10,6 +10,7 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { handleLLMError } from "../../util/errorHandling";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
import { ApplyAbortManager } from "core/edit/applyAbortManager";
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
export interface VerticalDiffCodeLens {
@ -437,6 +438,9 @@ export class VerticalDiffManager {
this.editDecorationManager.clear();
const abortManager = ApplyAbortManager.getInstance();
const abortController = abortManager.get(fileUri);
try {
const streamedLines: string[] = [];
@ -451,7 +455,7 @@ export class VerticalDiffManager {
language: getMarkdownLanguageTagForFile(fileUri),
onlyOneInsertion: !!onlyOneInsertion,
overridePrompt,
abortControllerId: fileUri,
abortController,
});
for await (const line of stream) {
@ -467,6 +471,10 @@ export class VerticalDiffManager {
// enable a listener for user edits to file while diff is open
this.enableDocumentChangeListener();
if (abortController.signal.aborted) {
vscode.commands.executeCommand("continue.rejectDiff");
}
return `${prefix}${streamedLines.join("\n")}${suffix}`;
} catch (e) {
this.disableDocumentChangeListener();

View file

@ -2,11 +2,13 @@ import { AnimatedEllipsis } from "../../..";
export function GeneratingIndicator({
text = "Generating",
testId,
}: {
text?: string;
testId?: string;
}) {
return (
<div className="text-description-muted text-xs">
<div className="text-description-muted text-xs" data-testid={testId}>
<span>{text}</span>
<AnimatedEllipsis />
</div>

View file

@ -1,24 +1,29 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch } from "../../../../redux/hooks";
import { cancelStream } from "../../../../redux/thunks";
import { getAltKeyLabel, getMetaKeyLabel } from "../../../../util";
import { Container, StopButton } from "./components";
import { GeneratingIndicator } from "./GeneratingIndicator";
export const IsApplyingToolbar = () => {
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useAppDispatch();
const jetbrains = window.location.protocol === "jb-api:";
return (
<Container>
<GeneratingIndicator text="Applying" />
<GeneratingIndicator text="Applying" testId={"notch-applying-text"} />
<StopButton
data-testid="notch-applying-cancel-button"
className="text-description"
onClick={() => {
// Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
// Apply is prioritized because it can be more catastrophic
// Intentional to be more WYSIWYG for now
ideMessenger.post("cancelApply", undefined);
// Keyboard shortcut is handled in chat
void dispatch(cancelStream());
ideMessenger.post("rejectDiff", {});
}}
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}

View file

@ -106,4 +106,56 @@ describe("Chat page test", () => {
).not.toBeInTheDocument();
});
});
it("should show apply cancellation", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Spy on the request method of ideMessenger
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
// Wait for applying toolbar to appear
await waitFor(() => {
const cancelApplyButton = screen.getByTestId(
"notch-applying-cancel-button",
);
const applyingText = screen.getByTestId("notch-applying-text");
expect(cancelApplyButton).toBeInTheDocument();
expect(applyingText).toBeInTheDocument();
});
const cancelApplyButton = screen.getByTestId(
"notch-applying-cancel-button",
);
cancelApplyButton.click();
// Verify that rejectDiff message has been posted to ideMessenger
expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
// Now simulate the IDE sending back a message that the apply state is closed
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
await waitFor(() => {
const cancelApplyButton = screen.queryByTestId(
"notch-applying-cancel-button",
);
const applyingText = screen.queryByTestId("notch-applying-text");
expect(cancelApplyButton).not.toBeInTheDocument();
expect(applyingText).not.toBeInTheDocument();
});
// Cleanup spy
messengerPostSpy.mockRestore();
});
});

View file

@ -132,7 +132,7 @@ export function Chat() {
!e.shiftKey
) {
dispatch(cancelStream());
ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
ideMessenger.post("rejectDiff", {}); // just always cancel, if not in applying won't matter
}
};
window.addEventListener("keydown", listener);

View file

@ -35,7 +35,7 @@ export const streamResponseAfterToolCall = createAsyncThunk<
const toolCallState = findToolCall(state.session.history, toolCallId);
if (!toolCallState) {
throw new Error("Tool call not found");
return; // in cases where edit tool is cancelled mid apply, this will be triggered
}
const toolOutput = toolCallState.output ?? [];