Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into cmmoran1130/main
Changesete3489ccbde59a380466222f7836bc2e994a97d411dacdf549f3bc3876635c5eb
AuthorNate <sestinj@gmail.com> · 2025-05-25 17:44 -07:00
CommitterNate <sestinj@gmail.com> · 2025-05-25 17:44 -07:00
Parents1f089284a191, 54ea0739010d

Browse the files at this changeset

86 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/config/markdown/parseMarkdownRule.test.ts +20 −0
@@ -151,4 +151,24 @@
151151 );
152152 expect(result.name).toBe("custom-rule");
153153 });
154+
155+ it("should include description from frontmatter", () => {
156+ const content = `---
157+globs: "**/test/**/*.kt"
158+name: Test Rule
159+description: This is a rule description from frontmatter
160+---
161+
162+# Test Rule
163+
164+This is the content of the rule.`;
165+
166+ const result = convertMarkdownRuleToContinueRule(
167+ "/path/to/rule.md",
168+ content,
169+ );
170+ expect(result.description).toBe(
171+ "This is a rule description from frontmatter",
172+ );
173+ });
154174 });
modified core/config/markdown/parseMarkdownRule.ts +2 −1
@@ -59,9 +59,10 @@
5959 }
6060
6161 return {
62+ name,
6263 rule: markdown,
6364 globs: frontmatter.globs,
64- name,
65+ description: frontmatter.description,
6566 source: "rules-block",
6667 ruleFile: path,
6768 };
modified core/config/util.ts +1 −0
@@ -77,6 +77,7 @@
7777 model: model.model,
7878 apiKey: model.apiKey,
7979 apiBase: model.apiBase,
80+ maxStopWords: model.maxStopWords,
8081 defaultCompletionOptions: model.completionOptions,
8182 };
8283 if (model.systemMessage) {
modified core/config/yaml/loadYaml.ts +2 −2
@@ -71,7 +71,7 @@
7171 command: server.command,
7272 args: server.args ?? [],
7373 env: server.env,
74- },
74+ } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
7575 timeout: server.connectionTimeout,
7676 };
7777 }
@@ -458,7 +458,7 @@
458458 transport: {
459459 type: "stdio",
460460 args: [],
461- ...server,
461+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
462462 },
463463 timeout: server.connectionTimeout,
464464 })),
modified core/control-plane/schema.ts +1 −0
@@ -26,6 +26,7 @@
2626 apiKey: z.string().optional(),
2727 apiBase: z.string().optional(),
2828 contextLength: z.number().optional(),
29+ maxStopWords: z.number().optional(),
2930 template: z
3031 .enum([
3132 "llama2",
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/Bedrock.ts +1 −1
@@ -306,7 +306,7 @@
306306 }
307307
308308 const supportsTools =
309- PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
309+ (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
310310
311311 let toolConfig = supportsTools && options.tools
312312 ? {
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 }
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
@@ -27,8 +27,12 @@
2727 // to call whatever LLM API is chosen
2828 private actualApiBase?: string;
2929
30+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
31+ private configEnv?: Record<string, any>;
32+
3033 constructor(options: LLMOptions) {
3134 super(options);
35+ this.configEnv = options.env;
3236 this.actualApiBase = options.apiBase;
3337 this.apiKeyLocation = options.apiKeyLocation;
3438 this.orgScopeId = options.orgScopeId;
@@ -48,6 +52,7 @@
4852 apiKeyLocation: this.apiKeyLocation,
4953 apiBase: this.actualApiBase,
5054 orgScopeId: this.orgScopeId ?? null,
55+ env: this.configEnv,
5156 };
5257 return {
5358 continueProperties,
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/llm/toolSupport.ts +3 −2
@@ -17,6 +17,7 @@
1717 "claude-3.5",
1818 "claude-3-7",
1919 "claude-3.7",
20+ "claude-sonnet-4",
2021 "gpt-4",
2122 "o3",
2223 "gemini",
@@ -24,7 +25,7 @@
2425 },
2526 anthropic: (model) => {
2627 if (
27- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
28+ ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
2829 model.toLowerCase().startsWith(part),
2930 )
3031 ) {
@@ -76,7 +77,7 @@
7677 // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
7778 if (
7879 model.toLowerCase().includes("sonnet") &&
79- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
80+ ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
8081 model.toLowerCase().includes(part),
8182 )
8283 ) {
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[]];
modified core/tools/definitions/createRuleBlock.ts +4 −0
@@ -28,6 +28,10 @@
2828 description:
2929 "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
3030 },
31+ description: {
32+ type: "string",
33+ description: "Short description of the rule",
34+ },
3135 globs: {
3236 type: "string",
3337 description:
modified core/tools/implementations/createRuleBlock.test.ts +54 −36
@@ -1,4 +1,4 @@
1-import * as YAML from "yaml";
1+import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
22 import { createRuleBlockImpl } from "./createRuleBlock";
33
44 // Mock the extras parameter with necessary functions
@@ -17,33 +17,6 @@
1717 jest.clearAllMocks();
1818 });
1919
20- it("should create a basic rule with name and rule content", async () => {
21- const args = {
22- name: "Test Rule",
23- rule: "Always write tests",
24- };
25-
26- const result = await createRuleBlockImpl(args, mockExtras as any);
27-
28- // Verify that writeFile was called with the correct YAML
29- expect(mockIde.writeFile).toHaveBeenCalled();
30- const yamlContent = mockIde.writeFile.mock.calls[0][1];
31- const parsedYaml = YAML.parse(yamlContent);
32-
33- // Verify the structure of the YAML
34- expect(parsedYaml).toEqual({
35- name: "Test Rule",
36- version: "0.0.1",
37- schema: "v1",
38- rules: [
39- {
40- name: "Test Rule",
41- rule: "Always write tests",
42- },
43- ],
44- });
45- });
46-
4720 it("should create a rule with glob pattern", async () => {
4821 const args = {
4922 name: "TypeScript Rule",
@@ -53,14 +26,16 @@
5326
5427 await createRuleBlockImpl(args, mockExtras as any);
5528
56- // Verify the YAML structure with globs
57- const yamlContent = mockIde.writeFile.mock.calls[0][1];
58- const parsedYaml = YAML.parse(yamlContent);
59- expect(parsedYaml.rules[0]).toEqual({
60- name: "TypeScript Rule",
61- rule: "Use interfaces for object shapes",
29+ const fileContent = mockIde.writeFile.mock.calls[0][1];
30+
31+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
32+
33+ expect(frontmatter).toEqual({
6234 globs: "**/*.{ts,tsx}",
6335 });
36+
37+ expect(markdown).toContain("# TypeScript Rule");
38+ expect(markdown).toContain("Use interfaces for object shapes");
6439 });
6540
6641 it("should create a filename based on sanitized rule name", async () => {
@@ -71,8 +46,51 @@
7146
7247 await createRuleBlockImpl(args, mockExtras as any);
7348
74- // Check that the filename is sanitized
7549 const fileUri = mockIde.writeFile.mock.calls[0][0];
76- expect(fileUri).toContain("special-chracters-spaces.yaml");
50+ expect(fileUri).toContain("special-chracters-spaces.md");
51+ });
52+
53+ it("should create a rule with description pattern", async () => {
54+ const args = {
55+ name: "Description Test",
56+ rule: "This is the rule content",
57+ description: "This is a detailed explanation of the rule",
58+ };
59+
60+ await createRuleBlockImpl(args, mockExtras as any);
61+
62+ const fileContent = mockIde.writeFile.mock.calls[0][1];
63+
64+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
65+
66+ expect(frontmatter).toEqual({
67+ description: "This is a detailed explanation of the rule",
68+ });
69+
70+ expect(markdown).toContain("# Description Test");
71+ expect(markdown).toContain("This is the rule content");
72+ });
73+
74+ it("should include both globs and description in frontmatter", async () => {
75+ const args = {
76+ name: "Complete Rule",
77+ rule: "Follow this standard",
78+ description: "This rule enforces our team standards",
79+ globs: "**/*.js",
80+ };
81+
82+ await createRuleBlockImpl(args, mockExtras as any);
83+
84+ const fileContent = mockIde.writeFile.mock.calls[0][1];
85+
86+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
87+
88+ expect(frontmatter).toEqual({
89+ description: "This rule enforces our team standards",
90+ globs: "**/*.js",
91+ });
92+
93+ expect(markdown).toContain("# Complete Rule");
94+ expect(markdown).toContain("Follow this standard");
7795 });
7896 });
modified core/tools/implementations/createRuleBlock.ts +16 −36
@@ -1,4 +1,3 @@
1-import { ConfigYaml } from "@continuedev/config-yaml";
21 import * as YAML from "yaml";
32 import { ToolImpl } from ".";
43 import { joinPathsToUri } from "../../util/uri";
@@ -6,8 +5,8 @@
65 export interface CreateRuleBlockArgs {
76 name: string;
87 rule: string;
8+ description: string;
99 globs?: string;
10- format?: "yaml" | "markdown"; // Add format option with yaml as default
1110 }
1211
1312 export const createRuleBlockImpl: ToolImpl = async (
@@ -20,26 +19,19 @@
2019 .replace(/[^a-z0-9\s-]/g, "")
2120 .replace(/\s+/g, "-");
2221
23- // Default to YAML format
24- const format = args.format ?? "yaml";
25- const fileExtension = format === "markdown" ? "md" : "yaml";
26-
27- const ruleObject = {
28- name: args.name,
29- rule: args.rule,
30- ...(args.globs ? { globs: args.globs.trim() } : {}),
31- };
32-
33- let fileContent: string;
34-
35- if (format === "markdown") {
36- // Generate markdown format with frontmatter
37- const frontmatter = {
38- ...(args.globs ? { globs: args.globs.trim() } : {}),
39- };
40-
41- const frontmatterYaml = YAML.stringify(frontmatter).trim();
42- fileContent = `---
22+ const fileExtension = "md";
23+
24+ const frontmatter: Record<string, string> = {};
25+
26+ if (args.globs) {
27+ frontmatter.globs = args.globs.trim();
28+ }
29+
30+ if (args.description) {
31+ frontmatter.description = args.description.trim();
32+ }
33+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
34+ let fileContent = `---
4335 ${frontmatterYaml}
4436 ---
4537
@@ -47,18 +39,6 @@
4739
4840 ${args.rule}
4941 `;
50- } else {
51- // Generate YAML format
52- const ruleBlock: ConfigYaml = {
53- name: args.name,
54- version: "0.0.1",
55- schema: "v1",
56- rules: [ruleObject],
57- };
58-
59- fileContent = YAML.stringify(ruleBlock);
60- }
61-
6242 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
6343 const rulesDirUri = joinPathsToUri(
6444 localContinueDir,
@@ -73,12 +53,12 @@
7353 return [
7454 {
7555 name: "New Rule Block",
76- description: "", // No description throws an error in the GUI
56+ description: args.description || "",
7757 uri: {
7858 type: "file",
7959 value: rulesDirUri,
8060 },
81- content: `Rule created successfully in ${format} format`,
61+ content: `Rule created successfully`,
8262 },
8363 ];
8464 };
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 docs/docs/reference.md +2 −1
@@ -188,6 +188,7 @@
188188 not currently used.
189189 - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
190190 provider and model. Supported capabilities include `tool_use` and `image_input`.
191+- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
191192 - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
192193 `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
193194 `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@@ -406,7 +407,7 @@
406407 - `destination` (**required**): The destination/endpoint that will receive the data. Can be:
407408 - an HTTP endpoint that will receive a POST request with a JSON blob
408409 - a file URL to a directory in which events will be dumpted to `.jsonl` files
409-- `schema` (**required**): the schema version of the JSON blobs to be sent
410+- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
410411 - `events`: an array of event names to include. Defaults to all events if not specified.
411412 - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
412413 contents, prompts, and completions. Defaults to `all`
modified docs/docusaurus.config.js +3 −1
@@ -66,7 +66,9 @@
6666 ],
6767
6868 scripts: [
69- '!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();',
69+ {
70+ src: "/scripts/custom-reo.js", // it references from static folder
71+ },
7072 ],
7173
7274 themeConfig:
added docs/static/scripts/custom-reo.js +1 −0
@@ -0,0 +1,1 @@
1+!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();
No newline at the end of the file
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 +3 −3
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.38",
5+ "version": "1.1.39",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -631,7 +631,7 @@
631631 "devDependencies": {
632632 "@biomejs/biome": "1.6.4",
633633 "@nestjs/common": "^11.0.16",
634- "@openapitools/openapi-generator-cli": "^2.5.2",
634+ "@openapitools/openapi-generator-cli": "^2.20.0",
635635 "@types/chai": "^5.0.1",
636636 "@types/cors": "^2.8.17",
637637 "@types/express": "^4.17.21",
@@ -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/TabBar/TabBar.tsx +12 −8
@@ -1,5 +1,5 @@
11 import { XMarkIcon } from "@heroicons/react/24/outline";
2-import { useCallback, useEffect } from "react";
2+import React, { useCallback, useEffect } from "react";
33 import { useDispatch, useSelector } from "react-redux";
44 import styled from "styled-components";
55 import { defaultBorderRadius } from "..";
@@ -35,6 +35,8 @@
3535 border-bottom: none;
3636 position: relative;
3737 margin-top: 2px;
38+ max-height: 100px;
39+ overflow: auto;
3840
3941 /* Hide scrollbar but keep functionality */
4042 scrollbar-width: none;
@@ -125,7 +127,7 @@
125127 background-color: ${tabBackgroundVar};
126128 `;
127129
128-export function TabBar() {
130+export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
129131 const dispatch = useDispatch<AppDispatch>();
130132 const currentSessionId = useSelector((state: RootState) => state.session.id);
131133 const currentSessionTitle = useSelector(
@@ -141,7 +143,6 @@
141143 return Date.now().toString(36) + Math.random().toString(36).substring(2);
142144 }, []);
143145
144- // Handle session changes
145146 useEffect(() => {
146147 if (!currentSessionId) return;
147148
@@ -224,10 +225,13 @@
224225 }
225226 };
226227
227- return tabs.length === 1 ? (
228- <></>
229- ) : (
230- <TabBarContainer>
228+ return (
229+ <TabBarContainer
230+ ref={ref}
231+ style={{
232+ display: tabs.length === 1 ? "none" : "flex",
233+ }}
234+ >
231235 {tabs.map((tab) => (
232236 <Tab
233237 key={tab.id}
@@ -253,4 +257,4 @@
253257 </TabBarSpace>
254258 </TabBarContainer>
255259 );
256-}
260+});
modified gui/src/components/find/FindWidget.tsx +126 −292
@@ -12,36 +12,25 @@
1212 useState,
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
15-import { useAppSelector } from "../../redux/hooks";
1615 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
17-
18-interface SearchMatch {
19- index: number;
20- textNode: Text;
21- overlayRectangle: Rectangle;
22-}
23-
24-type ScrollToMatchOption = "closest" | "first" | "none";
25-
26-const SEARCH_DEBOUNCE = 300;
27-const RESIZE_DEBOUNCE = 200;
28-
29-interface Rectangle {
30- top: number;
31- left: number;
32- width: number;
33- height: number;
34-}
35-
36-interface HighlightOverlayProps extends Rectangle {
16+import {
17+ Rectangle,
18+ SearchMatch,
19+ searchWithinContainer,
20+} from "./findWidgetSearch";
21+import useDebounceValue from "./useDebounce";
22+import { useElementSize } from "./useElementSize";
23+
24+interface HighlightOverlayProps {
25+ rectangle: Rectangle;
3726 isCurrent: boolean;
3827 }
3928
4029 const HighlightOverlay = (props: HighlightOverlayProps) => {
41- const { isCurrent, top, left, width, height } = props;
30+ const { top, left, width, height } = props.rectangle;
4231 return (
4332 <div
44- className={isCurrent ? "bg-findMatch-selected/50" : "bg-findMatch/50"}
33+ className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
4534 key={`highlight-${top}-${left}`}
4635 style={{
4736 position: "absolute",
@@ -56,6 +45,8 @@
5645 );
5746 };
5847
48+type ScrollToMatchOption = "closest" | "first" | "none";
49+
5950 /*
6051 useFindWidget takes a container ref and returns
6152 1. A widget that can be placed anywhere to search the contents of that container
@@ -64,18 +55,22 @@
6455
6556 Container must have relative positioning
6657 */
67-export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
58+export const useFindWidget = (
59+ searchRef: RefObject<HTMLDivElement>,
60+ headerRef: RefObject<HTMLDivElement>,
61+ disabled: boolean,
62+) => {
6863 // Search input, debounced
69- const [input, setInput] = useState<string>("");
70- const debouncedInput = useRef<string>("");
7164 const inputRef = useRef<HTMLInputElement>(null);
65+ const [currentValue, setCurrentValue] = useState<string>("");
66+ const searchTerm = useDebounceValue(currentValue, 300);
7267
7368 // Widget open/closed state
7469 const [open, setOpen] = useState<boolean>(false);
7570 const openWidget = useCallback(() => {
7671 setOpen(true);
7772 inputRef?.current?.select();
78- }, [setOpen, inputRef]);
73+ }, [inputRef]);
7974
8075 // Search settings and results
8176 const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
@@ -97,7 +92,7 @@
9792 behavior: "smooth",
9893 });
9994 },
100- [searchRef.current],
95+ [searchRef],
10196 );
10297
10398 const nextMatch = useCallback(() => {
@@ -143,327 +138,166 @@
143138 }, [inputRef, matches, nextMatch]);
144139
145140 // Handle container resize changes - highlight positions must adjust
146- const [isResizing, setIsResizing] = useState(false);
147- useEffect(() => {
148- let timeoutId: NodeJS.Timeout | null = null;
149- if (!searchRef?.current) return;
150-
151- const resizeObserver = new ResizeObserver((entries) => {
152- if (timeoutId) {
153- clearTimeout(timeoutId);
154- }
155- setIsResizing(true);
156- timeoutId = setTimeout(() => {
157- setIsResizing(false);
158- }, RESIZE_DEBOUNCE);
159- });
160-
161- resizeObserver.observe(searchRef.current);
162- return () => {
163- if (timeoutId) {
164- clearTimeout(timeoutId);
165- }
166- if (searchRef.current) resizeObserver.unobserve(searchRef.current);
167- };
168- }, [searchRef.current]);
141+ const { clientHeight: headerHeight, isResizing: headerResizing } =
142+ useElementSize(headerRef);
143+ const { isResizing: containerResizing } = useElementSize(searchRef);
144+ const isResizing = useMemo(() => {
145+ return containerResizing || headerResizing;
146+ }, [containerResizing, headerResizing]);
169147
170148 // Main function for finding matches and generating highlight overlays
171149 const refreshSearch = useCallback(
172- (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
173- if (clearFirst) setMatches([]);
174-
175- const searchContainer = searchRef.current;
176-
177- const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
178- if (!searchContainer || !_query) {
179- setMatches([]);
180- return;
181- }
182- const query = caseSensitive ? _query : _query.toLowerCase();
183-
184- // First grab all text nodes
185- // Skips any elements with the "find-widget-skip" class
186- const textNodes: Text[] = [];
187- const walker = document.createTreeWalker(
188- searchRef.current,
189- NodeFilter.SHOW_ALL,
150+ (scrollTo: ScrollToMatchOption = "none") => {
151+ const { results, closestToMiddle } = searchWithinContainer(
152+ searchRef,
153+ searchTerm,
190154 {
191- acceptNode: (node) => {
192- if (node.nodeType === Node.ELEMENT_NODE) {
193- if ((node as Element).classList.contains("find-widget-skip"))
194- return NodeFilter.FILTER_REJECT;
195- return NodeFilter.FILTER_ACCEPT;
196- } else if (node.nodeType === Node.TEXT_NODE) {
197- if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
198- const nodeValue = caseSensitive
199- ? node.nodeValue
200- : node.nodeValue.toLowerCase();
201- if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
202- }
203- return NodeFilter.FILTER_REJECT;
204- },
155+ caseSensitive,
156+ useRegex,
157+ offsetHeight: headerHeight,
205158 },
206159 );
207-
208- while (walker.nextNode()) {
209- if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
210- textNodes.push(walker.currentNode as Text);
211- }
212-
213- // Now walk through each node match and extract search results
214- // One node can have several matches
215- const newMatches: SearchMatch[] = [];
216- textNodes.forEach((textNode, idx) => {
217- // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
218- const highlightFullLine =
219- textNode.parentElement?.className.includes("hljs");
220-
221- let nodeTextValue = caseSensitive
222- ? textNode.nodeValue
223- : textNode.nodeValue.toLowerCase();
224- let startIndex = 0;
225- while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
226- // Create a range to measure the size and position of the match
227- const range = document.createRange();
228- range.setStart(textNode, startIndex);
229- const endIndex = startIndex + query.length;
230- range.setEnd(textNode, endIndex);
231- const rect = range.getBoundingClientRect();
232- range.detach();
233- startIndex = endIndex;
234-
235- const top =
236- rect.top + searchContainer.clientTop + searchContainer.scrollTop;
237- const left =
238- rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
239-
240- // Build a match result and push to matches
241- const newMatch: SearchMatch = {
242- index: 0, // will set later
243- textNode,
244- overlayRectangle: {
245- top,
246- left: highlightFullLine ? 2 : left,
247- width: highlightFullLine
248- ? searchContainer.clientWidth - 4
249- : rect.width, // equivalent of adding 2 px x padding
250- height: rect.height,
251- },
252- };
253- newMatches.push(newMatch);
254-
255- if (highlightFullLine) {
256- break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
257- }
258- }
259- });
260-
261- // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
262- // Filter them out by using the overlay rectangle as a hash key
263- const matchHash = Object.fromEntries(
264- newMatches.map((match) => [
265- JSON.stringify(match.overlayRectangle),
266- match,
267- ]),
268- );
269- const filteredMatches = Object.values(matchHash).map((match, index) => ({
270- ...match,
271- index,
272- }));
273-
160+ setMatches(results);
274161 // Find match closest to the middle of the view
275- const verticalMiddle =
276- searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
277- let closestDist = Infinity;
278- let closestMatchToMiddle: SearchMatch | null = null;
279- filteredMatches.forEach((match) => {
280- const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
281- if (dist < closestDist) {
282- closestDist = dist;
283- closestMatchToMiddle = match;
284- }
285- });
286-
287- // Update matches and scroll to the closest or first match
288- setMatches(filteredMatches);
289- if (query.length > 1 && filteredMatches.length) {
162+ if (searchTerm.length > 1 && results.length) {
290163 if (scrollTo === "first") {
291- scrollToMatch(filteredMatches[0]);
164+ scrollToMatch(results[0]);
292165 }
293166 if (scrollTo === "closest") {
294- if (closestMatchToMiddle) {
295- scrollToMatch(closestMatchToMiddle);
167+ if (closestToMiddle) {
168+ scrollToMatch(closestToMiddle);
296169 }
297170 }
298171 if (scrollTo === "none") {
299- if (closestMatchToMiddle) {
300- setCurrentMatch(closestMatchToMiddle);
172+ if (closestToMiddle) {
173+ setCurrentMatch(closestToMiddle);
301174 } else {
302- setCurrentMatch(filteredMatches[0]);
175+ setCurrentMatch(results[0]);
303176 }
304177 }
305178 }
306179 },
307- [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex],
180+ [
181+ searchTerm,
182+ caseSensitive,
183+ useRegex,
184+ searchRef,
185+ headerHeight,
186+ scrollToMatch,
187+ ],
308188 );
309189
310190 // Triggers that should cause immediate refresh of results to closest search value:
311- // Input change (debounced) and window click
312- const lastUpdateRef = useRef(0);
313191 useEffect(() => {
314- const debounce = () => {
315- debouncedInput.current = input;
316- lastUpdateRef.current = Date.now();
317- refreshSearch("closest");
318- };
319- const timeSinceLastUpdate = Date.now() - lastUpdateRef.current;
320- if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) {
321- debounce();
192+ if (disabled || isResizing || !open) {
193+ setMatches([]);
322194 } else {
323- const handler = setTimeout(() => {
324- debounce();
325- }, SEARCH_DEBOUNCE - timeSinceLastUpdate);
326- return () => {
327- clearTimeout(handler);
328- };
195+ refreshSearch("closest");
329196 }
330- }, [refreshSearch, input]);
197+ }, [refreshSearch, open, disabled, isResizing]);
331198
332- // Could consider doing any window click but I only handled search div here
333- // Since usually only clicks in search div will cause content changes in search div
199+ // Clicks in search div can cause content changes that for some reason don't trigger resize
200+ // Refresh clicking within container
334201 useEffect(() => {
335202 const searchContainer = searchRef.current;
336203 if (!open || !searchContainer) return;
337204 const handleSearchRefClick = () => {
338- refreshSearch("none");
205+ setTimeout(() => {
206+ refreshSearch("none");
207+ }, 150);
339208 };
340209 searchContainer.addEventListener("click", handleSearchRefClick);
341210 return () => {
342211 searchContainer.removeEventListener("click", handleSearchRefClick);
343212 };
344- }, [searchRef.current, refreshSearch, open]);
345-
346- // Triggers that should cause results to temporarily disappear and then reload
347- // Active = LLM is generating, etc.
348- const active = useAppSelector((state) => state.session.isStreaming);
349-
350- useEffect(() => {
351- if (active || isResizing) setMatches([]);
352- else refreshSearch("none");
353- }, [refreshSearch, active]);
354-
355- useEffect(() => {
356- if (!open) setMatches([]);
357- else refreshSearch("closest");
358- }, [refreshSearch, open]);
359-
360- useEffect(() => {
361- refreshSearch("closest");
362- }, [refreshSearch, caseSensitive, useRegex]);
213+ }, [searchRef, refreshSearch, open]);
363214
364215 // Find widget component
365- const widget = useMemo(() => {
366- return (
367- <div
368- className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
369- >
370- <Input
371- disabled={active}
372- type="text"
373- ref={inputRef}
374- value={input}
375- onChange={(e) => {
376- setInput(e.target.value);
377- }}
378- placeholder="Search..."
379- />
380- <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
381- {matches.length === 0
382- ? "No results"
383- : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
384- </p>
385- <div className="hidden flex-row gap-0.5 sm:flex">
386- <HeaderButtonWithToolTip
387- tooltipPlacement="top-end"
388- text={"Previous Match"}
389- onClick={(e) => {
390- e.stopPropagation();
391- previousMatch();
392- }}
393- className="h-4 w-4 focus:ring"
394- disabled={matches.length < 2 || active}
395- >
396- <ArrowUpIcon className="h-4 w-4" />
397- </HeaderButtonWithToolTip>
398- <HeaderButtonWithToolTip
399- tooltipPlacement="top-end"
400- text={"Next Match"}
401- onClick={(e) => {
402- e.stopPropagation();
403- nextMatch();
404- }}
405- className="h-4 w-4 focus:ring"
406- disabled={matches.length < 2 || active}
407- >
408- <ArrowDownIcon className="h-4 w-4" />
409- </HeaderButtonWithToolTip>
410- </div>
216+ const widget = (
217+ <div
218+ className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
219+ >
220+ <Input
221+ disabled={disabled}
222+ type="text"
223+ ref={inputRef}
224+ value={currentValue}
225+ onChange={(e) => {
226+ setCurrentValue(e.target.value);
227+ }}
228+ placeholder="Search..."
229+ />
230+ <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
231+ {matches.length === 0
232+ ? "No results"
233+ : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
234+ </p>
235+ <div className="hidden flex-row gap-0.5 sm:flex">
411236 <HeaderButtonWithToolTip
412- disabled={active}
413- inverted={caseSensitive}
414237 tooltipPlacement="top-end"
415- text={
416- caseSensitive
417- ? "Turn off case sensitivity"
418- : "Turn on case sensitivity"
419- }
238+ text={"Previous Match"}
420239 onClick={(e) => {
421240 e.stopPropagation();
422- setCaseSensitive((curr) => !curr);
241+ previousMatch();
423242 }}
424- className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
243+ className="h-4 w-4 focus:ring"
244+ disabled={matches.length < 2 || disabled}
425245 >
426- Aa
246+ <ArrowUpIcon className="h-4 w-4" />
427247 </HeaderButtonWithToolTip>
428- {/* TODO - add useRegex functionality */}
429- <HeaderButton
430- inverted={false}
431- onClick={() => setOpen(false)}
432- className="focus:ring"
248+ <HeaderButtonWithToolTip
249+ tooltipPlacement="top-end"
250+ text={"Next Match"}
251+ onClick={(e) => {
252+ e.stopPropagation();
253+ nextMatch();
254+ }}
255+ className="h-4 w-4 focus:ring"
256+ disabled={matches.length < 2 || disabled}
433257 >
434- <XMarkIcon className="h-4 w-4" />
435- </HeaderButton>
258+ <ArrowDownIcon className="h-4 w-4" />
259+ </HeaderButtonWithToolTip>
436260 </div>
437- );
438- }, [
439- open,
440- input,
441- inputRef,
442- caseSensitive,
443- matches,
444- currentMatch,
445- previousMatch,
446- nextMatch,
447- ]);
261+ <HeaderButtonWithToolTip
262+ disabled={disabled}
263+ inverted={caseSensitive}
264+ tooltipPlacement="top-end"
265+ text={
266+ caseSensitive
267+ ? "Turn off case sensitivity"
268+ : "Turn on case sensitivity"
269+ }
270+ onClick={(e) => {
271+ e.stopPropagation();
272+ setCaseSensitive((curr) => !curr);
273+ }}
274+ className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
275+ >
276+ Aa
277+ </HeaderButtonWithToolTip>
278+ {/* TODO - add useRegex functionality */}
279+ <HeaderButton
280+ inverted={false}
281+ onClick={() => setOpen(false)}
282+ className="focus:ring"
283+ >
284+ <XMarkIcon className="h-4 w-4" />
285+ </HeaderButton>
286+ </div>
287+ );
448288
449289 // Generate the highlight overlay elements
450290 const highlights = useMemo(() => {
451291 return matches.map((match) => (
452292 <HighlightOverlay
453- {...match.overlayRectangle}
293+ rectangle={match.overlayRectangle}
454294 isCurrent={currentMatch?.index === match.index}
455295 />
456296 ));
457297 }, [matches, currentMatch]);
458298
459299 return {
460- matches,
461300 highlights,
462- inputRef,
463- input: debouncedInput,
464- setInput,
465- open,
466- setOpen,
467301 widget,
468302 };
469303 };
added gui/src/components/find/findWidgetSearch.ts +146 −0
@@ -0,0 +1,146 @@
1+export interface Rectangle {
2+ top: number;
3+ left: number;
4+ width: number;
5+ height: number;
6+}
7+
8+export interface SearchMatch {
9+ index: number;
10+ textNode: Text;
11+ overlayRectangle: Rectangle;
12+}
13+
14+interface SearchOptions {
15+ caseSensitive: boolean;
16+ useRegex: boolean;
17+ offsetHeight: number;
18+}
19+
20+export const searchWithinContainer = (
21+ containerRef: React.RefObject<HTMLDivElement>,
22+ searchQuery: string,
23+ options: SearchOptions,
24+): {
25+ results: SearchMatch[];
26+ closestToMiddle: SearchMatch | null;
27+} => {
28+ const searchContainer = containerRef.current;
29+
30+ if (!searchContainer || !searchQuery) {
31+ return {
32+ results: [],
33+ closestToMiddle: null,
34+ };
35+ }
36+ const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase();
37+
38+ // First grab all text nodes
39+ // Skips any elements with the "find-widget-skip" class
40+ const textNodes: Text[] = [];
41+ const walker = document.createTreeWalker(
42+ searchContainer,
43+ NodeFilter.SHOW_ALL,
44+ {
45+ acceptNode: (node) => {
46+ if (node.nodeType === Node.ELEMENT_NODE) {
47+ if ((node as Element).classList.contains("find-widget-skip"))
48+ return NodeFilter.FILTER_REJECT;
49+ return NodeFilter.FILTER_ACCEPT;
50+ } else if (node.nodeType === Node.TEXT_NODE) {
51+ if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
52+ const nodeValue = options.caseSensitive
53+ ? node.nodeValue
54+ : node.nodeValue.toLowerCase();
55+ if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
56+ }
57+ return NodeFilter.FILTER_REJECT;
58+ },
59+ },
60+ );
61+
62+ while (walker.nextNode()) {
63+ if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
64+ textNodes.push(walker.currentNode as Text);
65+ }
66+
67+ // Now walk through each node match and extract search results
68+ // One node can have several matches
69+ const newMatches: SearchMatch[] = [];
70+ textNodes.forEach((textNode, idx) => {
71+ // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
72+ const highlightFullLine =
73+ textNode.parentElement?.className.includes("hljs");
74+
75+ let nodeTextValue = options.caseSensitive
76+ ? textNode.nodeValue
77+ : textNode.nodeValue.toLowerCase();
78+ let startIndex = 0;
79+ while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
80+ // Create a range to measure the size and position of the match
81+ const range = document.createRange();
82+ range.setStart(textNode, startIndex);
83+ const endIndex = startIndex + query.length;
84+ range.setEnd(textNode, endIndex);
85+ const rect = range.getBoundingClientRect();
86+ range.detach();
87+ startIndex = endIndex;
88+
89+ const top =
90+ rect.top +
91+ searchContainer.clientTop +
92+ searchContainer.scrollTop -
93+ options.offsetHeight;
94+
95+ const left =
96+ rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
97+
98+ // Build a match result and push to matches
99+ const newMatch: SearchMatch = {
100+ index: 0, // will set later
101+ textNode,
102+ overlayRectangle: {
103+ top,
104+ left: highlightFullLine ? 2 : left,
105+ width: highlightFullLine
106+ ? searchContainer.clientWidth - 4
107+ : rect.width, // equivalent of adding 2 px x padding
108+ height: rect.height,
109+ },
110+ };
111+ newMatches.push(newMatch);
112+
113+ if (highlightFullLine) {
114+ break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
115+ }
116+ }
117+ });
118+
119+ // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
120+ // Filter them out by using the overlay rectangle as a hash key
121+ const matchHash = Object.fromEntries(
122+ newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]),
123+ );
124+ const filteredMatches = Object.values(matchHash).map((match, index) => ({
125+ ...match,
126+ index,
127+ }));
128+
129+ // Find the match closest to the vertical middle of the container
130+ const verticalMiddle =
131+ searchContainer.scrollTop + searchContainer.clientHeight / 2;
132+ let closestDist = Infinity;
133+ let closestMatchToMiddle: SearchMatch | null = null;
134+ filteredMatches.forEach((match) => {
135+ const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
136+ if (dist < closestDist) {
137+ closestDist = dist;
138+ closestMatchToMiddle = match;
139+ }
140+ });
141+
142+ return {
143+ results: filteredMatches,
144+ closestToMiddle: closestMatchToMiddle,
145+ };
146+};
added gui/src/components/find/useDebounce.ts +19 −0
@@ -0,0 +1,19 @@
1+import { useEffect, useState } from "react";
2+
3+function useDebounceValue<T>(value: T, delay: number = 500): T {
4+ const [debouncedValue, setDebouncedValue] = useState<T>(value);
5+
6+ useEffect(() => {
7+ const timer = setTimeout(() => {
8+ setDebouncedValue(value);
9+ }, delay);
10+
11+ return () => {
12+ clearTimeout(timer);
13+ };
14+ }, [value, delay]);
15+
16+ return debouncedValue;
17+}
18+
19+export default useDebounceValue;
added gui/src/components/find/useElementSize.ts +81 −0
@@ -0,0 +1,81 @@
1+import { RefObject, useCallback, useEffect, useState } from "react";
2+
3+interface ElementSize {
4+ clientWidth: number;
5+ clientHeight: number;
6+ scrollWidth: number;
7+ scrollHeight: number;
8+ isResizing: boolean;
9+}
10+
11+interface UseElementSizeOptions {
12+ debounceMs?: number;
13+}
14+
15+export const useElementSize = (
16+ ref: RefObject<HTMLElement>,
17+ debounceMs = 250,
18+): ElementSize => {
19+ const [size, setSize] = useState<ElementSize>({
20+ clientWidth: 0,
21+ clientHeight: 0,
22+ scrollWidth: 0,
23+ scrollHeight: 0,
24+ isResizing: false,
25+ });
26+
27+ // Debounced update function
28+ const debouncedSetSize = useCallback(
29+ (measurements: Omit<ElementSize, "isResizing">) => {
30+ let timeoutId: NodeJS.Timeout;
31+
32+ setSize((prev) => ({ ...prev, isResizing: true }));
33+
34+ timeoutId = setTimeout(() => {
35+ setSize({
36+ ...measurements,
37+ isResizing: false,
38+ });
39+ }, debounceMs);
40+
41+ return () => clearTimeout(timeoutId);
42+ },
43+ [debounceMs],
44+ );
45+
46+ useEffect(() => {
47+ if (!ref.current) return;
48+
49+ const updateSize = () => {
50+ const element = ref.current;
51+ if (!element) return;
52+
53+ const measurements = {
54+ clientWidth: element.clientWidth,
55+ clientHeight: element.clientHeight,
56+ scrollWidth: element.scrollWidth,
57+ scrollHeight: element.scrollHeight,
58+ };
59+
60+ debouncedSetSize(measurements);
61+ };
62+
63+ // Create ResizeObserver instance
64+ const resizeObserver = new ResizeObserver(() => {
65+ updateSize();
66+ });
67+
68+ // Start observing the element
69+ resizeObserver.observe(ref.current);
70+
71+ // Initial size calculation
72+ updateSize();
73+
74+ // Cleanup
75+ return () => {
76+ resizeObserver.disconnect();
77+ };
78+ }, [ref, debouncedSetSize]);
79+
80+ return size;
81+};
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 +11 −6
@@ -44,16 +44,17 @@
4444 setDialogMessage,
4545 setShowDialog,
4646 } from "../../redux/slices/uiSlice";
47+import { streamResponseThunk } from "../../redux/thunks";
4748 import { cancelStream } from "../../redux/thunks/cancelStream";
4849 import { streamEditThunk } from "../../redux/thunks/editMode";
4950 import { loadLastSession } from "../../redux/thunks/session";
50-import { streamResponseThunk } from "../../redux/thunks";
5151 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
5252 import {
5353 FREE_TRIAL_LIMIT_REQUESTS,
5454 incrementFreeTrialCount,
5555 } from "../../util/freeTrial";
5656
57+import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
5758 import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
5859 import EditModeDetails from "../../components/mainInput/EditModeDetails";
5960 import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
@@ -61,7 +62,6 @@
6162 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
6263 import { ToolCallDiv } from "./ToolCallDiv";
6364 import { useAutoScroll } from "./useAutoScroll";
64-import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
6565
6666 const StepsDiv = styled.div`
6767 position: relative;
@@ -113,6 +113,7 @@
113113 const [stepsOpen] = useState<(boolean | undefined)[]>([]);
114114 const mainTextInputRef = useRef<HTMLInputElement>(null);
115115 const stepsDivRef = useRef<HTMLDivElement>(null);
116+ const tabsRef = useRef<HTMLDivElement>(null);
116117 const history = useAppSelector((state) => state.session.history);
117118 const showChatScrollbar = useAppSelector(
118119 (state) => state.config.config.ui?.showChatScrollbar,
@@ -143,6 +144,7 @@
143144 !e.shiftKey
144145 ) {
145146 dispatch(cancelStream());
147+ ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
146148 }
147149 };
148150 window.addEventListener("keydown", listener);
@@ -152,7 +154,11 @@
152154 };
153155 }, [isStreaming, jetbrains]);
154156
155- const { widget, highlights } = useFindWidget(stepsDivRef);
157+ const { widget, highlights } = useFindWidget(
158+ stepsDivRef,
159+ tabsRef,
160+ isStreaming,
161+ );
156162
157163 const currentToolCallApplyState = useAppSelector(
158164 selectCurrentToolCallApplyState,
@@ -286,13 +292,12 @@
286292
287293 return (
288294 <>
295+ {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />}
289296 {widget}
290297
291- {!!showSessionTabs && mode !== "edit" && <TabBar />}
292-
293298 <StepsDiv
294299 ref={stepsDivRef}
295- className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
300+ className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
296301 >
297302 {highlights}
298303 {history.map((item, index: number) => (
modified gui/src/pages/gui/StreamError.tsx +86 −47
@@ -1,12 +1,15 @@
11 import {
22 ArrowTopRightOnSquareIcon,
3- Cog8ToothIcon,
3+ ClipboardIcon,
4+ Cog6ToothIcon,
5+ KeyIcon,
46 } from "@heroicons/react/24/outline";
57 import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
68 import { useContext, useMemo } from "react";
7-import { Button, SecondaryButton } from "../../components";
9+import { GhostButton, SecondaryButton } from "../../components";
810 import { DiscordIcon } from "../../components/svg/DiscordIcon";
911 import { GithubIcon } from "../../components/svg/GithubIcon";
12+import ToggleDiv from "../../components/ToggleDiv";
1013 import { useAuth } from "../../context/Auth";
1114 import { IdeMessengerContext } from "../../context/IdeMessenger";
1215 import { selectSelectedProfile } from "../../redux/";
@@ -48,11 +51,15 @@
4851 );
4952
5053 const handleRefreshProfiles = () => {
51- refreshProfiles();
54+ void refreshProfiles();
5255 dispatch(setShowDialog(false));
5356 dispatch(setDialogMessage(undefined));
5457 };
5558
59+ const copyErrorToClipboard = () => {
60+ void navigator.clipboard.writeText(parsedError);
61+ };
62+
5663 // Collect model information to display useful error info
5764 let modelTitle = "Chat model";
5865 let providerName = "the model provider";
@@ -99,30 +106,29 @@
99106 }
100107
101108 const checkKeysButton = apiKeyUrl ? (
102- <Button
103- className="cursor-pointer hover:underline"
109+ <GhostButton
110+ className="flex items-center"
104111 onClick={() => {
105112 ideMessenger.post("openUrl", apiKeyUrl!);
106113 }}
107114 >
108- Check keys/usage
109- </Button>
115+ <KeyIcon className="mr-1.5 h-3.5 w-3.5" />
116+ <span>View key</span>
117+ </GhostButton>
110118 ) : null;
111119
112120 const configButton = (
113- <SecondaryButton
114- className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70"
121+ <GhostButton
122+ className="flex items-center"
115123 onClick={() => {
116124 ideMessenger.post("config/openProfile", {
117125 profileId: undefined,
118126 });
119127 }}
120128 >
121- <div>
122- <Cog8ToothIcon className="h-4 w-4" />
123- </div>
124- <span>Open Assistant configuration</span>
125- </SecondaryButton>
129+ <Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
130+ <span>View config</span>
131+ </GhostButton>
126132 );
127133
128134 if (
@@ -131,7 +137,20 @@
131137 return <ModelsAddOnLimitDialog />;
132138 }
133139
134- let errorContent: React.ReactNode = <></>;
140+ let errorContent = (
141+ <div className="mb-3 mt-1">
142+ <div className="m-0 p-0">
143+ <p className="m-0 mb-2 p-0">
144+ There was an error handling the response from{" "}
145+ {selectedModel?.title || "the model"}.
146+ </p>
147+ <p className="m-0 p-0">
148+ Please try to submit your message again, and if the error persists,
149+ let us know by reporting the issue using the buttons below.
150+ </p>
151+ </div>
152+ </div>
153+ );
135154
136155 // Display components for specific errors
137156 if (statusCode === 429) {
@@ -141,7 +160,7 @@
141160 {`This might mean your ${modelTitle} usage has been rate limited
142161 by ${providerName}.`}
143162 </span>
144- <div className="flex flex-row flex-wrap gap-2">
163+ <div className="flex flex-row flex-wrap justify-start gap-3 py-4">
145164 {checkKeysButton}
146165 {configButton}
147166 </div>
@@ -230,51 +249,71 @@
230249 );
231250 }
232251
252+ console.log({ message });
253+
233254 return (
234- <div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}>
235- <p className="m-0 p-0 text-lg text-red-500">
236- {statusCode ? `Error (status code ${statusCode})` : "Error"}
237- </p>
238-
239- {message ? (
240- <div className="mt-2 flex flex-col gap-0 rounded-sm">
241- <code className="max-h-20 overflow-y-auto p-2 font-mono">
242- {parsedError}
243- </code>
244- <div
245- className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline"
246- onClick={() => {
247- ideMessenger.post("toggleDevTools", undefined);
248- }}
249- >
250- <span className="px-2">View Logs</span>
251- <ArrowTopRightOnSquareIcon className="h-4 w-4" />
252- </div>
255+ <div className="flex flex-col gap-4 px-3 pb-3 pt-3">
256+ {/* Concise error title */}
257+ <h3 className="text-error m-0 p-0 text-lg font-medium">
258+ Error handling model response
259+ </h3>
260+
261+ {errorContent}
262+
263+ {/* Expandable technical details using ToggleDiv */}
264+ {message && (
265+ <div className="mb-2">
266+ <ToggleDiv title="View error output" testId="error-output-toggle">
267+ <div className="flex flex-col gap-0 rounded-sm">
268+ <code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs">
269+ {parsedError}
270+ </code>
271+
272+ <div className="flex flex-row items-center justify-end gap-2 p-2">
273+ <GhostButton
274+ onClick={copyErrorToClipboard}
275+ className="flex items-center"
276+ >
277+ <ClipboardIcon className="mr-1.5 h-3.5 w-3.5" />
278+ <span>Copy output</span>
279+ </GhostButton>
280+
281+ <GhostButton
282+ onClick={() => {
283+ ideMessenger.post("toggleDevTools", undefined);
284+ }}
285+ className="flex items-center"
286+ >
287+ <ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" />
288+ <span className="text-xs">View Logs</span>
289+ </GhostButton>
290+ </div>
291+ </div>
292+ </ToggleDiv>
253293 </div>
254- ) : null}
255- <div className="mt-3">{errorContent}</div>
256-
257- <div className="mt-2 flex flex-col gap-1.5">
258- <span>Report this error:</span>
259- <div className="flex flex-row flex-wrap items-center gap-2">
260- <SecondaryButton
261- className="flex flex-row items-center gap-2 hover:opacity-70"
294+ )}
295+
296+ <div>
297+ <span className="text-base font-medium">Report this error</span>
298+ <div className="mt-2 flex flex-row flex-wrap items-center gap-2">
299+ <GhostButton
300+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
262301 onClick={() => {
263302 ideMessenger.post("openUrl", GITHUB_LINK);
264303 }}
265304 >
266305 <GithubIcon className="h-5 w-5" />
267306 <span className="xs:flex hidden">Github</span>
268- </SecondaryButton>
269- <SecondaryButton
270- className="flex flex-row items-center gap-2 hover:opacity-70"
307+ </GhostButton>
308+ <GhostButton
309+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
271310 onClick={() => {
272311 ideMessenger.post("openUrl", DISCORD_LINK);
273312 }}
274313 >
275314 <DiscordIcon className="h-5 w-5" />
276315 <span className="xs:flex hidden">Discord</span>
277- </SecondaryButton>
316+ </GhostButton>
278317 </div>
279318 </div>
280319 </div>
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}
modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.87",
9+ "version": "1.0.88",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/config-yaml/src/load/clientRender.ts +1 −0
@@ -160,6 +160,7 @@
160160 apiKeyLocation: z.string().optional(),
161161 apiBase: z.string().optional(),
162162 orgScopeId: z.string().nullable(),
163+ env: z.record(z.string(), z.any()).optional(),
163164 });
164165
165166 export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;
modified packages/config-yaml/src/schemas/index.ts +6 −2
@@ -9,13 +9,16 @@
99 params: z.any().optional(),
1010 });
1111
12+// TODO: This should be a discriminated union by type
1213 const mcpServerSchema = z.object({
1314 name: z.string(),
14- command: z.string(),
15+ command: z.string().optional(),
16+ type: z.enum(["sse", "stdio"]).optional(),
17+ url: z.string().optional(),
1518 faviconUrl: z.string().optional(),
1619 args: z.array(z.string()).optional(),
1720 env: z.record(z.string()).optional(),
18- connectionTimeout: z.number().gt(0).optional()
21+ connectionTimeout: z.number().gt(0).optional(),
1922 });
2023
2124 export type MCPServer = z.infer<typeof mcpServerSchema>;
@@ -39,6 +42,7 @@
3942 const ruleObjectSchema = z.object({
4043 name: z.string(),
4144 rule: z.string(),
45+ description: z.string().optional(),
4246 globs: z.union([z.string(), z.array(z.string())]).optional(),
4347 });
4448 const ruleSchema = z.union([z.string(), ruleObjectSchema]);
modified packages/config-yaml/src/schemas/models.ts +1 −0
@@ -117,6 +117,7 @@
117117 model: z.string(),
118118 apiKey: z.string().optional(),
119119 apiBase: z.string().optional(),
120+ maxStopWords: z.number().optional(),
120121 roles: modelRolesSchema.array().optional(),
121122 capabilities: modelCapabilitySchema.array().optional(),
122123 defaultCompletionOptions: completionOptionsSchema.optional(),
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/README.md +1 −1
@@ -64,7 +64,7 @@
6464 - [x] Vllm
6565 - [ ] Vertex AI
6666 - [x] Voyage AI
67-- [ ] WatsonX
67+- [x] WatsonX
6868 - [x] xAI
6969 - [x] Fireworks
7070 - [x] Moonshot
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 +2 −2
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.26",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
@@ -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/apis/WatsonX.ts +314 −0
@@ -0,0 +1,314 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { OpenAI } from "openai/index";
3+import {
4+ ChatCompletion,
5+ ChatCompletionChunk,
6+ ChatCompletionCreateParamsNonStreaming,
7+ ChatCompletionCreateParamsStreaming,
8+ Completion,
9+ CompletionCreateParamsNonStreaming,
10+ CompletionCreateParamsStreaming,
11+} from "openai/resources/index";
12+import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
13+import { WatsonXConfig } from "../types.js";
14+import { chatCompletion, customFetch } from "../util.js";
15+import {
16+ BaseLlmApi,
17+ CreateRerankResponse,
18+ FimCreateParamsStreaming,
19+ RerankCreateParams,
20+} from "./base.js";
21+
22+export class WatsonXApi implements BaseLlmApi {
23+ apiBase: string;
24+ apiVersion: string = "2023-05-29";
25+ projectId?: string;
26+ deploymentId?: string;
27+
28+ constructor(protected config: WatsonXConfig) {
29+ this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
30+ if (!this.apiBase.endsWith("/")) {
31+ this.apiBase += "/";
32+ }
33+ this.apiVersion = config.env.apiVersion ?? this.apiVersion;
34+ this.projectId = config.env.projectId;
35+ this.deploymentId = config.env.deploymentId;
36+ }
37+
38+ private async getHeaders(): Promise<Record<string, string>> {
39+ const bearer = await this.getBearerToken();
40+ return {
41+ "Content-Type": "application/json",
42+ Authorization: `Bearer ${bearer.token}`,
43+ };
44+ }
45+
46+ async getBearerToken(): Promise<{ token: string; expiration: number }> {
47+ if (this.apiBase?.includes("cloud.ibm.com")) {
48+ // watsonx SaaS
49+ const wxToken = (await (
50+ await customFetch(this.config.requestOptions)(
51+ `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
52+ {
53+ method: "POST",
54+ headers: {
55+ "Content-Type": "application/x-www-form-urlencoded",
56+ Accept: "application/json",
57+ },
58+ },
59+ )
60+ ).json()) as any;
61+ return {
62+ token: wxToken["access_token"],
63+ expiration: wxToken["expiration"],
64+ };
65+ } else {
66+ // watsonx Software
67+ if (!this.config.apiKey?.includes(":")) {
68+ // Using ZenApiKey auth
69+ return {
70+ token: this.config.apiKey ?? "",
71+ expiration: -1,
72+ };
73+ } else {
74+ // Using username/password auth
75+ const userPass = this.config.apiKey?.split(":");
76+ const wxToken = (await (
77+ await customFetch(this.config.requestOptions)(
78+ `${this.apiBase}/icp4d-api/v1/authorize`,
79+ {
80+ method: "POST",
81+ headers: {
82+ "Content-Type": "application/json",
83+ Accept: "application/json",
84+ },
85+ body: JSON.stringify({
86+ username: userPass[0],
87+ password: userPass[1],
88+ }),
89+ },
90+ )
91+ ).json()) as any;
92+ const wxTokenExpiry = (await (
93+ await customFetch(this.config.requestOptions)(
94+ `${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
95+ {
96+ method: "GET",
97+ headers: {
98+ Accept: "application/json",
99+ Authorization: `Bearer ${wxToken["token"]}`,
100+ },
101+ },
102+ )
103+ ).json()) as any;
104+ return {
105+ token: wxToken["token"],
106+ expiration: wxTokenExpiry["exp"],
107+ };
108+ }
109+ }
110+ }
111+
112+ private getEndpoint(endpoint: string): string {
113+ return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
114+ }
115+
116+ private _convertBody(oaiBody: ChatCompletionCreateParams) {
117+ const stopSequences = oaiBody.stop
118+ ? Array.isArray(oaiBody.stop)
119+ ? oaiBody.stop.filter((s) => s.trim() !== "")
120+ : [oaiBody.stop]
121+ : undefined;
122+
123+ const payload: any = {
124+ messages: oaiBody.messages,
125+ max_tokens: oaiBody.max_tokens ?? 1024,
126+ stop: stopSequences,
127+ frequency_penalty: oaiBody.frequency_penalty,
128+ presence_penalty: oaiBody.presence_penalty,
129+ };
130+
131+ if (!this.deploymentId) {
132+ payload.model_id = oaiBody.model;
133+ payload.project_id = this.projectId;
134+ }
135+
136+ if (oaiBody.temperature !== undefined) {
137+ payload.temperature = oaiBody.temperature;
138+ }
139+
140+ if (oaiBody.top_p !== undefined) {
141+ payload.top_p = oaiBody.top_p;
142+ }
143+
144+ if (oaiBody.tools) {
145+ payload.tools = oaiBody.tools;
146+ if (oaiBody.tool_choice) {
147+ payload.tool_choice = oaiBody.tool_choice;
148+ } else {
149+ payload.tool_choice_option = "auto";
150+ }
151+ }
152+
153+ return payload;
154+ }
155+
156+ async chatCompletionNonStream(
157+ body: ChatCompletionCreateParamsNonStreaming,
158+ signal: AbortSignal,
159+ ): Promise<ChatCompletion> {
160+ const generator = this.chatCompletionStream(
161+ {
162+ ...body,
163+ stream: true,
164+ },
165+ signal,
166+ );
167+
168+ let content = "";
169+ for await (const chunk of generator) {
170+ content += chunk.choices[0].delta.content ?? "";
171+ }
172+ return chatCompletion({
173+ content,
174+ model: body.model,
175+ });
176+ }
177+
178+ async *chatCompletionStream(
179+ body: ChatCompletionCreateParamsStreaming,
180+ signal: AbortSignal,
181+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
182+ const url = this.getEndpoint("chat");
183+ const headers = await this.getHeaders();
184+ const stringifiedBody = JSON.stringify(this._convertBody(body));
185+ const response = await customFetch(this.config.requestOptions)(url, {
186+ method: "POST",
187+ headers,
188+ body: stringifiedBody,
189+ signal,
190+ });
191+
192+ if (!response.ok || !response.body) {
193+ throw new Error(
194+ `Failed to stream chat completion: ${await response.text()}`,
195+ );
196+ }
197+
198+ for await (const value of streamSse(response as any)) {
199+ if (!value.choices?.[0]) {
200+ continue;
201+ }
202+ yield value;
203+ }
204+ }
205+
206+ async completionNonStream(
207+ body: CompletionCreateParamsNonStreaming,
208+ signal: AbortSignal,
209+ ): Promise<Completion> {
210+ throw new Error("Method not implemented.");
211+ }
212+
213+ async *completionStream(
214+ body: CompletionCreateParamsStreaming,
215+ signal: AbortSignal,
216+ ): AsyncGenerator<Completion, any, unknown> {
217+ const params = {
218+ decoding_method: body.temperature ? "sample" : "greedy",
219+ max_new_tokens: body.max_tokens ?? 1024,
220+ min_new_tokens: 1,
221+ stop_sequences: body.stop
222+ ? Array.isArray(body.stop)
223+ ? body.stop
224+ : [body.stop]
225+ : [],
226+ include_stop_sequence: false,
227+ repetition_penalty: body.frequency_penalty || 1,
228+ temperature: body.temperature,
229+ top_p: body.top_p,
230+ top_k: 100,
231+ };
232+
233+ const payload: any = {
234+ input: body.prompt,
235+ parameters: params,
236+ };
237+
238+ if (!this.deploymentId) {
239+ payload.model_id = body.model;
240+ payload.project_id = this.projectId;
241+ }
242+
243+ const url = this.getEndpoint("generation");
244+ const response = await customFetch(this.config.requestOptions)(url, {
245+ method: "POST",
246+ headers: await this.getHeaders(),
247+ body: JSON.stringify(payload),
248+ signal,
249+ });
250+
251+ if (!response.ok || !response.body) {
252+ throw new Error(`Failed to stream completion: ${await response.text()}`);
253+ }
254+
255+ let generatedText = "";
256+ for await (const value of streamSse(response as any)) {
257+ const lines = value.toString().split("\n");
258+ let generatedChunk = "";
259+
260+ lines.forEach((line: string) => {
261+ if (line.startsWith("data:")) {
262+ const dataStr = line.replace(/^data:\s+/, "");
263+ try {
264+ const data = JSON.parse(dataStr);
265+ data.results.forEach((result: any) => {
266+ generatedChunk += result.generated_text || "";
267+ });
268+ } catch (e) {
269+ // parsing error is expected with streaming response
270+ }
271+ }
272+ });
273+
274+ if (generatedChunk) {
275+ generatedText += generatedChunk;
276+ yield {
277+ id: `watsonx-${Date.now()}`,
278+ object: "text_completion",
279+ created: Date.now(),
280+ model: body.model,
281+ choices: [
282+ {
283+ text: generatedChunk,
284+ index: 0,
285+ logprobs: null,
286+ finish_reason: "stop",
287+ },
288+ ],
289+ };
290+ }
291+ }
292+ }
293+
294+ async *fimStream(
295+ body: FimCreateParamsStreaming,
296+ signal: AbortSignal,
297+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
298+ throw new Error("Method not implemented.");
299+ }
300+
301+ async embed(
302+ body: OpenAI.Embeddings.EmbeddingCreateParams,
303+ ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
304+ throw new Error("Method not implemented.");
305+ }
306+
307+ async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
308+ throw new Error("Method not implemented.");
309+ }
310+
311+ async list(): Promise<OpenAI.Models.Model[]> {
312+ throw new Error("Method not implemented.");
313+ }
314+}
modified packages/openai-adapters/src/index.ts +8 −3
@@ -11,6 +11,7 @@
1111 import { MoonshotApi } from "./apis/Moonshot.js";
1212 import { OpenAIApi } from "./apis/OpenAI.js";
1313 import { RelaceApi } from "./apis/Relace.js";
14+import { WatsonXApi } from "./apis/WatsonX.js";
1415 import { BaseLlmApi } from "./apis/base.js";
1516 import { LLMConfig, OpenAIConfigSchema } from "./types.js";
1617
@@ -48,6 +49,8 @@
4849 return new RelaceApi(config);
4950 case "inception":
5051 return new InceptionApi(config);
52+ case "watsonx":
53+ return new WatsonXApi(config);
5154 case "x-ai":
5255 return openAICompatible("https://api.x.ai/v1/", config);
5356 case "voyage":
@@ -75,7 +78,10 @@
7578 case "nvidia":
7679 return openAICompatible("https://integrate.api.nvidia.com/v1/", config);
7780 case "ovhcloud":
78- return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config);
81+ return openAICompatible(
82+ "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
83+ config,
84+ );
7985 case "scaleway":
8086 return openAICompatible("https://api.scaleway.ai/v1/", config);
8187 case "fireworks":
@@ -111,10 +117,9 @@
111117 type Completion,
112118 type CompletionCreateParams,
113119 type CompletionCreateParamsNonStreaming,
114- type CompletionCreateParamsStreaming
120+ type CompletionCreateParamsStreaming,
115121 } from "openai/resources/index";
116122
117123 // export
118124 export type { BaseLlmApi } from "./apis/base.js";
119125 export type { LLMConfig } from "./types.js";
120-
modified packages/openai-adapters/src/test/main.test.ts +1 −0
@@ -10,6 +10,7 @@
1010 provider: config.provider as any,
1111 apiKey: config.apiKey,
1212 apiBase: config.apiBase,
13+ env: config.env,
1314 });
1415
1516 if (false) {
modified packages/openai-adapters/src/types.ts +12 −0
@@ -99,6 +99,17 @@
9999 });
100100 export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>;
101101
102+export const WatsonXConfigSchema = BasePlusConfig.extend({
103+ provider: z.literal("watsonx"),
104+ apiKey: z.string(),
105+ env: z.object({
106+ apiVersion: z.string().optional(),
107+ projectId: z.string().optional(),
108+ deploymentId: z.string().optional(),
109+ }),
110+});
111+export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>;
112+
102113 export const JinaConfigSchema = OpenAIConfigSchema.extend({
103114 provider: z.literal("jina"),
104115 });
@@ -118,6 +129,7 @@
118129 AzureConfigSchema,
119130 GeminiConfigSchema,
120131 AnthropicConfigSchema,
132+ WatsonXConfigSchema,
121133 JinaConfigSchema,
122134 MockConfigSchema,
123135 InceptionConfigSchema,
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+};