catch client abort errors

This commit is contained in:
Dallin Romney 2025-05-15 18:45:55 -07:00
parent d93d665512
commit 1a47f96259
16 changed files with 176 additions and 111 deletions

View file

@ -382,6 +382,9 @@ export abstract class BaseLLM implements ILLM {
// Error mapping to be more helpful
if (!resp.ok) {
if (resp.status === 499) {
return resp; // client side cancellation
}
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
const error = JSON.parse(text)?.error?.replace(/"/g, "'");

View file

@ -213,6 +213,11 @@ class Anthropic extends BaseLLM {
signal,
});
if (response.status === 499) {
// Aborted by user
return;
}
if (!response.ok) {
const json = await response.json();
if (json.type === "error") {

View file

@ -134,10 +134,8 @@ class Asksage extends BaseLLM {
body: JSON.stringify(args),
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
if (response.status === 499) {
return ""; // Aborted by user
}
const data = await response.json();
@ -167,10 +165,8 @@ class Asksage extends BaseLLM {
signal,
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();

View file

@ -84,6 +84,10 @@ class Cohere extends BaseLLM {
signal,
});
if (resp.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await resp.json();
yield { role: "assistant", content: data.text };

View file

@ -132,12 +132,16 @@ class Flowise extends BaseLLM {
): AsyncGenerator<ChatMessage> {
const requestBody = this._getRequestBody(messages, options);
const { socket, socketInfo } = await this._initializeSocket();
const request = this.fetch(this._getChatUrl(), {
const response = await this.fetch(this._getChatUrl(), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal,
}).then((res) => res.json());
});
if (response.status === 499) {
return; // Aborted by user
}
while (await socketInfo.hasNextToken()) {
yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@ -145,7 +149,7 @@ class Flowise extends BaseLLM {
if (socketInfo.error) {
socket.disconnect();
try {
yield { role: "assistant", content: (await request).text };
yield { role: "assistant", content: await response.text() };
} catch (error: any) {
yield { role: "assistant", content: (error as Error).message ?? error };
}

View file

@ -438,6 +438,10 @@ class Gemini extends BaseLLM {
body: JSON.stringify(body),
signal,
});
if (response.status === 499) {
// Aborted by user
return;
}
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };
}

View file

@ -457,6 +457,10 @@ class Ollama extends BaseLLM implements ModelInstaller {
}
if (chatOptions.stream === false) {
if (response.status === 499) {
// Aborted by user
return;
}
const json = (await response.json()) as OllamaChatResponse;
yield convertChatMessage(json);
} else {

View file

@ -352,6 +352,10 @@ class OpenAI extends BaseLLM {
// Handle non-streaming response
if (body.stream === false) {
if (response.status === 499) {
// Aborted by user
return;
}
const data = await response.json();
yield data.choices[0].message;
return;

View file

@ -95,6 +95,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatAnthropic(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
@ -128,8 +129,13 @@ class VertexAI extends BaseLLM {
]
: systemMessage,
}),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
@ -150,6 +156,7 @@ class VertexAI extends BaseLLM {
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
`publishers/google/models/${options.model}:streamGenerateContent`,
@ -160,6 +167,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const message of this.geminiInstance.processGeminiResponse(
streamResponse(response),
@ -171,6 +179,7 @@ class VertexAI extends BaseLLM {
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const instances = messages.map((message) => ({ prompt: message.content }));
@ -193,7 +202,11 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield { role: "assistant", content: data.predictions[0].content };
}
@ -203,6 +216,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatMistral(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const apiBase = this.apiBase!;
const apiURL = new URL(
@ -228,6 +242,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const chunk of streamSse(response)) {
@ -304,6 +319,9 @@ class VertexAI extends BaseLLM {
}),
signal,
});
if (resp.status === 499) {
return; // Aborted by user
}
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
yield (await resp.json()).predictions[0].content;
@ -323,14 +341,14 @@ class VertexAI extends BaseLLM {
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider === "gemini") {
yield* this.streamChatGemini(convertedMsgs, options);
yield* this.streamChatGemini(convertedMsgs, options, signal);
} else if (this.vertexProvider === "mistral") {
yield* this.StreamChatMistral(messages, options);
yield* this.StreamChatMistral(messages, options, signal);
} else if (this.vertexProvider === "anthropic") {
yield* this.StreamChatAnthropic(messages, options);
yield* this.StreamChatAnthropic(messages, options, signal);
} else {
if (options.model.includes("bison")) {
yield* this.streamChatBison(convertedMsgs, options);
yield* this.streamChatBison(convertedMsgs, options, signal);
} else {
throw new Error(`Unsupported model: ${options.model}`);
}

View file

@ -4,11 +4,8 @@ import {
CompletionOptions,
LLMOptions,
} from "../../index.js";
import {
fromChatCompletionChunk,
} from "../openaiTypeConverters.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
import { streamResponse, streamSse } from "../stream.js";
let watsonxToken = {
@ -86,7 +83,7 @@ class WatsonX extends BaseLLM {
}
_getEndpoint(endpoint: string): string {
return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
}
static providerName = "watsonx";
@ -182,7 +179,6 @@ class WatsonX extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
await this.updateWatsonxToken();
const stopSequences = options.stop?.slice(0, 6) ?? [];
@ -214,44 +210,38 @@ class WatsonX extends BaseLLM {
payload.project_id = this.projectId;
}
var response = await this.fetch(url, {
const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
if (isNaN(generatedTextIndex)) {
console.error(`Unable to parse stream chunk ID: ${el}`);
}
} else if (el.startsWith("data:")) {
const dataStr = el.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
if (isNaN(generatedTextIndex)) {
console.error(`Unable to parse stream chunk ID: ${el}`);
}
});
yield generatedChunk
}
} else if (el.startsWith("data:")) {
const dataStr = el.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
}
});
yield generatedChunk;
}
}
@ -267,7 +257,7 @@ class WatsonX extends BaseLLM {
const headers = this._getHeaders();
const payload: any = {
messages: messages,
messages: messages,
max_tokens: options.maxTokens ?? 1024,
stop: stopSequences,
frequency_penalty: options.frequencyPenalty || 1,
@ -281,36 +271,30 @@ class WatsonX extends BaseLLM {
if (!!options.temperature) {
payload.temperature = options.temperature;
}
}
if (!!options.topP) {
payload.top_p = options.topP;
}
if (!!options.tools) {
payload.tools = options.tools;
if (options.toolChoice) {
payload.tool_choice = options.toolChoice;
payload.tool_choice = options.toolChoice;
} else {
payload.tool_choice_option = "auto";
payload.tool_choice_option = "auto";
}
}
var response = await this.fetch(url, {
const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
}
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
}
}
}

View file

@ -10,6 +10,10 @@ async function* toAsyncIterable(
export async function* streamResponse(
response: Response,
): AsyncGenerator<string> {
if (response.status === 499) {
return; // In case of client-side cancellation, just return
}
if (response.status !== 200) {
throw new Error(await response.text());
}
@ -21,22 +25,29 @@ export async function* streamResponse(
// Get the major version of Node.js
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
try {
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
}
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
} catch (e) {
if (e instanceof Error && e.name.startsWith("AbortError")) {
return; // In case of client-side cancellation, just return
}
throw e;
}
}

View file

@ -97,6 +97,7 @@ async function processDiff(
action: "accept" | "reject",
sidebar: ContinueGUIWebviewViewProvider,
ide: VsCodeIde,
core: Core,
verticalDiffManager: VerticalDiffManager,
newFileUri?: string,
streamId?: string,
@ -121,6 +122,9 @@ async function processDiff(
// 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);
@ -236,6 +240,7 @@ const getCommandsMap: (
"accept",
sidebar,
ide,
core,
verticalDiffManager,
newFileUri,
streamId,
@ -246,6 +251,7 @@ const getCommandsMap: (
"reject",
sidebar,
ide,
core,
verticalDiffManager,
newFileUri,
streamId,

View file

@ -13,10 +13,7 @@ const AdvancedPage = () => {
className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
>
<header className="mb-4 flex items-center justify-between border-b-2 pb-4">
I apologize, but there seems to be a misunderstanding. The user's
request doesn't appear to be related to rewriting the code section you
provided. The request mentions editing a readme.md file, which is not
part of the React component code you've shown.
{" "}
<button
className="rounded bg-blue-500 px-4 py-2 text-white"
onClick={toggleDarkMode}

View file

@ -107,19 +107,30 @@ export async function fetchwithRequestOptions(
}
// fetch the request with the provided options
const resp = await fetch(url, {
...init,
body: updatedBody ?? init?.body,
headers: headers,
agent: agent,
});
try {
const resp = await fetch(url, {
...init,
body: updatedBody ?? init?.body,
headers: headers,
agent: agent,
});
if (!resp.ok) {
const requestId = resp.headers.get("x-request-id");
if (requestId) {
console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
if (!resp.ok) {
const requestId = resp.headers.get("x-request-id");
if (requestId) {
console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
}
}
}
return resp;
return resp;
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
// Return a Response object that streamResponse etc can handle
return new Response(null, {
status: 499, // Client Closed Request
statusText: "Client Closed Request",
});
}
throw error;
}
}

View file

@ -10,6 +10,9 @@ export async function* toAsyncIterable(
export async function* streamResponse(
response: Response,
): AsyncGenerator<string> {
if (response.status === 499) {
return; // In case of client-side cancellation, just return
}
if (response.status !== 200) {
throw new Error(await response.text());
}
@ -21,22 +24,29 @@ export async function* streamResponse(
// Get the major version of Node.js
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
try {
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
}
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
} catch (e) {
if (e instanceof Error && e.name.startsWith("AbortError")) {
return; // In case of client-side cancellation, just return
}
throw e;
}
}

View file

@ -105,6 +105,10 @@ export class RelaceApi implements BaseLlmApi {
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const result = (await response.json()) as any;
const mergedCode = result.mergedCode;