Elffuss BraidHub

kikocis/continue public

Merge pull request #5694 from continuedev/dallin/cancelable-apply

Make Apply Streaming Cancelable
Changeset54ea0739010d8625499eca7bf32cf7681d5e637b24f4beb67c323ca6fcd39ff4
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-05-25 16:33 -07:00
CommitterGitHub <noreply@github.com> · 2025-05-25 16:33 -07:00
Parents158decf78aee, ea74bf50486d

Browse the files at this changeset

56 files changed

modified core/commands/slash/http.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { SlashCommand } from "../../index.js";
23 import { removeQuotesAndEscapes } from "../../util/index.js";
3-import { streamResponse } from "../../llm/stream.js";
44
55 const HttpSlashCommand: SlashCommand = {
66 name: "http",
modified core/core.ts +65 −70
@@ -35,7 +35,6 @@
3535
3636 import {
3737 ContextItemWithId,
38- DiffLine,
3938 IdeSettings,
4039 ModelDescription,
4140 RangeInFile,
@@ -62,61 +61,7 @@
6261 import { llmStreamChat } from "./llm/streamChat";
6362 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
6463 import type { IMessenger, Message } from "./protocol/messenger";
65-
66-// This function is used for jetbrains inline edit and apply
67-async function* streamDiffLinesGenerator(
68- configHandler: ConfigHandler,
69- abortedMessageIds: Set<string>,
70- msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
71-): AsyncGenerator<DiffLine> {
72- const {
73- highlighted,
74- prefix,
75- suffix,
76- input,
77- language,
78- modelTitle,
79- includeRulesInSystemMessage,
80- } = msg.data;
81-
82- const { config } = await configHandler.loadConfig();
83- if (!config) {
84- throw new Error("Failed to load config");
85- }
86-
87- // Title can be an edit, chat, or apply model
88- // Fall back to chat
89- const llm =
90- config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
91- config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
92- config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
93- config.selectedModelByRole.chat;
94-
95- if (!llm) {
96- throw new Error("No model selected");
97- }
98-
99- // rules included for edit, NOT apply
100- const rules = includeRulesInSystemMessage ? config.rules : undefined;
101-
102- for await (const diffLine of streamDiffLines({
103- highlighted,
104- prefix,
105- suffix,
106- llm,
107- rulesToInclude: rules,
108- input,
109- language,
110- onlyOneInsertion: false,
111- overridePrompt: undefined,
112- })) {
113- if (abortedMessageIds.has(msg.messageId)) {
114- abortedMessageIds.delete(msg.messageId);
115- break;
116- }
117- yield diffLine;
118- }
119-}
64+import { StreamAbortManager } from "./util/abortManager";
12065
12166 export class Core {
12267 configHandler: ConfigHandler;
@@ -132,7 +77,18 @@
13277 this.globalContext.get("indexingPaused") === true,
13378 );
13479
135- private abortedMessageIds: Set<string> = new Set();
80+ private messageAbortControllers = new Map<string, AbortController>();
81+ private addMessageAbortController(id: string): AbortController {
82+ const controller = new AbortController();
83+ this.messageAbortControllers.set(id, controller);
84+ controller.signal.addEventListener("abort", () => {
85+ this.messageAbortControllers.delete(id);
86+ });
87+ return controller;
88+ }
89+ private abortById(messageId: string) {
90+ this.messageAbortControllers.get(messageId)?.abort();
91+ }
13692
13793 invoke<T extends keyof ToCoreProtocol>(
13894 messageType: T,
@@ -301,7 +257,7 @@
301257 });
302258
303259 on("abort", (msg) => {
304- this.abortedMessageIds.add(msg.messageId);
260+ this.abortById(msg.data ?? msg.messageId);
305261 });
306262
307263 on("ping", (msg) => {
@@ -470,27 +426,28 @@
470426 }
471427 });
472428
473- on("llm/streamChat", (msg) =>
474- llmStreamChat(
429+ on("llm/streamChat", (msg) => {
430+ const abortController = this.addMessageAbortController(msg.messageId);
431+ return llmStreamChat(
475432 this.configHandler,
476- this.abortedMessageIds,
433+ abortController,
477434 msg,
478435 this.ide,
479436 this.messenger,
480- ),
481- );
437+ );
438+ });
482439
483440 on("llm/complete", async (msg) => {
484- const model = (await this.configHandler.loadConfig()).config
485- ?.selectedModelByRole.chat;
486-
441+ const { config } = await this.configHandler.loadConfig();
442+ const model = config?.selectedModelByRole.chat;
487443 if (!model) {
488444 throw new Error("No chat model selected");
489445 }
446+ const abortController = this.addMessageAbortController(msg.messageId);
490447
491448 const completion = await model.complete(
492449 msg.data.prompt,
493- new AbortController().signal,
450+ abortController.signal,
494451 msg.data.completionOptions,
495452 );
496453 return completion;
@@ -532,9 +489,47 @@
532489 this.completionProvider.cancel();
533490 });
534491
535- on("streamDiffLines", (msg) =>
536- streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
537- );
492+ on("streamDiffLines", async (msg) => {
493+ const { config } = await this.configHandler.loadConfig();
494+ if (!config) {
495+ throw new Error("Failed to load config");
496+ }
497+
498+ const { data } = msg;
499+
500+ // Title can be an edit, chat, or apply model
501+ // Fall back to chat
502+ const llm =
503+ config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
504+ config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
505+ config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
506+ config.selectedModelByRole.chat;
507+
508+ if (!llm) {
509+ throw new Error("No model selected");
510+ }
511+
512+ return streamDiffLines({
513+ highlighted: data.highlighted,
514+ prefix: data.prefix,
515+ suffix: data.suffix,
516+ llm,
517+ // rules included for edit, NOT apply
518+ rulesToInclude: data.includeRulesInSystemMessage
519+ ? config.rules
520+ : undefined,
521+ input: data.input,
522+ language: data.language,
523+ onlyOneInsertion: false,
524+ overridePrompt: undefined,
525+ abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
526+ });
527+ });
528+
529+ on("cancelApply", async (msg) => {
530+ const abortManager = StreamAbortManager.getInstance();
531+ abortManager.clear();
532+ });
538533
539534 on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
540535
modified core/edit/recursiveStream.ts +5 −2
@@ -16,6 +16,7 @@
1616
1717 export async function* recursiveStream(
1818 llm: ILLM,
19+ abortController: AbortController,
1920 prompt: ChatMessage[] | string,
2021 prediction: Prediction | undefined,
2122 currentBuffer = "",
@@ -28,7 +29,7 @@
2829 // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
2930
3031 if (typeof prompt === "string") {
31- const generator = llm.streamComplete(prompt, new AbortController().signal, {
32+ const generator = llm.streamComplete(prompt, abortController.signal, {
3233 raw: true,
3334 prediction: undefined,
3435 reasoning: false,
@@ -50,6 +51,7 @@
5051 // // TODO - Prediction capabilities lost because of partial input
5152 // yield* recursiveStream(
5253 // llm,
54+ // abortController,
5355 // continuationPrompt,
5456 // undefined,
5557 // buffer,
@@ -60,7 +62,7 @@
6062 }
6163 }
6264 } else {
63- const generator = llm.streamChat(prompt, new AbortController().signal, {
65+ const generator = llm.streamChat(prompt, abortController.signal, {
6466 prediction,
6567 reasoning: false,
6668 });
@@ -90,6 +92,7 @@
9092 // await generator.return(DUD_PROMPT_LOG);
9193 // yield* recursiveStream(
9294 // llm,
95+ // abortController,
9396 // continuationPrompt,
9497 // undefined,
9598 // buffer,
modified core/edit/streamDiffLines.ts +6 −1
@@ -20,6 +20,7 @@
2020 import { streamLines } from "../diff/util";
2121 import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
2222 import { gptEditPrompt } from "../llm/templates/edit";
23+import { StreamAbortManager } from "../util/abortManager";
2324 import { findLast } from "../util/findLast";
2425 import { Telemetry } from "../util/posthog";
2526 import { recursiveStream } from "./recursiveStream";
@@ -63,6 +64,7 @@
6364 highlighted,
6465 suffix,
6566 llm,
67+ abortControllerId,
6668 input,
6769 language,
6870 onlyOneInsertion,
@@ -73,12 +75,15 @@
7375 highlighted: string;
7476 suffix: string;
7577 llm: ILLM;
78+ abortControllerId: string;
7679 input: string;
7780 language: string | undefined;
7881 onlyOneInsertion: boolean;
7982 overridePrompt: ChatMessage[] | undefined;
8083 rulesToInclude: RuleWithSource[] | undefined;
8184 }): AsyncGenerator<DiffLine> {
85+ const abortManager = StreamAbortManager.getInstance();
86+ const abortController = abortManager.get(abortControllerId);
8287 void Telemetry.capture(
8388 "inlineEdit",
8489 {
@@ -158,7 +163,7 @@
158163 content: highlighted,
159164 };
160165
161- const completion = recursiveStream(llm, prompt, prediction);
166+ const completion = recursiveStream(llm, abortController, prompt, prediction);
162167
163168 let lines = streamLines(completion);
164169
modified core/index.d.ts +1 −0
@@ -1240,6 +1240,7 @@
12401240 language: string | undefined;
12411241 modelTitle: string | undefined;
12421242 includeRulesInSystemMessage: boolean;
1243+ fileUri?: string;
12431244 }
12441245
12451246 export interface HighlightedCodePayload {
modified core/llm/index.ts +3 −0
@@ -382,6 +382,9 @@
382382
383383 // Error mapping to be more helpful
384384 if (!resp.ok) {
385+ if (resp.status === 499) {
386+ return resp; // client side cancellation
387+ }
385388 let text = await resp.text();
386389 if (resp.status === 404 && !resp.url.includes("/v1")) {
387390 const error = JSON.parse(text)?.error?.replace(/"/g, "'");
modified core/llm/llms/Anthropic.ts +5 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
23 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 class Anthropic extends BaseLLM {
77 static providerName = "anthropic";
@@ -213,6 +213,10 @@
213213 signal,
214214 });
215215
216+ if (response.status === 499) {
217+ return; // Aborted by user
218+ }
219+
216220 if (!response.ok) {
217221 const json = await response.json();
218222 if (json.type === "error") {
modified core/llm/llms/Asksage.ts +4 −8
@@ -134,10 +134,8 @@
134134 body: JSON.stringify(args),
135135 });
136136
137- if (!response.ok) {
138- throw new Error(
139- `API request failed with status ${response.status}: ${response.statusText}`,
140- );
137+ if (response.status === 499) {
138+ return ""; // Aborted by user
141139 }
142140
143141 const data = await response.json();
@@ -167,10 +165,8 @@
167165 signal,
168166 });
169167
170- if (!response.ok) {
171- throw new Error(
172- `API request failed with status ${response.status}: ${response.statusText}`,
173- );
168+ if (response.status === 499) {
169+ return; // Aborted by user
174170 }
175171
176172 const data = await response.json();
modified core/llm/llms/Cloudflare.ts +1 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions } from "../../index.js";
23 import { renderChatMessage } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 export default class Cloudflare extends BaseLLM {
77 static providerName = "cloudflare";
modified core/llm/llms/Cohere.ts +5 −1
@@ -1,3 +1,4 @@
1+import { streamJSON } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
@@ -6,7 +7,6 @@
67 } from "../../index.js";
78 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
89 import { BaseLLM } from "../index.js";
9-import { streamJSON } from "../stream.js";
1010
1111 class Cohere extends BaseLLM {
1212 static providerName = "cohere";
@@ -84,6 +84,10 @@
8484 signal,
8585 });
8686
87+ if (resp.status === 499) {
88+ return; // Aborted by user
89+ }
90+
8791 if (options.stream === false) {
8892 const data = await resp.json();
8993 yield { role: "assistant", content: data.text };
modified core/llm/llms/Deepseek.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Flowise.ts +7 −3
@@ -132,12 +132,16 @@
132132 ): AsyncGenerator<ChatMessage> {
133133 const requestBody = this._getRequestBody(messages, options);
134134 const { socket, socketInfo } = await this._initializeSocket();
135- const request = this.fetch(this._getChatUrl(), {
135+ const response = await this.fetch(this._getChatUrl(), {
136136 method: "POST",
137137 headers: this._getHeaders(),
138138 body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
139139 signal,
140- }).then((res) => res.json());
140+ });
141+
142+ if (response.status === 499) {
143+ return; // Aborted by user
144+ }
141145
142146 while (await socketInfo.hasNextToken()) {
143147 yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@@ -145,7 +149,7 @@
145149 if (socketInfo.error) {
146150 socket.disconnect();
147151 try {
148- yield { role: "assistant", content: (await request).text };
152+ yield { role: "assistant", content: await response.text() };
149153 } catch (error: any) {
150154 yield { role: "assistant", content: (error as Error).message ?? error };
151155 }
modified core/llm/llms/FreeTrial.ts +1 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
23 import { getHeaders } from "../../continueServer/stubs/headers.js";
34 import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@@ -8,7 +9,6 @@
89 LLMOptions,
910 } from "../../index.js";
1011 import { BaseLLM } from "../index.js";
11-import { streamResponse } from "../stream.js";
1212
1313 class FreeTrial extends BaseLLM {
1414 static providerName = "free-trial";
modified core/llm/llms/Gemini.ts +4 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { v4 as uuidv4 } from "uuid";
23 import {
34 AssistantChatMessage,
@@ -10,7 +11,6 @@
1011 } from "../../index.js";
1112 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
1213 import { BaseLLM } from "../index.js";
13-import { streamResponse } from "../stream.js";
1414 import {
1515 GeminiChatContent,
1616 GeminiChatContentPart,
@@ -438,6 +438,9 @@
438438 body: JSON.stringify(body),
439439 signal,
440440 });
441+ if (response.status === 499) {
442+ return; // Aborted by user
443+ }
441444 const data = await response.json();
442445 yield { role: "assistant", content: data.candidates[0].content };
443446 }
modified core/llm/llms/HuggingFaceInferenceAPI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceInferenceAPI extends BaseLLM {
66 static providerName = "huggingface-inference-api";
modified core/llm/llms/HuggingFaceTGI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceTGI extends BaseLLM {
66 private static MAX_STOP_TOKENS = 4;
modified core/llm/llms/Inception.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33
44 import OpenAI from "./OpenAI.js";
55
modified core/llm/llms/LlamaCpp.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class LlamaCpp extends BaseLLM {
66 static providerName = "llama.cpp";
modified core/llm/llms/Moonshot.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Ollama.ts +4 −1
@@ -2,6 +2,7 @@
22 import { JSONSchema7, JSONSchema7Object } from "json-schema";
33 import { v4 as uuidv4 } from "uuid";
44
5+import { streamResponse } from "@continuedev/fetch";
56 import {
67 ChatMessage,
78 ChatMessageRole,
@@ -12,7 +13,6 @@
1213 import { renderChatMessage } from "../../util/messageContent.js";
1314 import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
1415 import { BaseLLM } from "../index.js";
15-import { streamResponse } from "../stream.js";
1616
1717 type OllamaChatMessage = {
1818 role: ChatMessageRole;
@@ -457,6 +457,9 @@
457457 }
458458
459459 if (chatOptions.stream === false) {
460+ if (response.status === 499) {
461+ return; // Aborted by user
462+ }
460463 const json = (await response.json()) as OllamaChatResponse;
461464 yield convertChatMessage(json);
462465 } else {
modified core/llm/llms/OpenAI.ts +4 −1
@@ -3,6 +3,7 @@
33 ChatCompletionMessageParam,
44 } from "openai/resources/index";
55
6+import { streamSse } from "@continuedev/fetch";
67 import {
78 ChatMessage,
89 CompletionOptions,
@@ -16,7 +17,6 @@
1617 LlmApiRequestType,
1718 toChatBody,
1819 } from "../openaiTypeConverters.js";
19-import { streamSse } from "../stream.js";
2020
2121 const NON_CHAT_MODELS = [
2222 "text-davinci-002",
@@ -352,6 +352,9 @@
352352
353353 // Handle non-streaming response
354354 if (body.stream === false) {
355+ if (response.status === 499) {
356+ return; // Aborted by user
357+ }
355358 const data = await response.json();
356359 yield data.choices[0].message;
357360 return;
modified core/llm/llms/SiliconFlow.ts +2 −2
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
@@ -58,7 +58,7 @@
5858 console.warn("[SiliconFlow] rerank: query is empty");
5959 return [];
6060 }
61-
61+
6262 if (!chunks || chunks.length === 0) {
6363 console.warn("[SiliconFlow] rerank: chunks is empty");
6464 return [];
modified core/llm/llms/VertexAI.ts +23 −5
@@ -1,9 +1,9 @@
11 import { GoogleAuth } from "google-auth-library";
22
3+import { streamResponse, streamSse } from "@continuedev/fetch";
34 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
45 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
56 import { BaseLLM } from "../index.js";
6-import { streamResponse, streamSse } from "../stream.js";
77
88 import Anthropic from "./Anthropic.js";
99 import Gemini from "./Gemini.js";
@@ -95,6 +95,7 @@
9595 protected async *StreamChatAnthropic(
9696 messages: ChatMessage[],
9797 options: CompletionOptions,
98+ signal: AbortSignal,
9899 ): AsyncGenerator<ChatMessage> {
99100 const systemMessage = stripImages(
100101 messages.filter((m) => m.role === "system")[0]?.content ?? "",
@@ -128,8 +129,13 @@
128129 ]
129130 : systemMessage,
130131 }),
132+ signal,
131133 });
132134
135+ if (response.status === 499) {
136+ return; // Aborted by user
137+ }
138+
133139 if (options.stream === false) {
134140 const data = await response.json();
135141 yield { role: "assistant", content: data.content[0].text };
@@ -150,6 +156,7 @@
150156 private async *streamChatGemini(
151157 messages: ChatMessage[],
152158 options: CompletionOptions,
159+ signal: AbortSignal,
153160 ): AsyncGenerator<ChatMessage> {
154161 const apiURL = new URL(
155162 `publishers/google/models/${options.model}:streamGenerateContent`,
@@ -160,6 +167,7 @@
160167 const response = await this.fetch(apiURL, {
161168 method: "POST",
162169 body: JSON.stringify(body),
170+ signal,
163171 });
164172 for await (const message of this.geminiInstance.processGeminiResponse(
165173 streamResponse(response),
@@ -171,6 +179,7 @@
171179 private async *streamChatBison(
172180 messages: ChatMessage[],
173181 options: CompletionOptions,
182+ signal: AbortSignal,
174183 ): AsyncGenerator<ChatMessage> {
175184 const instances = messages.map((message) => ({ prompt: message.content }));
176185
@@ -193,7 +202,11 @@
193202 const response = await this.fetch(apiURL, {
194203 method: "POST",
195204 body: JSON.stringify(body),
205+ signal,
196206 });
207+ if (response.status === 499) {
208+ return; // Aborted by user
209+ }
197210 const data = await response.json();
198211 yield { role: "assistant", content: data.predictions[0].content };
199212 }
@@ -203,6 +216,7 @@
203216 protected async *StreamChatMistral(
204217 messages: ChatMessage[],
205218 options: CompletionOptions,
219+ signal: AbortSignal,
206220 ): AsyncGenerator<ChatMessage> {
207221 const apiBase = this.apiBase!;
208222 const apiURL = new URL(
@@ -228,6 +242,7 @@
228242 const response = await this.fetch(apiURL, {
229243 method: "POST",
230244 body: JSON.stringify(body),
245+ signal,
231246 });
232247
233248 for await (const chunk of streamSse(response)) {
@@ -304,6 +319,9 @@
304319 }),
305320 signal,
306321 });
322+ if (resp.status === 499) {
323+ return; // Aborted by user
324+ }
307325 // Streaming is not supported by code-gecko
308326 // TODO: convert to non-streaming fim method when one exist in continue.
309327 yield (await resp.json()).predictions[0].content;
@@ -323,14 +341,14 @@
323341 ? this.geminiInstance.removeSystemMessage(messages)
324342 : messages;
325343 if (this.vertexProvider === "gemini") {
326- yield* this.streamChatGemini(convertedMsgs, options);
344+ yield* this.streamChatGemini(convertedMsgs, options, signal);
327345 } else if (this.vertexProvider === "mistral") {
328- yield* this.StreamChatMistral(messages, options);
346+ yield* this.StreamChatMistral(messages, options, signal);
329347 } else if (this.vertexProvider === "anthropic") {
330- yield* this.StreamChatAnthropic(messages, options);
348+ yield* this.StreamChatAnthropic(messages, options, signal);
331349 } else {
332350 if (options.model.includes("bison")) {
333- yield* this.streamChatBison(convertedMsgs, options);
351+ yield* this.streamChatBison(convertedMsgs, options, signal);
334352 } else {
335353 throw new Error(`Unsupported model: ${options.model}`);
336354 }
modified core/llm/llms/WatsonX.ts +37 −53
@@ -1,15 +1,12 @@
1+import { streamResponse, streamSse } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
45 CompletionOptions,
56 LLMOptions,
67 } from "../../index.js";
7-import {
8- fromChatCompletionChunk,
9-} from "../openaiTypeConverters.js";
10-import { renderChatMessage } from "../../util/messageContent.js";
118 import { BaseLLM } from "../index.js";
12-import { streamResponse, streamSse } from "../stream.js";
9+import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
1310
1411 let watsonxToken = {
1512 expiration: 0,
@@ -86,7 +83,7 @@
8683 }
8784
8885 _getEndpoint(endpoint: string): string {
89- return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
86+ return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
9087 }
9188
9289 static providerName = "watsonx";
@@ -182,7 +179,6 @@
182179 signal: AbortSignal,
183180 options: CompletionOptions,
184181 ): AsyncGenerator<string> {
185-
186182 await this.updateWatsonxToken();
187183
188184 const stopSequences = options.stop?.slice(0, 6) ?? [];
@@ -214,44 +210,38 @@
214210 payload.project_id = this.projectId;
215211 }
216212
217- var response = await this.fetch(url, {
213+ const response = await this.fetch(url, {
218214 method: "POST",
219215 headers: headers,
220216 body: JSON.stringify(payload),
221217 signal,
222218 });
223219
224- if (!response.ok || response.body === null) {
225- throw new Error(
226- "Something went wrong. No response received, check your connection",
227- );
228- } else {
229- for await (const value of streamResponse(response)) {
230- const lines = value.split("\n");
231- let generatedChunk = "";
232- let generatedTextIndex = undefined;
233- lines.forEach((el: string) => {
234- // console.log(`${el}`);
235- if (el.startsWith("id:")) {
236- generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
237- if (isNaN(generatedTextIndex)) {
238- console.error(`Unable to parse stream chunk ID: ${el}`);
239- }
240- } else if (el.startsWith("data:")) {
241- const dataStr = el.replace(/^data:\s+/, "");
242- try {
243- const data = JSON.parse(dataStr);
244- data.results.forEach((result: any) => {
245- generatedChunk += result.generated_text || "";
246- });
247- } catch (e) {
248- // parsing error is expected with streaming response
249- // console.error(`Error parsing JSON string: ${dataStr}`, e);
250- }
220+ for await (const value of streamResponse(response)) {
221+ const lines = value.split("\n");
222+ let generatedChunk = "";
223+ let generatedTextIndex = undefined;
224+ lines.forEach((el: string) => {
225+ // console.log(`${el}`);
226+ if (el.startsWith("id:")) {
227+ generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
228+ if (isNaN(generatedTextIndex)) {
229+ console.error(`Unable to parse stream chunk ID: ${el}`);
251230 }
252- });
253- yield generatedChunk
254- }
231+ } else if (el.startsWith("data:")) {
232+ const dataStr = el.replace(/^data:\s+/, "");
233+ try {
234+ const data = JSON.parse(dataStr);
235+ data.results.forEach((result: any) => {
236+ generatedChunk += result.generated_text || "";
237+ });
238+ } catch (e) {
239+ // parsing error is expected with streaming response
240+ // console.error(`Error parsing JSON string: ${dataStr}`, e);
241+ }
242+ }
243+ });
244+ yield generatedChunk;
255245 }
256246 }
257247
@@ -267,7 +257,7 @@
267257 const headers = this._getHeaders();
268258
269259 const payload: any = {
270- messages: messages,
260+ messages: messages,
271261 max_tokens: options.maxTokens ?? 1024,
272262 stop: stopSequences,
273263 frequency_penalty: options.frequencyPenalty || 1,
@@ -281,36 +271,30 @@
281271
282272 if (!!options.temperature) {
283273 payload.temperature = options.temperature;
284- }
274+ }
285275 if (!!options.topP) {
286276 payload.top_p = options.topP;
287277 }
288278 if (!!options.tools) {
289279 payload.tools = options.tools;
290280 if (options.toolChoice) {
291- payload.tool_choice = options.toolChoice;
281+ payload.tool_choice = options.toolChoice;
292282 } else {
293- payload.tool_choice_option = "auto";
283+ payload.tool_choice_option = "auto";
294284 }
295285 }
296286
297- var response = await this.fetch(url, {
287+ const response = await this.fetch(url, {
298288 method: "POST",
299289 headers: headers,
300290 body: JSON.stringify(payload),
301291 signal,
302292 });
303293
304- if (!response.ok || response.body === null) {
305- throw new Error(
306- "Something went wrong. No response received, check your connection",
307- );
308- } else {
309- for await (const value of streamSse(response)) {
310- const chunk = fromChatCompletionChunk(value);
311- if (chunk) {
312- yield chunk;
313- }
294+ for await (const value of streamSse(response)) {
295+ const chunk = fromChatCompletionChunk(value);
296+ if (chunk) {
297+ yield chunk;
314298 }
315299 }
316300 }
deleted core/llm/stream.test.ts +0 −72
@@ -1,72 +0,0 @@
1-import { Readable } from "stream";
2-import { streamSse } from "./stream";
3-
4-function createMockResponse(sseLines: string[]): Response {
5- // Create a Readable stream that emits the SSE lines
6- const stream = new Readable({
7- read() {
8- for (const line of sseLines) {
9- this.push(line + "\n\n");
10- }
11- this.push(null); // End of stream
12- }
13- }) as any;
14-
15- // Minimal Response mock
16- return {
17- status: 200,
18- body: stream,
19- text: async () => "",
20- } as unknown as Response;
21-}
22-
23-describe("streamSse", () => {
24- it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25- const sseLines = [
26- 'data: {"foo": "bar"}',
27- 'data: {"baz": 42}',
28- 'data:[DONE]'
29- ];
30- const response = createMockResponse(sseLines);
31-
32- const results = [];
33- for await (const data of streamSse(response)) {
34- results.push(data);
35- }
36-
37- expect(results).toEqual([
38- { foo: "bar" },
39- { baz: 42 }
40- ]);
41- });
42-
43- it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
44- const sseLines = [
45- 'data: {"foo": "bar"}',
46- 'data: {"baz": 42}',
47- 'data: [DONE]'
48- ];
49- const response = createMockResponse(sseLines);
50-
51- const results = [];
52- for await (const data of streamSse(response)) {
53- results.push(data);
54- }
55-
56- expect(results).toEqual([
57- { foo: "bar" },
58- { baz: 42 }
59- ]);
60- });
61-
62- it("throws on malformed JSON", async () => {
63- const sseLines = [
64- 'data: {"foo": "bar"',
65- 'data:[DONE]'
66- ];
67- const response = createMockResponse(sseLines);
68-
69- const iterator = streamSse(response)[Symbol.asyncIterator]();
70- await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
71- });
72-});
modified core/llm/stream.ts +1 −1
@@ -1,4 +1,4 @@
1-async function* toAsyncIterable(
1+export async function* toAsyncIterable(
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
modified core/llm/streamChat.ts +27 −35
@@ -8,7 +8,7 @@
88
99 export async function* llmStreamChat(
1010 configHandler: ConfigHandler,
11- abortedMessageIds: Set<string>,
11+ abortController: AbortController,
1212 msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
1313 ide: IDE,
1414 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
@@ -75,52 +75,44 @@
7575 selectedCode,
7676 config,
7777 fetch: (url, init) =>
78- fetchwithRequestOptions(url, init, config.requestOptions),
78+ fetchwithRequestOptions(
79+ url,
80+ {
81+ ...init,
82+ signal: abortController.signal,
83+ },
84+ config.requestOptions,
85+ ),
7986 completionOptions,
8087 });
81- const checkActiveInterval = setInterval(() => {
82- if (abortedMessageIds.has(msg.messageId)) {
83- abortedMessageIds.delete(msg.messageId);
84- clearInterval(checkActiveInterval);
85- }
86- }, 100);
87- try {
88- let next = await gen.next();
89- while (!next.done) {
90- if (abortedMessageIds.has(msg.messageId)) {
91- abortedMessageIds.delete(msg.messageId);
92- next = await gen.return(errorPromptLog);
93- clearInterval(checkActiveInterval);
94- break;
95- }
96- if (next.value) {
97- yield {
98- role: "assistant",
99- content: next.value,
100- };
101- }
102- next = await gen.next();
88+ let next = await gen.next();
89+ while (!next.done) {
90+ if (abortController.signal.aborted) {
91+ next = await gen.return(errorPromptLog);
92+ break;
10393 }
104- if (!next.done) {
105- throw new Error("Will never happen");
94+ if (next.value) {
95+ yield {
96+ role: "assistant",
97+ content: next.value,
98+ };
10699 }
107-
108- return next.value;
109- } catch (e) {
110- throw e;
111- } finally {
112- clearInterval(checkActiveInterval);
100+ next = await gen.next();
113101 }
102+ if (!next.done) {
103+ throw new Error("Will never happen");
104+ }
105+
106+ return next.value;
114107 } else {
115108 const gen = model.streamChat(
116109 messages,
117- new AbortController().signal,
110+ abortController.signal,
118111 completionOptions,
119112 );
120113 let next = await gen.next();
121114 while (!next.done) {
122- if (abortedMessageIds.has(msg.messageId)) {
123- abortedMessageIds.delete(msg.messageId);
115+ if (abortController.signal.aborted) {
124116 next = await gen.return(errorPromptLog);
125117 break;
126118 }
modified core/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified core/package.json +2 −2
@@ -49,9 +49,9 @@
4949 "@aws-sdk/credential-providers": "^3.778.0",
5050 "@continuedev/config-types": "^1.0.13",
5151 "@continuedev/config-yaml": "file:../packages/config-yaml",
52- "@continuedev/fetch": "^1.0.6",
52+ "@continuedev/fetch": "^1.0.10",
5353 "@continuedev/llm-info": "^1.0.8",
54- "@continuedev/openai-adapters": "^1.0.19",
54+ "@continuedev/openai-adapters": "^1.0.25",
5555 "@modelcontextprotocol/sdk": "^1.5.0",
5656 "@mozilla/readability": "^0.5.0",
5757 "@octokit/rest": "^20.1.1",
modified core/protocol/core.ts +1 −0
@@ -46,6 +46,7 @@
4646 // Special
4747 ping: [string, string];
4848 abort: [undefined, void];
49+ cancelApply: [undefined, void];
4950
5051 // History
5152 "history/list": [ListHistoryOptions, SessionMetadata[]];
added core/util/abortManager.ts +37 −0
@@ -0,0 +1,37 @@
1+export class StreamAbortManager {
2+ private static instance: StreamAbortManager;
3+ private controllers: Map<string, AbortController>;
4+
5+ private constructor() {
6+ this.controllers = new Map();
7+ }
8+
9+ public static getInstance(): StreamAbortManager {
10+ if (!StreamAbortManager.instance) {
11+ StreamAbortManager.instance = new StreamAbortManager();
12+ }
13+ return StreamAbortManager.instance;
14+ }
15+
16+ public get(id: string): AbortController {
17+ let controller = this.controllers.get(id);
18+ if (!controller) {
19+ controller = new AbortController();
20+ this.controllers.set(id, controller);
21+ }
22+ return controller;
23+ }
24+
25+ public abort(id: string): void {
26+ const controller = this.controllers.get(id);
27+ if (controller) {
28+ controller.abort();
29+ this.controllers.delete(id);
30+ }
31+ }
32+
33+ public clear(): void {
34+ this.controllers.forEach((controller) => controller.abort());
35+ this.controllers.clear();
36+ }
37+}
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +1 −1
@@ -108,7 +108,7 @@
108108 )
109109 continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
110110 continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
111-
111+ continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
112112 cleanUpFile(file)
113113 }
114114
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +2 −2
@@ -111,7 +111,8 @@
111111 suffix = suffix,
112112 language = virtualFile?.fileType?.name,
113113 modelTitle = modelTitle,
114- includeRulesInSystemMessage = includeRulesInSystemMessage
114+ includeRulesInSystemMessage = includeRulesInSystemMessage,
115+ fileUri = virtualFile?.url
115116 ),
116117 null
117118 ) { response ->
@@ -289,7 +290,6 @@
289290 }
290291 }
291292
292-
293293 private fun handleFinishedResponse() {
294294 ApplicationManager.getApplication().invokeLater {
295295 // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +2 −1
@@ -244,7 +244,8 @@
244244 val input: String,
245245 val language: String?,
246246 val modelTitle: String?,
247- val includeRulesInSystemMessage: Boolean
247+ val includeRulesInSystemMessage: Boolean,
248+ val fileUri: String?
248249 )
249250
250251 data class AcceptOrRejectDiffPayload(
modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/package.json +1 −1
@@ -661,7 +661,7 @@
661661 },
662662 "dependencies": {
663663 "@continuedev/config-types": "^1.0.14",
664- "@continuedev/fetch": "^1.0.3",
664+ "@continuedev/fetch": "^1.0.10",
665665 "@electron/rebuild": "^3.2.10",
666666 "@reduxjs/toolkit": "^1.9.3",
667667 "@types/node-fetch": "^2.6.11",
modified extensions/vscode/src/commands.ts +14 −4
@@ -97,6 +97,7 @@
9797 action: "accept" | "reject",
9898 sidebar: ContinueGUIWebviewViewProvider,
9999 ide: VsCodeIde,
100+ core: Core,
100101 verticalDiffManager: VerticalDiffManager,
101102 newFileUri?: string,
102103 streamId?: string,
@@ -121,6 +122,9 @@
121122
122123 // Clear vertical diffs depending on action
123124 verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
125+ if (action === "reject") {
126+ core.invoke("cancelApply", undefined);
127+ }
124128
125129 if (streamId) {
126130 const fileContent = await ide.readFile(newOrCurrentUri);
@@ -236,18 +240,20 @@
236240 "accept",
237241 sidebar,
238242 ide,
243+ core,
239244 verticalDiffManager,
240245 newFileUri,
241246 streamId,
242247 ),
243248
244- "continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
249+ "continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
245250 processDiff(
246251 "reject",
247252 sidebar,
248253 ide,
254+ core,
249255 verticalDiffManager,
250- newFilepath,
256+ newFileUri,
251257 streamId,
252258 ),
253259 "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
@@ -573,11 +579,15 @@
573579 await addEntireFileToContext(
574580 vscode.Uri.parse(fileUri),
575581 sidebar.webviewProtocol,
576- ide.ideUtils
582+ ide.ideUtils,
577583 );
578584 }
579585 } else {
580- await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
586+ await addEntireFileToContext(
587+ uri,
588+ sidebar.webviewProtocol,
589+ ide.ideUtils,
590+ );
581591 }
582592 }
583593 },
modified extensions/vscode/src/diff/vertical/manager.ts +3 −4
@@ -1,5 +1,4 @@
11 import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
2-import { ConfigHandler } from "core/config/ConfigHandler";
32 import { streamDiffLines } from "core/edit/streamDiffLines";
43 import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
54 import { getMarkdownLanguageTagForFile } from "core/util";
@@ -31,7 +30,6 @@
3130 logDiffs: DiffLine[] | undefined;
3231
3332 constructor(
34- private readonly configHandler: ConfigHandler,
3533 private readonly webviewProtocol: VsCodeWebviewProtocol,
3634 private readonly editDecorationManager: EditDecorationManager,
3735 ) {
@@ -43,12 +41,12 @@
4341 startLine: number,
4442 endLine: number,
4543 options: VerticalDiffHandlerOptions,
46- ) {
44+ ): VerticalDiffHandler | undefined {
4745 if (this.fileUriToHandler.has(fileUri)) {
4846 this.fileUriToHandler.get(fileUri)?.clear(false);
4947 this.fileUriToHandler.delete(fileUri);
5048 }
51- const editor = vscode.window.activeTextEditor; // TODO
49+ const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
5250 if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
5351 const handler = new VerticalDiffHandler(
5452 startLine,
@@ -453,6 +451,7 @@
453451 language: getMarkdownLanguageTagForFile(fileUri),
454452 onlyOneInsertion: !!onlyOneInsertion,
455453 overridePrompt,
454+ abortControllerId: fileUri,
456455 });
457456
458457 for await (const line of stream) {
modified extensions/vscode/src/extension/VsCodeExtension.ts +0 −1
@@ -130,7 +130,6 @@
130130 this.configHandler.loadConfig();
131131
132132 this.verticalDiffManager = new VerticalDiffManager(
133- this.configHandler,
134133 this.sidebar.webviewProtocol,
135134 this.editDecorationManager,
136135 );
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/mainInput/Lump/LumpToolbar.tsx +36 −1
@@ -1,4 +1,4 @@
1-import { useContext, useEffect } from "react";
1+import { useContext, useEffect, useMemo } from "react";
22 import { useSelector } from "react-redux";
33 import styled from "styled-components";
44 import { AnimatedEllipsis } from "../..";
@@ -40,12 +40,27 @@
4040 );
4141 }
4242
43+function ApplyingIndicator() {
44+ return (
45+ <div className="text-xs text-gray-400">
46+ <span>Applying</span>
47+ <AnimatedEllipsis />
48+ </div>
49+ );
50+}
51+
4352 export function LumpToolbar() {
4453 const dispatch = useAppDispatch();
4554 const ideMessenger = useContext(IdeMessengerContext);
4655 const ttsActive = useAppSelector((state) => state.ui.ttsActive);
4756 const isStreaming = useAppSelector((state) => state.session.isStreaming);
4857 const jetbrains = isJetBrains();
58+ const applyStates = useAppSelector(
59+ (store) => store.session.codeBlockApplyStates.states,
60+ );
61+ const isApplying = useMemo(() => {
62+ return applyStates.find((state) => state.status === "streaming");
63+ }, [applyStates]);
4964
5065 const toolCallState = useSelector(selectCurrentToolCall);
5166
@@ -89,6 +104,26 @@
89104 );
90105 }
91106
107+ if (isApplying) {
108+ return (
109+ <Container>
110+ <ApplyingIndicator />
111+ <StopButton
112+ className="text-gray-400"
113+ onClick={() => {
114+ // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
115+ // Apply is prioritized because it can be more catastrophic
116+ // Intentional to be more WYSIWYG for now
117+ ideMessenger.post("cancelApply", undefined);
118+ }}
119+ >
120+ {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
121+ {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
122+ </StopButton>
123+ </Container>
124+ );
125+ }
126+
92127 if (isStreaming) {
93128 return (
94129 <Container>
modified gui/src/pages/gui/Chat.tsx +1 −0
@@ -144,6 +144,7 @@
144144 !e.shiftKey
145145 ) {
146146 dispatch(cancelStream());
147+ ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
147148 }
148149 };
149150 window.addEventListener("keydown", listener);
modified manual-testing-sandbox/AdvancedPage.tsx +1 −4
@@ -13,10 +13,7 @@
1313 className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
1414 >
1515 <header className="mb-4 flex items-center justify-between border-b-2 pb-4">
16- I apologize, but there seems to be a misunderstanding. The user's
17- request doesn't appear to be related to rewriting the code section you
18- provided. The request mentions editing a readme.md file, which is not
19- part of the React component code you've shown.
16+ {" "}
2017 <button
2118 className="rounded bg-blue-500 px-4 py-2 text-white"
2219 onClick={toggleDarkMode}
added packages/fetch/.gitignore +1 −0
@@ -0,0 +1,1 @@
1+coverage/
No newline at the end of the file
added packages/fetch/jest.globals.d.ts +14 −0
@@ -0,0 +1,14 @@
1+// This file declares the Jest globals for TypeScript
2+import '@jest/globals';
3+
4+declare global {
5+ const describe: typeof import('@jest/globals').describe;
6+ const expect: typeof import('@jest/globals').expect;
7+ const it: typeof import('@jest/globals').it;
8+ const test: typeof import('@jest/globals').test;
9+ const beforeAll: typeof import('@jest/globals').beforeAll;
10+ const afterAll: typeof import('@jest/globals').afterAll;
11+ const beforeEach: typeof import('@jest/globals').beforeEach;
12+ const afterEach: typeof import('@jest/globals').afterEach;
13+ const jest: typeof import('@jest/globals').jest;
14+}
No newline at the end of the file
modified packages/fetch/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/fetch",
3- "version": "1.0.6",
3+ "version": "1.0.9",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/fetch",
9- "version": "1.0.6",
9+ "version": "1.0.9",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.5",
modified packages/fetch/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/fetch",
3- "version": "1.0.9",
3+ "version": "1.0.10",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/fetch/src/stream.test.ts +63 −3
@@ -1,6 +1,66 @@
1-// The parseDataLine function is not exported, so we need to import it
2-// indirectly by re-exporting it for testing purposes
3-import { parseDataLine } from "./stream.js";
1+import { Readable } from "stream";
2+import { parseDataLine, streamSse } from "./stream.js";
3+
4+function createMockResponse(sseLines: string[]): Response {
5+ // Create a Readable stream that emits the SSE lines
6+ const stream = new Readable({
7+ read() {
8+ for (const line of sseLines) {
9+ this.push(line + "\n\n");
10+ }
11+ this.push(null); // End of stream
12+ },
13+ }) as any;
14+
15+ // Minimal Response mock
16+ return {
17+ status: 200,
18+ body: stream,
19+ text: async () => "",
20+ } as unknown as Response;
21+}
22+
23+describe("streamSse", () => {
24+ it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25+ const sseLines = [
26+ 'data: {"foo": "bar"}',
27+ 'data: {"baz": 42}',
28+ "data:[DONE]",
29+ ];
30+ const response = createMockResponse(sseLines);
31+
32+ const results = [];
33+ for await (const data of streamSse(response)) {
34+ results.push(data);
35+ }
36+
37+ expect(results).toEqual([{ foo: "bar" }, { baz: 42 }]);
38+ });
39+
40+ it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
41+ const sseLines = [
42+ 'data: {"foo": "bar"}',
43+ 'data: {"baz": 42}',
44+ "data: [DONE]",
45+ ];
46+ const response = createMockResponse(sseLines);
47+
48+ const results = [];
49+ for await (const data of streamSse(response)) {
50+ results.push(data);
51+ }
52+
53+ expect(results).toEqual([{ foo: "bar" }, { baz: 42 }]);
54+ });
55+
56+ it("throws on malformed JSON", async () => {
57+ const sseLines = ['data: {"foo": "bar"', "data:[DONE]"];
58+ const response = createMockResponse(sseLines);
59+
60+ const iterator = streamSse(response)[Symbol.asyncIterator]();
61+ await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
62+ });
63+});
464
565 describe("parseDataLine", () => {
666 test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => {
modified packages/fetch/src/stream.ts +2 −1
@@ -2,7 +2,7 @@
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
5- // @ts-expect-error
5+ // @ts-ignore
66 yield chunk as Uint8Array;
77 }
88 }
@@ -13,6 +13,7 @@
1313 if (response.status === 499) {
1414 return; // In case of client-side cancellation, just return
1515 }
16+
1617 if (response.status !== 200) {
1718 throw new Error(await response.text());
1819 }
modified packages/fetch/tsconfig.json +1 −1
@@ -19,5 +19,5 @@
1919 "declaration": true
2020 // "sourceMap": true
2121 },
22- "include": ["src/**/*"]
22+ "include": ["src/**/*", "jest.globals.d.ts"]
2323 }
modified packages/openai-adapters/package-lock.json +6 −6
@@ -1,18 +1,18 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.22",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/openai-adapters",
9- "version": "1.0.21",
9+ "version": "1.0.22",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@azure/openai": "^1.0.0-beta.12",
1313 "@continuedev/config-types": "^1.0.5",
1414 "@continuedev/config-yaml": "^1.0.51",
15- "@continuedev/fetch": "^1.0.3",
15+ "@continuedev/fetch": "^1.0.10",
1616 "dotenv": "^16.5.0",
1717 "json-schema": "^0.4.0",
1818 "node-fetch": "^3.3.2",
@@ -716,9 +716,9 @@
716716 }
717717 },
718718 "node_modules/@continuedev/fetch": {
719- "version": "1.0.3",
720- "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz",
721- "integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==",
719+ "version": "1.0.10",
720+ "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
721+ "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
722722 "dependencies": {
723723 "@continuedev/config-types": "^1.0.5",
724724 "follow-redirects": "^1.15.6",
modified packages/openai-adapters/package.json +1 −1
@@ -15,7 +15,7 @@
1515 "@azure/openai": "^1.0.0-beta.12",
1616 "@continuedev/config-types": "^1.0.5",
1717 "@continuedev/config-yaml": "^1.0.51",
18- "@continuedev/fetch": "^1.0.3",
18+ "@continuedev/fetch": "^1.0.10",
1919 "dotenv": "^16.5.0",
2020 "json-schema": "^0.4.0",
2121 "node-fetch": "^3.3.2",
modified packages/openai-adapters/src/apis/Anthropic.ts +5 −0
@@ -12,6 +12,7 @@
1212 import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
1313 import { AnthropicConfig } from "../types.js";
1414 import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
15+import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1516 import {
1617 BaseLlmApi,
1718 CreateRerankResponse,
@@ -157,6 +158,10 @@
157158 },
158159 );
159160
161+ if (response.status === 499) {
162+ return EMPTY_CHAT_COMPLETION;
163+ }
164+
160165 const completion = (await response.json()) as any;
161166 return {
162167 id: completion.id,
modified packages/openai-adapters/src/apis/Cohere.ts +5 −0
@@ -15,6 +15,7 @@
1515 } from "openai/resources/index";
1616 import { CohereConfig } from "../types.js";
1717 import { chatCompletion, customFetch, embedding } from "../util.js";
18+import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1819 import {
1920 BaseLlmApi,
2021 CreateRerankResponse,
@@ -77,6 +78,10 @@
7778 },
7879 );
7980
81+ if (resp.status === 499) {
82+ return EMPTY_CHAT_COMPLETION;
83+ }
84+
8085 const data = (await resp.json()) as any;
8186 const { input_tokens, output_tokens } = data.meta.tokens;
8287 return chatCompletion({
modified packages/openai-adapters/src/apis/Relace.ts +4 −0
@@ -105,6 +105,10 @@
105105 signal,
106106 });
107107
108+ if (response.status === 499) {
109+ return; // Aborted by user
110+ }
111+
108112 const result = (await response.json()) as any;
109113 const mergedCode = result.mergedCode;
110114
added packages/openai-adapters/src/util/emptyChatCompletion.ts +21 −0
@@ -0,0 +1,21 @@
1+import { ChatCompletion } from "openai/resources/index";
2+
3+export const EMPTY_CHAT_COMPLETION: ChatCompletion = {
4+ choices: [
5+ {
6+ finish_reason: "stop",
7+ index: 0,
8+ logprobs: null,
9+ message: {
10+ content: null,
11+ role: "assistant",
12+ refusal: null,
13+ },
14+ },
15+ ],
16+ usage: undefined,
17+ created: Date.now(),
18+ id: "",
19+ model: "UNSPECIFIED",
20+ object: "chat.completion",
21+};