Changesets · Branches · Tags · Compare
| Changeset | e3489ccbde59a380466222f7836bc2e994a97d411dacdf549f3bc3876635c5eb |
|---|---|
| Author | Nate <sestinj@gmail.com> · 2025-05-25 17:44 -07:00 |
| Committer | Nate <sestinj@gmail.com> · 2025-05-25 17:44 -07:00 |
| Parents | 1f089284a191, 54ea0739010d |
86 files changed
modified core/commands/slash/http.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 1 | 2 | import { SlashCommand } from "../../index.js"; |
| 2 | 3 | import { removeQuotesAndEscapes } from "../../util/index.js"; |
| 3 | -import { streamResponse } from "../../llm/stream.js"; | |
| 4 | 4 | |
| 5 | 5 | const HttpSlashCommand: SlashCommand = { |
| 6 | 6 | name: "http", |
modified core/config/markdown/parseMarkdownRule.test.ts +20 −0
| @@ -151,4 +151,24 @@ | ||
| 151 | 151 | ); |
| 152 | 152 | expect(result.name).toBe("custom-rule"); |
| 153 | 153 | }); |
| 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 | + }); | |
| 154 | 174 | }); |
modified core/config/markdown/parseMarkdownRule.ts +2 −1
| @@ -59,9 +59,10 @@ | ||
| 59 | 59 | } |
| 60 | 60 | |
| 61 | 61 | return { |
| 62 | + name, | |
| 62 | 63 | rule: markdown, |
| 63 | 64 | globs: frontmatter.globs, |
| 64 | - name, | |
| 65 | + description: frontmatter.description, | |
| 65 | 66 | source: "rules-block", |
| 66 | 67 | ruleFile: path, |
| 67 | 68 | }; |
modified core/config/util.ts +1 −0
| @@ -77,6 +77,7 @@ | ||
| 77 | 77 | model: model.model, |
| 78 | 78 | apiKey: model.apiKey, |
| 79 | 79 | apiBase: model.apiBase, |
| 80 | + maxStopWords: model.maxStopWords, | |
| 80 | 81 | defaultCompletionOptions: model.completionOptions, |
| 81 | 82 | }; |
| 82 | 83 | if (model.systemMessage) { |
modified core/config/yaml/loadYaml.ts +2 −2
| @@ -71,7 +71,7 @@ | ||
| 71 | 71 | command: server.command, |
| 72 | 72 | args: server.args ?? [], |
| 73 | 73 | env: server.env, |
| 74 | - }, | |
| 74 | + } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) | |
| 75 | 75 | timeout: server.connectionTimeout, |
| 76 | 76 | }; |
| 77 | 77 | } |
| @@ -458,7 +458,7 @@ | ||
| 458 | 458 | transport: { |
| 459 | 459 | type: "stdio", |
| 460 | 460 | args: [], |
| 461 | - ...server, | |
| 461 | + ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 462 | 462 | }, |
| 463 | 463 | timeout: server.connectionTimeout, |
| 464 | 464 | })), |
modified core/control-plane/schema.ts +1 −0
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | apiKey: z.string().optional(), |
| 27 | 27 | apiBase: z.string().optional(), |
| 28 | 28 | contextLength: z.number().optional(), |
| 29 | + maxStopWords: z.number().optional(), | |
| 29 | 30 | template: z |
| 30 | 31 | .enum([ |
| 31 | 32 | "llama2", |
modified core/core.ts +65 −70
| @@ -35,7 +35,6 @@ | ||
| 35 | 35 | |
| 36 | 36 | import { |
| 37 | 37 | ContextItemWithId, |
| 38 | - DiffLine, | |
| 39 | 38 | IdeSettings, |
| 40 | 39 | ModelDescription, |
| 41 | 40 | RangeInFile, |
| @@ -62,61 +61,7 @@ | ||
| 62 | 61 | import { llmStreamChat } from "./llm/streamChat"; |
| 63 | 62 | import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; |
| 64 | 63 | 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"; | |
| 120 | 65 | |
| 121 | 66 | export class Core { |
| 122 | 67 | configHandler: ConfigHandler; |
| @@ -132,7 +77,18 @@ | ||
| 132 | 77 | this.globalContext.get("indexingPaused") === true, |
| 133 | 78 | ); |
| 134 | 79 | |
| 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 | + } | |
| 136 | 92 | |
| 137 | 93 | invoke<T extends keyof ToCoreProtocol>( |
| 138 | 94 | messageType: T, |
| @@ -301,7 +257,7 @@ | ||
| 301 | 257 | }); |
| 302 | 258 | |
| 303 | 259 | on("abort", (msg) => { |
| 304 | - this.abortedMessageIds.add(msg.messageId); | |
| 260 | + this.abortById(msg.data ?? msg.messageId); | |
| 305 | 261 | }); |
| 306 | 262 | |
| 307 | 263 | on("ping", (msg) => { |
| @@ -470,27 +426,28 @@ | ||
| 470 | 426 | } |
| 471 | 427 | }); |
| 472 | 428 | |
| 473 | - on("llm/streamChat", (msg) => | |
| 474 | - llmStreamChat( | |
| 429 | + on("llm/streamChat", (msg) => { | |
| 430 | + const abortController = this.addMessageAbortController(msg.messageId); | |
| 431 | + return llmStreamChat( | |
| 475 | 432 | this.configHandler, |
| 476 | - this.abortedMessageIds, | |
| 433 | + abortController, | |
| 477 | 434 | msg, |
| 478 | 435 | this.ide, |
| 479 | 436 | this.messenger, |
| 480 | - ), | |
| 481 | - ); | |
| 437 | + ); | |
| 438 | + }); | |
| 482 | 439 | |
| 483 | 440 | 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; | |
| 487 | 443 | if (!model) { |
| 488 | 444 | throw new Error("No chat model selected"); |
| 489 | 445 | } |
| 446 | + const abortController = this.addMessageAbortController(msg.messageId); | |
| 490 | 447 | |
| 491 | 448 | const completion = await model.complete( |
| 492 | 449 | msg.data.prompt, |
| 493 | - new AbortController().signal, | |
| 450 | + abortController.signal, | |
| 494 | 451 | msg.data.completionOptions, |
| 495 | 452 | ); |
| 496 | 453 | return completion; |
| @@ -532,9 +489,47 @@ | ||
| 532 | 489 | this.completionProvider.cancel(); |
| 533 | 490 | }); |
| 534 | 491 | |
| 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 | + }); | |
| 538 | 533 | |
| 539 | 534 | on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); |
| 540 | 535 |
modified core/edit/recursiveStream.ts +5 −2
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | export async function* recursiveStream( |
| 18 | 18 | llm: ILLM, |
| 19 | + abortController: AbortController, | |
| 19 | 20 | prompt: ChatMessage[] | string, |
| 20 | 21 | prediction: Prediction | undefined, |
| 21 | 22 | currentBuffer = "", |
| @@ -28,7 +29,7 @@ | ||
| 28 | 29 | // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries |
| 29 | 30 | |
| 30 | 31 | if (typeof prompt === "string") { |
| 31 | - const generator = llm.streamComplete(prompt, new AbortController().signal, { | |
| 32 | + const generator = llm.streamComplete(prompt, abortController.signal, { | |
| 32 | 33 | raw: true, |
| 33 | 34 | prediction: undefined, |
| 34 | 35 | reasoning: false, |
| @@ -50,6 +51,7 @@ | ||
| 50 | 51 | // // TODO - Prediction capabilities lost because of partial input |
| 51 | 52 | // yield* recursiveStream( |
| 52 | 53 | // llm, |
| 54 | + // abortController, | |
| 53 | 55 | // continuationPrompt, |
| 54 | 56 | // undefined, |
| 55 | 57 | // buffer, |
| @@ -60,7 +62,7 @@ | ||
| 60 | 62 | } |
| 61 | 63 | } |
| 62 | 64 | } else { |
| 63 | - const generator = llm.streamChat(prompt, new AbortController().signal, { | |
| 65 | + const generator = llm.streamChat(prompt, abortController.signal, { | |
| 64 | 66 | prediction, |
| 65 | 67 | reasoning: false, |
| 66 | 68 | }); |
| @@ -90,6 +92,7 @@ | ||
| 90 | 92 | // await generator.return(DUD_PROMPT_LOG); |
| 91 | 93 | // yield* recursiveStream( |
| 92 | 94 | // llm, |
| 95 | + // abortController, | |
| 93 | 96 | // continuationPrompt, |
| 94 | 97 | // undefined, |
| 95 | 98 | // buffer, |
modified core/edit/streamDiffLines.ts +6 −1
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | import { streamLines } from "../diff/util"; |
| 21 | 21 | import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; |
| 22 | 22 | import { gptEditPrompt } from "../llm/templates/edit"; |
| 23 | +import { StreamAbortManager } from "../util/abortManager"; | |
| 23 | 24 | import { findLast } from "../util/findLast"; |
| 24 | 25 | import { Telemetry } from "../util/posthog"; |
| 25 | 26 | import { recursiveStream } from "./recursiveStream"; |
| @@ -63,6 +64,7 @@ | ||
| 63 | 64 | highlighted, |
| 64 | 65 | suffix, |
| 65 | 66 | llm, |
| 67 | + abortControllerId, | |
| 66 | 68 | input, |
| 67 | 69 | language, |
| 68 | 70 | onlyOneInsertion, |
| @@ -73,12 +75,15 @@ | ||
| 73 | 75 | highlighted: string; |
| 74 | 76 | suffix: string; |
| 75 | 77 | llm: ILLM; |
| 78 | + abortControllerId: string; | |
| 76 | 79 | input: string; |
| 77 | 80 | language: string | undefined; |
| 78 | 81 | onlyOneInsertion: boolean; |
| 79 | 82 | overridePrompt: ChatMessage[] | undefined; |
| 80 | 83 | rulesToInclude: RuleWithSource[] | undefined; |
| 81 | 84 | }): AsyncGenerator<DiffLine> { |
| 85 | + const abortManager = StreamAbortManager.getInstance(); | |
| 86 | + const abortController = abortManager.get(abortControllerId); | |
| 82 | 87 | void Telemetry.capture( |
| 83 | 88 | "inlineEdit", |
| 84 | 89 | { |
| @@ -158,7 +163,7 @@ | ||
| 158 | 163 | content: highlighted, |
| 159 | 164 | }; |
| 160 | 165 | |
| 161 | - const completion = recursiveStream(llm, prompt, prediction); | |
| 166 | + const completion = recursiveStream(llm, abortController, prompt, prediction); | |
| 162 | 167 | |
| 163 | 168 | let lines = streamLines(completion); |
| 164 | 169 |
modified core/index.d.ts +1 −0
| @@ -1240,6 +1240,7 @@ | ||
| 1240 | 1240 | language: string | undefined; |
| 1241 | 1241 | modelTitle: string | undefined; |
| 1242 | 1242 | includeRulesInSystemMessage: boolean; |
| 1243 | + fileUri?: string; | |
| 1243 | 1244 | } |
| 1244 | 1245 | |
| 1245 | 1246 | export interface HighlightedCodePayload { |
modified core/llm/index.ts +3 −0
| @@ -382,6 +382,9 @@ | ||
| 382 | 382 | |
| 383 | 383 | // Error mapping to be more helpful |
| 384 | 384 | if (!resp.ok) { |
| 385 | + if (resp.status === 499) { | |
| 386 | + return resp; // client side cancellation | |
| 387 | + } | |
| 385 | 388 | let text = await resp.text(); |
| 386 | 389 | if (resp.status === 404 && !resp.url.includes("/v1")) { |
| 387 | 390 | 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"; | |
| 1 | 2 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | 3 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 3 | 4 | import { BaseLLM } from "../index.js"; |
| 4 | -import { streamSse } from "../stream.js"; | |
| 5 | 5 | |
| 6 | 6 | class Anthropic extends BaseLLM { |
| 7 | 7 | static providerName = "anthropic"; |
| @@ -213,6 +213,10 @@ | ||
| 213 | 213 | signal, |
| 214 | 214 | }); |
| 215 | 215 | |
| 216 | + if (response.status === 499) { | |
| 217 | + return; // Aborted by user | |
| 218 | + } | |
| 219 | + | |
| 216 | 220 | if (!response.ok) { |
| 217 | 221 | const json = await response.json(); |
| 218 | 222 | if (json.type === "error") { |
modified core/llm/llms/Asksage.ts +4 −8
| @@ -134,10 +134,8 @@ | ||
| 134 | 134 | body: JSON.stringify(args), |
| 135 | 135 | }); |
| 136 | 136 | |
| 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 | |
| 141 | 139 | } |
| 142 | 140 | |
| 143 | 141 | const data = await response.json(); |
| @@ -167,10 +165,8 @@ | ||
| 167 | 165 | signal, |
| 168 | 166 | }); |
| 169 | 167 | |
| 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 | |
| 174 | 170 | } |
| 175 | 171 | |
| 176 | 172 | const data = await response.json(); |
modified core/llm/llms/Bedrock.ts +1 −1
| @@ -306,7 +306,7 @@ | ||
| 306 | 306 | } |
| 307 | 307 | |
| 308 | 308 | const supportsTools = |
| 309 | - PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; | |
| 309 | + (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false; | |
| 310 | 310 | |
| 311 | 311 | let toolConfig = supportsTools && options.tools |
| 312 | 312 | ? { |
modified core/llm/llms/Cloudflare.ts +1 −1
| @@ -1,7 +1,7 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { ChatMessage, CompletionOptions } from "../../index.js"; |
| 2 | 3 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 3 | 4 | import { BaseLLM } from "../index.js"; |
| 4 | -import { streamSse } from "../stream.js"; | |
| 5 | 5 | |
| 6 | 6 | export default class Cloudflare extends BaseLLM { |
| 7 | 7 | static providerName = "cloudflare"; |
modified core/llm/llms/Cohere.ts +5 −1
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { streamJSON } from "@continuedev/fetch"; | |
| 1 | 2 | import { |
| 2 | 3 | ChatMessage, |
| 3 | 4 | Chunk, |
| @@ -6,7 +7,6 @@ | ||
| 6 | 7 | } from "../../index.js"; |
| 7 | 8 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 8 | 9 | import { BaseLLM } from "../index.js"; |
| 9 | -import { streamJSON } from "../stream.js"; | |
| 10 | 10 | |
| 11 | 11 | class Cohere extends BaseLLM { |
| 12 | 12 | static providerName = "cohere"; |
| @@ -84,6 +84,10 @@ | ||
| 84 | 84 | signal, |
| 85 | 85 | }); |
| 86 | 86 | |
| 87 | + if (resp.status === 499) { | |
| 88 | + return; // Aborted by user | |
| 89 | + } | |
| 90 | + | |
| 87 | 91 | if (options.stream === false) { |
| 88 | 92 | const data = await resp.json(); |
| 89 | 93 | yield { role: "assistant", content: data.text }; |
modified core/llm/llms/Deepseek.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | import { osModelsEditPrompt } from "../templates/edit.js"; |
| 4 | 4 | |
| 5 | 5 | import OpenAI from "./OpenAI.js"; |
modified core/llm/llms/Flowise.ts +7 −3
| @@ -132,12 +132,16 @@ | ||
| 132 | 132 | ): AsyncGenerator<ChatMessage> { |
| 133 | 133 | const requestBody = this._getRequestBody(messages, options); |
| 134 | 134 | const { socket, socketInfo } = await this._initializeSocket(); |
| 135 | - const request = this.fetch(this._getChatUrl(), { | |
| 135 | + const response = await this.fetch(this._getChatUrl(), { | |
| 136 | 136 | method: "POST", |
| 137 | 137 | headers: this._getHeaders(), |
| 138 | 138 | body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), |
| 139 | 139 | signal, |
| 140 | - }).then((res) => res.json()); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + if (response.status === 499) { | |
| 143 | + return; // Aborted by user | |
| 144 | + } | |
| 141 | 145 | |
| 142 | 146 | while (await socketInfo.hasNextToken()) { |
| 143 | 147 | yield { role: "assistant", content: socketInfo.getCurrentMessage() }; |
| @@ -145,7 +149,7 @@ | ||
| 145 | 149 | if (socketInfo.error) { |
| 146 | 150 | socket.disconnect(); |
| 147 | 151 | try { |
| 148 | - yield { role: "assistant", content: (await request).text }; | |
| 152 | + yield { role: "assistant", content: await response.text() }; | |
| 149 | 153 | } catch (error: any) { |
| 150 | 154 | yield { role: "assistant", content: (error as Error).message ?? error }; |
| 151 | 155 | } |
modified core/llm/llms/FreeTrial.ts +1 −1
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 1 | 2 | import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; |
| 2 | 3 | import { getHeaders } from "../../continueServer/stubs/headers.js"; |
| 3 | 4 | import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; |
| @@ -8,7 +9,6 @@ | ||
| 8 | 9 | LLMOptions, |
| 9 | 10 | } from "../../index.js"; |
| 10 | 11 | import { BaseLLM } from "../index.js"; |
| 11 | -import { streamResponse } from "../stream.js"; | |
| 12 | 12 | |
| 13 | 13 | class FreeTrial extends BaseLLM { |
| 14 | 14 | static providerName = "free-trial"; |
modified core/llm/llms/Gemini.ts +4 −1
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 1 | 2 | import { v4 as uuidv4 } from "uuid"; |
| 2 | 3 | import { |
| 3 | 4 | AssistantChatMessage, |
| @@ -10,7 +11,6 @@ | ||
| 10 | 11 | } from "../../index.js"; |
| 11 | 12 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 12 | 13 | import { BaseLLM } from "../index.js"; |
| 13 | -import { streamResponse } from "../stream.js"; | |
| 14 | 14 | import { |
| 15 | 15 | GeminiChatContent, |
| 16 | 16 | GeminiChatContentPart, |
| @@ -438,6 +438,9 @@ | ||
| 438 | 438 | body: JSON.stringify(body), |
| 439 | 439 | signal, |
| 440 | 440 | }); |
| 441 | + if (response.status === 499) { | |
| 442 | + return; // Aborted by user | |
| 443 | + } | |
| 441 | 444 | const data = await response.json(); |
| 442 | 445 | yield { role: "assistant", content: data.candidates[0].content }; |
| 443 | 446 | } |
modified core/llm/llms/HuggingFaceInferenceAPI.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions } from "../../index.js"; |
| 2 | 3 | import { BaseLLM } from "../index.js"; |
| 3 | -import { streamSse } from "../stream.js"; | |
| 4 | 4 | |
| 5 | 5 | class HuggingFaceInferenceAPI extends BaseLLM { |
| 6 | 6 | static providerName = "huggingface-inference-api"; |
modified core/llm/llms/HuggingFaceTGI.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | 3 | import { BaseLLM } from "../index.js"; |
| 3 | -import { streamSse } from "../stream.js"; | |
| 4 | 4 | |
| 5 | 5 | class HuggingFaceTGI extends BaseLLM { |
| 6 | 6 | private static MAX_STOP_TOKENS = 4; |
modified core/llm/llms/Inception.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | |
| 4 | 4 | import OpenAI from "./OpenAI.js"; |
| 5 | 5 |
modified core/llm/llms/LlamaCpp.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | 3 | import { BaseLLM } from "../index.js"; |
| 3 | -import { streamSse } from "../stream.js"; | |
| 4 | 4 | |
| 5 | 5 | class LlamaCpp extends BaseLLM { |
| 6 | 6 | static providerName = "llama.cpp"; |
modified core/llm/llms/Moonshot.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | import { osModelsEditPrompt } from "../templates/edit.js"; |
| 4 | 4 | |
| 5 | 5 | import OpenAI from "./OpenAI.js"; |
modified core/llm/llms/Ollama.ts +4 −1
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import { JSONSchema7, JSONSchema7Object } from "json-schema"; |
| 3 | 3 | import { v4 as uuidv4 } from "uuid"; |
| 4 | 4 | |
| 5 | +import { streamResponse } from "@continuedev/fetch"; | |
| 5 | 6 | import { |
| 6 | 7 | ChatMessage, |
| 7 | 8 | ChatMessageRole, |
| @@ -12,7 +13,6 @@ | ||
| 12 | 13 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 13 | 14 | import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; |
| 14 | 15 | import { BaseLLM } from "../index.js"; |
| 15 | -import { streamResponse } from "../stream.js"; | |
| 16 | 16 | |
| 17 | 17 | type OllamaChatMessage = { |
| 18 | 18 | role: ChatMessageRole; |
| @@ -457,6 +457,9 @@ | ||
| 457 | 457 | } |
| 458 | 458 | |
| 459 | 459 | if (chatOptions.stream === false) { |
| 460 | + if (response.status === 499) { | |
| 461 | + return; // Aborted by user | |
| 462 | + } | |
| 460 | 463 | const json = (await response.json()) as OllamaChatResponse; |
| 461 | 464 | yield convertChatMessage(json); |
| 462 | 465 | } else { |
modified core/llm/llms/OpenAI.ts +4 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | ChatCompletionMessageParam, |
| 4 | 4 | } from "openai/resources/index"; |
| 5 | 5 | |
| 6 | +import { streamSse } from "@continuedev/fetch"; | |
| 6 | 7 | import { |
| 7 | 8 | ChatMessage, |
| 8 | 9 | CompletionOptions, |
| @@ -16,7 +17,6 @@ | ||
| 16 | 17 | LlmApiRequestType, |
| 17 | 18 | toChatBody, |
| 18 | 19 | } from "../openaiTypeConverters.js"; |
| 19 | -import { streamSse } from "../stream.js"; | |
| 20 | 20 | |
| 21 | 21 | const NON_CHAT_MODELS = [ |
| 22 | 22 | "text-davinci-002", |
| @@ -352,6 +352,9 @@ | ||
| 352 | 352 | |
| 353 | 353 | // Handle non-streaming response |
| 354 | 354 | if (body.stream === false) { |
| 355 | + if (response.status === 499) { | |
| 356 | + return; // Aborted by user | |
| 357 | + } | |
| 355 | 358 | const data = await response.json(); |
| 356 | 359 | yield data.choices[0].message; |
| 357 | 360 | return; |
modified core/llm/llms/SiliconFlow.ts +2 −2
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { Chunk, CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | import { osModelsEditPrompt } from "../templates/edit.js"; |
| 4 | 4 | |
| 5 | 5 | import OpenAI from "./OpenAI.js"; |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | console.warn("[SiliconFlow] rerank: query is empty"); |
| 59 | 59 | return []; |
| 60 | 60 | } |
| 61 | - | |
| 61 | + | |
| 62 | 62 | if (!chunks || chunks.length === 0) { |
| 63 | 63 | console.warn("[SiliconFlow] rerank: chunks is empty"); |
| 64 | 64 | return []; |
modified core/llm/llms/VertexAI.ts +23 −5
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | import { GoogleAuth } from "google-auth-library"; |
| 2 | 2 | |
| 3 | +import { streamResponse, streamSse } from "@continuedev/fetch"; | |
| 3 | 4 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 4 | 5 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 5 | 6 | import { BaseLLM } from "../index.js"; |
| 6 | -import { streamResponse, streamSse } from "../stream.js"; | |
| 7 | 7 | |
| 8 | 8 | import Anthropic from "./Anthropic.js"; |
| 9 | 9 | import Gemini from "./Gemini.js"; |
| @@ -95,6 +95,7 @@ | ||
| 95 | 95 | protected async *StreamChatAnthropic( |
| 96 | 96 | messages: ChatMessage[], |
| 97 | 97 | options: CompletionOptions, |
| 98 | + signal: AbortSignal, | |
| 98 | 99 | ): AsyncGenerator<ChatMessage> { |
| 99 | 100 | const systemMessage = stripImages( |
| 100 | 101 | messages.filter((m) => m.role === "system")[0]?.content ?? "", |
| @@ -128,8 +129,13 @@ | ||
| 128 | 129 | ] |
| 129 | 130 | : systemMessage, |
| 130 | 131 | }), |
| 132 | + signal, | |
| 131 | 133 | }); |
| 132 | 134 | |
| 135 | + if (response.status === 499) { | |
| 136 | + return; // Aborted by user | |
| 137 | + } | |
| 138 | + | |
| 133 | 139 | if (options.stream === false) { |
| 134 | 140 | const data = await response.json(); |
| 135 | 141 | yield { role: "assistant", content: data.content[0].text }; |
| @@ -150,6 +156,7 @@ | ||
| 150 | 156 | private async *streamChatGemini( |
| 151 | 157 | messages: ChatMessage[], |
| 152 | 158 | options: CompletionOptions, |
| 159 | + signal: AbortSignal, | |
| 153 | 160 | ): AsyncGenerator<ChatMessage> { |
| 154 | 161 | const apiURL = new URL( |
| 155 | 162 | `publishers/google/models/${options.model}:streamGenerateContent`, |
| @@ -160,6 +167,7 @@ | ||
| 160 | 167 | const response = await this.fetch(apiURL, { |
| 161 | 168 | method: "POST", |
| 162 | 169 | body: JSON.stringify(body), |
| 170 | + signal, | |
| 163 | 171 | }); |
| 164 | 172 | for await (const message of this.geminiInstance.processGeminiResponse( |
| 165 | 173 | streamResponse(response), |
| @@ -171,6 +179,7 @@ | ||
| 171 | 179 | private async *streamChatBison( |
| 172 | 180 | messages: ChatMessage[], |
| 173 | 181 | options: CompletionOptions, |
| 182 | + signal: AbortSignal, | |
| 174 | 183 | ): AsyncGenerator<ChatMessage> { |
| 175 | 184 | const instances = messages.map((message) => ({ prompt: message.content })); |
| 176 | 185 | |
| @@ -193,7 +202,11 @@ | ||
| 193 | 202 | const response = await this.fetch(apiURL, { |
| 194 | 203 | method: "POST", |
| 195 | 204 | body: JSON.stringify(body), |
| 205 | + signal, | |
| 196 | 206 | }); |
| 207 | + if (response.status === 499) { | |
| 208 | + return; // Aborted by user | |
| 209 | + } | |
| 197 | 210 | const data = await response.json(); |
| 198 | 211 | yield { role: "assistant", content: data.predictions[0].content }; |
| 199 | 212 | } |
| @@ -203,6 +216,7 @@ | ||
| 203 | 216 | protected async *StreamChatMistral( |
| 204 | 217 | messages: ChatMessage[], |
| 205 | 218 | options: CompletionOptions, |
| 219 | + signal: AbortSignal, | |
| 206 | 220 | ): AsyncGenerator<ChatMessage> { |
| 207 | 221 | const apiBase = this.apiBase!; |
| 208 | 222 | const apiURL = new URL( |
| @@ -228,6 +242,7 @@ | ||
| 228 | 242 | const response = await this.fetch(apiURL, { |
| 229 | 243 | method: "POST", |
| 230 | 244 | body: JSON.stringify(body), |
| 245 | + signal, | |
| 231 | 246 | }); |
| 232 | 247 | |
| 233 | 248 | for await (const chunk of streamSse(response)) { |
| @@ -304,6 +319,9 @@ | ||
| 304 | 319 | }), |
| 305 | 320 | signal, |
| 306 | 321 | }); |
| 322 | + if (resp.status === 499) { | |
| 323 | + return; // Aborted by user | |
| 324 | + } | |
| 307 | 325 | // Streaming is not supported by code-gecko |
| 308 | 326 | // TODO: convert to non-streaming fim method when one exist in continue. |
| 309 | 327 | yield (await resp.json()).predictions[0].content; |
| @@ -323,14 +341,14 @@ | ||
| 323 | 341 | ? this.geminiInstance.removeSystemMessage(messages) |
| 324 | 342 | : messages; |
| 325 | 343 | if (this.vertexProvider === "gemini") { |
| 326 | - yield* this.streamChatGemini(convertedMsgs, options); | |
| 344 | + yield* this.streamChatGemini(convertedMsgs, options, signal); | |
| 327 | 345 | } else if (this.vertexProvider === "mistral") { |
| 328 | - yield* this.StreamChatMistral(messages, options); | |
| 346 | + yield* this.StreamChatMistral(messages, options, signal); | |
| 329 | 347 | } else if (this.vertexProvider === "anthropic") { |
| 330 | - yield* this.StreamChatAnthropic(messages, options); | |
| 348 | + yield* this.StreamChatAnthropic(messages, options, signal); | |
| 331 | 349 | } else { |
| 332 | 350 | if (options.model.includes("bison")) { |
| 333 | - yield* this.streamChatBison(convertedMsgs, options); | |
| 351 | + yield* this.streamChatBison(convertedMsgs, options, signal); | |
| 334 | 352 | } else { |
| 335 | 353 | throw new Error(`Unsupported model: ${options.model}`); |
| 336 | 354 | } |
modified core/llm/llms/WatsonX.ts +37 −53
| @@ -1,15 +1,12 @@ | ||
| 1 | +import { streamResponse, streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { |
| 2 | 3 | ChatMessage, |
| 3 | 4 | Chunk, |
| 4 | 5 | CompletionOptions, |
| 5 | 6 | LLMOptions, |
| 6 | 7 | } from "../../index.js"; |
| 7 | -import { | |
| 8 | - fromChatCompletionChunk, | |
| 9 | -} from "../openaiTypeConverters.js"; | |
| 10 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 11 | 8 | import { BaseLLM } from "../index.js"; |
| 12 | -import { streamResponse, streamSse } from "../stream.js"; | |
| 9 | +import { fromChatCompletionChunk } from "../openaiTypeConverters.js"; | |
| 13 | 10 | |
| 14 | 11 | let watsonxToken = { |
| 15 | 12 | expiration: 0, |
| @@ -86,7 +83,7 @@ | ||
| 86 | 83 | } |
| 87 | 84 | |
| 88 | 85 | _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}`; | |
| 90 | 87 | } |
| 91 | 88 | |
| 92 | 89 | static providerName = "watsonx"; |
| @@ -182,7 +179,6 @@ | ||
| 182 | 179 | signal: AbortSignal, |
| 183 | 180 | options: CompletionOptions, |
| 184 | 181 | ): AsyncGenerator<string> { |
| 185 | - | |
| 186 | 182 | await this.updateWatsonxToken(); |
| 187 | 183 | |
| 188 | 184 | const stopSequences = options.stop?.slice(0, 6) ?? []; |
| @@ -214,44 +210,38 @@ | ||
| 214 | 210 | payload.project_id = this.projectId; |
| 215 | 211 | } |
| 216 | 212 | |
| 217 | - var response = await this.fetch(url, { | |
| 213 | + const response = await this.fetch(url, { | |
| 218 | 214 | method: "POST", |
| 219 | 215 | headers: headers, |
| 220 | 216 | body: JSON.stringify(payload), |
| 221 | 217 | signal, |
| 222 | 218 | }); |
| 223 | 219 | |
| 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}`); | |
| 251 | 230 | } |
| 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; | |
| 255 | 245 | } |
| 256 | 246 | } |
| 257 | 247 | |
| @@ -267,7 +257,7 @@ | ||
| 267 | 257 | const headers = this._getHeaders(); |
| 268 | 258 | |
| 269 | 259 | const payload: any = { |
| 270 | - messages: messages, | |
| 260 | + messages: messages, | |
| 271 | 261 | max_tokens: options.maxTokens ?? 1024, |
| 272 | 262 | stop: stopSequences, |
| 273 | 263 | frequency_penalty: options.frequencyPenalty || 1, |
| @@ -281,36 +271,30 @@ | ||
| 281 | 271 | |
| 282 | 272 | if (!!options.temperature) { |
| 283 | 273 | payload.temperature = options.temperature; |
| 284 | - } | |
| 274 | + } | |
| 285 | 275 | if (!!options.topP) { |
| 286 | 276 | payload.top_p = options.topP; |
| 287 | 277 | } |
| 288 | 278 | if (!!options.tools) { |
| 289 | 279 | payload.tools = options.tools; |
| 290 | 280 | if (options.toolChoice) { |
| 291 | - payload.tool_choice = options.toolChoice; | |
| 281 | + payload.tool_choice = options.toolChoice; | |
| 292 | 282 | } else { |
| 293 | - payload.tool_choice_option = "auto"; | |
| 283 | + payload.tool_choice_option = "auto"; | |
| 294 | 284 | } |
| 295 | 285 | } |
| 296 | 286 | |
| 297 | - var response = await this.fetch(url, { | |
| 287 | + const response = await this.fetch(url, { | |
| 298 | 288 | method: "POST", |
| 299 | 289 | headers: headers, |
| 300 | 290 | body: JSON.stringify(payload), |
| 301 | 291 | signal, |
| 302 | 292 | }); |
| 303 | 293 | |
| 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; | |
| 314 | 298 | } |
| 315 | 299 | } |
| 316 | 300 | } |
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
| @@ -27,8 +27,12 @@ | ||
| 27 | 27 | // to call whatever LLM API is chosen |
| 28 | 28 | private actualApiBase?: string; |
| 29 | 29 | |
| 30 | + // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions | |
| 31 | + private configEnv?: Record<string, any>; | |
| 32 | + | |
| 30 | 33 | constructor(options: LLMOptions) { |
| 31 | 34 | super(options); |
| 35 | + this.configEnv = options.env; | |
| 32 | 36 | this.actualApiBase = options.apiBase; |
| 33 | 37 | this.apiKeyLocation = options.apiKeyLocation; |
| 34 | 38 | this.orgScopeId = options.orgScopeId; |
| @@ -48,6 +52,7 @@ | ||
| 48 | 52 | apiKeyLocation: this.apiKeyLocation, |
| 49 | 53 | apiBase: this.actualApiBase, |
| 50 | 54 | orgScopeId: this.orgScopeId ?? null, |
| 55 | + env: this.configEnv, | |
| 51 | 56 | }; |
| 52 | 57 | return { |
| 53 | 58 | 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( | |
| 2 | 2 | nodeReadable: NodeJS.ReadableStream, |
| 3 | 3 | ): AsyncGenerator<Uint8Array> { |
| 4 | 4 | for await (const chunk of nodeReadable) { |
modified core/llm/streamChat.ts +27 −35
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | export async function* llmStreamChat( |
| 10 | 10 | configHandler: ConfigHandler, |
| 11 | - abortedMessageIds: Set<string>, | |
| 11 | + abortController: AbortController, | |
| 12 | 12 | msg: Message<ToCoreProtocol["llm/streamChat"][0]>, |
| 13 | 13 | ide: IDE, |
| 14 | 14 | messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>, |
| @@ -75,52 +75,44 @@ | ||
| 75 | 75 | selectedCode, |
| 76 | 76 | config, |
| 77 | 77 | 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 | + ), | |
| 79 | 86 | completionOptions, |
| 80 | 87 | }); |
| 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; | |
| 103 | 93 | } |
| 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 | + }; | |
| 106 | 99 | } |
| 107 | - | |
| 108 | - return next.value; | |
| 109 | - } catch (e) { | |
| 110 | - throw e; | |
| 111 | - } finally { | |
| 112 | - clearInterval(checkActiveInterval); | |
| 100 | + next = await gen.next(); | |
| 113 | 101 | } |
| 102 | + if (!next.done) { | |
| 103 | + throw new Error("Will never happen"); | |
| 104 | + } | |
| 105 | + | |
| 106 | + return next.value; | |
| 114 | 107 | } else { |
| 115 | 108 | const gen = model.streamChat( |
| 116 | 109 | messages, |
| 117 | - new AbortController().signal, | |
| 110 | + abortController.signal, | |
| 118 | 111 | completionOptions, |
| 119 | 112 | ); |
| 120 | 113 | let next = await gen.next(); |
| 121 | 114 | while (!next.done) { |
| 122 | - if (abortedMessageIds.has(msg.messageId)) { | |
| 123 | - abortedMessageIds.delete(msg.messageId); | |
| 115 | + if (abortController.signal.aborted) { | |
| 124 | 116 | next = await gen.return(errorPromptLog); |
| 125 | 117 | break; |
| 126 | 118 | } |
modified core/llm/toolSupport.ts +3 −2
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | "claude-3.5", |
| 18 | 18 | "claude-3-7", |
| 19 | 19 | "claude-3.7", |
| 20 | + "claude-sonnet-4", | |
| 20 | 21 | "gpt-4", |
| 21 | 22 | "o3", |
| 22 | 23 | "gemini", |
| @@ -24,7 +25,7 @@ | ||
| 24 | 25 | }, |
| 25 | 26 | anthropic: (model) => { |
| 26 | 27 | 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) => | |
| 28 | 29 | model.toLowerCase().startsWith(part), |
| 29 | 30 | ) |
| 30 | 31 | ) { |
| @@ -76,7 +77,7 @@ | ||
| 76 | 77 | // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 |
| 77 | 78 | if ( |
| 78 | 79 | 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) => | |
| 80 | 81 | model.toLowerCase().includes(part), |
| 81 | 82 | ) |
| 82 | 83 | ) { |
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 @@ | ||
| 49 | 49 | "@aws-sdk/credential-providers": "^3.778.0", |
| 50 | 50 | "@continuedev/config-types": "^1.0.13", |
| 51 | 51 | "@continuedev/config-yaml": "file:../packages/config-yaml", |
| 52 | - "@continuedev/fetch": "^1.0.6", | |
| 52 | + "@continuedev/fetch": "^1.0.10", | |
| 53 | 53 | "@continuedev/llm-info": "^1.0.8", |
| 54 | - "@continuedev/openai-adapters": "^1.0.19", | |
| 54 | + "@continuedev/openai-adapters": "^1.0.25", | |
| 55 | 55 | "@modelcontextprotocol/sdk": "^1.5.0", |
| 56 | 56 | "@mozilla/readability": "^0.5.0", |
| 57 | 57 | "@octokit/rest": "^20.1.1", |
modified core/protocol/core.ts +1 −0
| @@ -46,6 +46,7 @@ | ||
| 46 | 46 | // Special |
| 47 | 47 | ping: [string, string]; |
| 48 | 48 | abort: [undefined, void]; |
| 49 | + cancelApply: [undefined, void]; | |
| 49 | 50 | |
| 50 | 51 | // History |
| 51 | 52 | "history/list": [ListHistoryOptions, SessionMetadata[]]; |
modified core/tools/definitions/createRuleBlock.ts +4 −0
| @@ -28,6 +28,10 @@ | ||
| 28 | 28 | description: |
| 29 | 29 | "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", |
| 30 | 30 | }, |
| 31 | + description: { | |
| 32 | + type: "string", | |
| 33 | + description: "Short description of the rule", | |
| 34 | + }, | |
| 31 | 35 | globs: { |
| 32 | 36 | type: "string", |
| 33 | 37 | 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"; | |
| 2 | 2 | import { createRuleBlockImpl } from "./createRuleBlock"; |
| 3 | 3 | |
| 4 | 4 | // Mock the extras parameter with necessary functions |
| @@ -17,33 +17,6 @@ | ||
| 17 | 17 | jest.clearAllMocks(); |
| 18 | 18 | }); |
| 19 | 19 | |
| 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 | - | |
| 47 | 20 | it("should create a rule with glob pattern", async () => { |
| 48 | 21 | const args = { |
| 49 | 22 | name: "TypeScript Rule", |
| @@ -53,14 +26,16 @@ | ||
| 53 | 26 | |
| 54 | 27 | await createRuleBlockImpl(args, mockExtras as any); |
| 55 | 28 | |
| 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({ | |
| 62 | 34 | globs: "**/*.{ts,tsx}", |
| 63 | 35 | }); |
| 36 | + | |
| 37 | + expect(markdown).toContain("# TypeScript Rule"); | |
| 38 | + expect(markdown).toContain("Use interfaces for object shapes"); | |
| 64 | 39 | }); |
| 65 | 40 | |
| 66 | 41 | it("should create a filename based on sanitized rule name", async () => { |
| @@ -71,8 +46,51 @@ | ||
| 71 | 46 | |
| 72 | 47 | await createRuleBlockImpl(args, mockExtras as any); |
| 73 | 48 | |
| 74 | - // Check that the filename is sanitized | |
| 75 | 49 | 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"); | |
| 77 | 95 | }); |
| 78 | 96 | }); |
modified core/tools/implementations/createRuleBlock.ts +16 −36
| @@ -1,4 +1,3 @@ | ||
| 1 | -import { ConfigYaml } from "@continuedev/config-yaml"; | |
| 2 | 1 | import * as YAML from "yaml"; |
| 3 | 2 | import { ToolImpl } from "."; |
| 4 | 3 | import { joinPathsToUri } from "../../util/uri"; |
| @@ -6,8 +5,8 @@ | ||
| 6 | 5 | export interface CreateRuleBlockArgs { |
| 7 | 6 | name: string; |
| 8 | 7 | rule: string; |
| 8 | + description: string; | |
| 9 | 9 | globs?: string; |
| 10 | - format?: "yaml" | "markdown"; // Add format option with yaml as default | |
| 11 | 10 | } |
| 12 | 11 | |
| 13 | 12 | export const createRuleBlockImpl: ToolImpl = async ( |
| @@ -20,26 +19,19 @@ | ||
| 20 | 19 | .replace(/[^a-z0-9\s-]/g, "") |
| 21 | 20 | .replace(/\s+/g, "-"); |
| 22 | 21 | |
| 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 = `--- | |
| 43 | 35 | ${frontmatterYaml} |
| 44 | 36 | --- |
| 45 | 37 | |
| @@ -47,18 +39,6 @@ | ||
| 47 | 39 | |
| 48 | 40 | ${args.rule} |
| 49 | 41 | `; |
| 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 | - | |
| 62 | 42 | const [localContinueDir] = await extras.ide.getWorkspaceDirs(); |
| 63 | 43 | const rulesDirUri = joinPathsToUri( |
| 64 | 44 | localContinueDir, |
| @@ -73,12 +53,12 @@ | ||
| 73 | 53 | return [ |
| 74 | 54 | { |
| 75 | 55 | name: "New Rule Block", |
| 76 | - description: "", // No description throws an error in the GUI | |
| 56 | + description: args.description || "", | |
| 77 | 57 | uri: { |
| 78 | 58 | type: "file", |
| 79 | 59 | value: rulesDirUri, |
| 80 | 60 | }, |
| 81 | - content: `Rule created successfully in ${format} format`, | |
| 61 | + content: `Rule created successfully`, | |
| 82 | 62 | }, |
| 83 | 63 | ]; |
| 84 | 64 | }; |
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 @@ | ||
| 188 | 188 | not currently used. |
| 189 | 189 | - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on |
| 190 | 190 | 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. | |
| 191 | 192 | - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are |
| 192 | 193 | `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [ |
| 193 | 194 | `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [ |
| @@ -406,7 +407,7 @@ | ||
| 406 | 407 | - `destination` (**required**): The destination/endpoint that will receive the data. Can be: |
| 407 | 408 | - an HTTP endpoint that will receive a POST request with a JSON blob |
| 408 | 409 | - 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` | |
| 410 | 411 | - `events`: an array of event names to include. Defaults to all events if not specified. |
| 411 | 412 | - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file |
| 412 | 413 | contents, prompts, and completions. Defaults to `all` |
modified docs/docusaurus.config.js +3 −1
| @@ -66,7 +66,9 @@ | ||
| 66 | 66 | ], |
| 67 | 67 | |
| 68 | 68 | 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 | + }, | |
| 70 | 72 | ], |
| 71 | 73 | |
| 72 | 74 | 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 @@ | ||
| 108 | 108 | ) |
| 109 | 109 | continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex) |
| 110 | 110 | continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex) |
| 111 | - | |
| 111 | + continuePluginService.coreMessenger?.request("cancelApply", null, null) {} | |
| 112 | 112 | cleanUpFile(file) |
| 113 | 113 | } |
| 114 | 114 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +2 −2
| @@ -111,7 +111,8 @@ | ||
| 111 | 111 | suffix = suffix, |
| 112 | 112 | language = virtualFile?.fileType?.name, |
| 113 | 113 | modelTitle = modelTitle, |
| 114 | - includeRulesInSystemMessage = includeRulesInSystemMessage | |
| 114 | + includeRulesInSystemMessage = includeRulesInSystemMessage, | |
| 115 | + fileUri = virtualFile?.url | |
| 115 | 116 | ), |
| 116 | 117 | null |
| 117 | 118 | ) { response -> |
| @@ -289,7 +290,6 @@ | ||
| 289 | 290 | } |
| 290 | 291 | } |
| 291 | 292 | |
| 292 | - | |
| 293 | 293 | private fun handleFinishedResponse() { |
| 294 | 294 | ApplicationManager.getApplication().invokeLater { |
| 295 | 295 | // 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 @@ | ||
| 244 | 244 | val input: String, |
| 245 | 245 | val language: String?, |
| 246 | 246 | val modelTitle: String?, |
| 247 | - val includeRulesInSystemMessage: Boolean | |
| 247 | + val includeRulesInSystemMessage: Boolean, | |
| 248 | + val fileUri: String? | |
| 248 | 249 | ) |
| 249 | 250 | |
| 250 | 251 | 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 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.38", | |
| 5 | + "version": "1.1.39", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
| @@ -631,7 +631,7 @@ | ||
| 631 | 631 | "devDependencies": { |
| 632 | 632 | "@biomejs/biome": "1.6.4", |
| 633 | 633 | "@nestjs/common": "^11.0.16", |
| 634 | - "@openapitools/openapi-generator-cli": "^2.5.2", | |
| 634 | + "@openapitools/openapi-generator-cli": "^2.20.0", | |
| 635 | 635 | "@types/chai": "^5.0.1", |
| 636 | 636 | "@types/cors": "^2.8.17", |
| 637 | 637 | "@types/express": "^4.17.21", |
| @@ -661,7 +661,7 @@ | ||
| 661 | 661 | }, |
| 662 | 662 | "dependencies": { |
| 663 | 663 | "@continuedev/config-types": "^1.0.14", |
| 664 | - "@continuedev/fetch": "^1.0.3", | |
| 664 | + "@continuedev/fetch": "^1.0.10", | |
| 665 | 665 | "@electron/rebuild": "^3.2.10", |
| 666 | 666 | "@reduxjs/toolkit": "^1.9.3", |
| 667 | 667 | "@types/node-fetch": "^2.6.11", |
modified extensions/vscode/src/commands.ts +14 −4
| @@ -97,6 +97,7 @@ | ||
| 97 | 97 | action: "accept" | "reject", |
| 98 | 98 | sidebar: ContinueGUIWebviewViewProvider, |
| 99 | 99 | ide: VsCodeIde, |
| 100 | + core: Core, | |
| 100 | 101 | verticalDiffManager: VerticalDiffManager, |
| 101 | 102 | newFileUri?: string, |
| 102 | 103 | streamId?: string, |
| @@ -121,6 +122,9 @@ | ||
| 121 | 122 | |
| 122 | 123 | // Clear vertical diffs depending on action |
| 123 | 124 | verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); |
| 125 | + if (action === "reject") { | |
| 126 | + core.invoke("cancelApply", undefined); | |
| 127 | + } | |
| 124 | 128 | |
| 125 | 129 | if (streamId) { |
| 126 | 130 | const fileContent = await ide.readFile(newOrCurrentUri); |
| @@ -236,18 +240,20 @@ | ||
| 236 | 240 | "accept", |
| 237 | 241 | sidebar, |
| 238 | 242 | ide, |
| 243 | + core, | |
| 239 | 244 | verticalDiffManager, |
| 240 | 245 | newFileUri, |
| 241 | 246 | streamId, |
| 242 | 247 | ), |
| 243 | 248 | |
| 244 | - "continue.rejectDiff": async (newFilepath?: string, streamId?: string) => | |
| 249 | + "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => | |
| 245 | 250 | processDiff( |
| 246 | 251 | "reject", |
| 247 | 252 | sidebar, |
| 248 | 253 | ide, |
| 254 | + core, | |
| 249 | 255 | verticalDiffManager, |
| 250 | - newFilepath, | |
| 256 | + newFileUri, | |
| 251 | 257 | streamId, |
| 252 | 258 | ), |
| 253 | 259 | "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => { |
| @@ -573,11 +579,15 @@ | ||
| 573 | 579 | await addEntireFileToContext( |
| 574 | 580 | vscode.Uri.parse(fileUri), |
| 575 | 581 | sidebar.webviewProtocol, |
| 576 | - ide.ideUtils | |
| 582 | + ide.ideUtils, | |
| 577 | 583 | ); |
| 578 | 584 | } |
| 579 | 585 | } else { |
| 580 | - await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils); | |
| 586 | + await addEntireFileToContext( | |
| 587 | + uri, | |
| 588 | + sidebar.webviewProtocol, | |
| 589 | + ide.ideUtils, | |
| 590 | + ); | |
| 581 | 591 | } |
| 582 | 592 | } |
| 583 | 593 | }, |
modified extensions/vscode/src/diff/vertical/manager.ts +3 −4
| @@ -1,5 +1,4 @@ | ||
| 1 | 1 | import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core"; |
| 2 | -import { ConfigHandler } from "core/config/ConfigHandler"; | |
| 3 | 2 | import { streamDiffLines } from "core/edit/streamDiffLines"; |
| 4 | 3 | import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; |
| 5 | 4 | import { getMarkdownLanguageTagForFile } from "core/util"; |
| @@ -31,7 +30,6 @@ | ||
| 31 | 30 | logDiffs: DiffLine[] | undefined; |
| 32 | 31 | |
| 33 | 32 | constructor( |
| 34 | - private readonly configHandler: ConfigHandler, | |
| 35 | 33 | private readonly webviewProtocol: VsCodeWebviewProtocol, |
| 36 | 34 | private readonly editDecorationManager: EditDecorationManager, |
| 37 | 35 | ) { |
| @@ -43,12 +41,12 @@ | ||
| 43 | 41 | startLine: number, |
| 44 | 42 | endLine: number, |
| 45 | 43 | options: VerticalDiffHandlerOptions, |
| 46 | - ) { | |
| 44 | + ): VerticalDiffHandler | undefined { | |
| 47 | 45 | if (this.fileUriToHandler.has(fileUri)) { |
| 48 | 46 | this.fileUriToHandler.get(fileUri)?.clear(false); |
| 49 | 47 | this.fileUriToHandler.delete(fileUri); |
| 50 | 48 | } |
| 51 | - const editor = vscode.window.activeTextEditor; // TODO | |
| 49 | + const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files | |
| 52 | 50 | if (editor && URI.equal(editor.document.uri.toString(), fileUri)) { |
| 53 | 51 | const handler = new VerticalDiffHandler( |
| 54 | 52 | startLine, |
| @@ -453,6 +451,7 @@ | ||
| 453 | 451 | language: getMarkdownLanguageTagForFile(fileUri), |
| 454 | 452 | onlyOneInsertion: !!onlyOneInsertion, |
| 455 | 453 | overridePrompt, |
| 454 | + abortControllerId: fileUri, | |
| 456 | 455 | }); |
| 457 | 456 | |
| 458 | 457 | for await (const line of stream) { |
modified extensions/vscode/src/extension/VsCodeExtension.ts +0 −1
| @@ -130,7 +130,6 @@ | ||
| 130 | 130 | this.configHandler.loadConfig(); |
| 131 | 131 | |
| 132 | 132 | this.verticalDiffManager = new VerticalDiffManager( |
| 133 | - this.configHandler, | |
| 134 | 133 | this.sidebar.webviewProtocol, |
| 135 | 134 | this.editDecorationManager, |
| 136 | 135 | ); |
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 @@ | ||
| 1 | 1 | import { XMarkIcon } from "@heroicons/react/24/outline"; |
| 2 | -import { useCallback, useEffect } from "react"; | |
| 2 | +import React, { useCallback, useEffect } from "react"; | |
| 3 | 3 | import { useDispatch, useSelector } from "react-redux"; |
| 4 | 4 | import styled from "styled-components"; |
| 5 | 5 | import { defaultBorderRadius } from ".."; |
| @@ -35,6 +35,8 @@ | ||
| 35 | 35 | border-bottom: none; |
| 36 | 36 | position: relative; |
| 37 | 37 | margin-top: 2px; |
| 38 | + max-height: 100px; | |
| 39 | + overflow: auto; | |
| 38 | 40 | |
| 39 | 41 | /* Hide scrollbar but keep functionality */ |
| 40 | 42 | scrollbar-width: none; |
| @@ -125,7 +127,7 @@ | ||
| 125 | 127 | background-color: ${tabBackgroundVar}; |
| 126 | 128 | `; |
| 127 | 129 | |
| 128 | -export function TabBar() { | |
| 130 | +export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => { | |
| 129 | 131 | const dispatch = useDispatch<AppDispatch>(); |
| 130 | 132 | const currentSessionId = useSelector((state: RootState) => state.session.id); |
| 131 | 133 | const currentSessionTitle = useSelector( |
| @@ -141,7 +143,6 @@ | ||
| 141 | 143 | return Date.now().toString(36) + Math.random().toString(36).substring(2); |
| 142 | 144 | }, []); |
| 143 | 145 | |
| 144 | - // Handle session changes | |
| 145 | 146 | useEffect(() => { |
| 146 | 147 | if (!currentSessionId) return; |
| 147 | 148 | |
| @@ -224,10 +225,13 @@ | ||
| 224 | 225 | } |
| 225 | 226 | }; |
| 226 | 227 | |
| 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 | + > | |
| 231 | 235 | {tabs.map((tab) => ( |
| 232 | 236 | <Tab |
| 233 | 237 | key={tab.id} |
| @@ -253,4 +257,4 @@ | ||
| 253 | 257 | </TabBarSpace> |
| 254 | 258 | </TabBarContainer> |
| 255 | 259 | ); |
| 256 | -} | |
| 260 | +}); |
modified gui/src/components/find/FindWidget.tsx +126 −292
| @@ -12,36 +12,25 @@ | ||
| 12 | 12 | useState, |
| 13 | 13 | } from "react"; |
| 14 | 14 | import { HeaderButton, Input } from ".."; |
| 15 | -import { useAppSelector } from "../../redux/hooks"; | |
| 16 | 15 | 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; | |
| 37 | 26 | isCurrent: boolean; |
| 38 | 27 | } |
| 39 | 28 | |
| 40 | 29 | const HighlightOverlay = (props: HighlightOverlayProps) => { |
| 41 | - const { isCurrent, top, left, width, height } = props; | |
| 30 | + const { top, left, width, height } = props.rectangle; | |
| 42 | 31 | return ( |
| 43 | 32 | <div |
| 44 | - className={isCurrent ? "bg-findMatch-selected/50" : "bg-findMatch/50"} | |
| 33 | + className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"} | |
| 45 | 34 | key={`highlight-${top}-${left}`} |
| 46 | 35 | style={{ |
| 47 | 36 | position: "absolute", |
| @@ -56,6 +45,8 @@ | ||
| 56 | 45 | ); |
| 57 | 46 | }; |
| 58 | 47 | |
| 48 | +type ScrollToMatchOption = "closest" | "first" | "none"; | |
| 49 | + | |
| 59 | 50 | /* |
| 60 | 51 | useFindWidget takes a container ref and returns |
| 61 | 52 | 1. A widget that can be placed anywhere to search the contents of that container |
| @@ -64,18 +55,22 @@ | ||
| 64 | 55 | |
| 65 | 56 | Container must have relative positioning |
| 66 | 57 | */ |
| 67 | -export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => { | |
| 58 | +export const useFindWidget = ( | |
| 59 | + searchRef: RefObject<HTMLDivElement>, | |
| 60 | + headerRef: RefObject<HTMLDivElement>, | |
| 61 | + disabled: boolean, | |
| 62 | +) => { | |
| 68 | 63 | // Search input, debounced |
| 69 | - const [input, setInput] = useState<string>(""); | |
| 70 | - const debouncedInput = useRef<string>(""); | |
| 71 | 64 | const inputRef = useRef<HTMLInputElement>(null); |
| 65 | + const [currentValue, setCurrentValue] = useState<string>(""); | |
| 66 | + const searchTerm = useDebounceValue(currentValue, 300); | |
| 72 | 67 | |
| 73 | 68 | // Widget open/closed state |
| 74 | 69 | const [open, setOpen] = useState<boolean>(false); |
| 75 | 70 | const openWidget = useCallback(() => { |
| 76 | 71 | setOpen(true); |
| 77 | 72 | inputRef?.current?.select(); |
| 78 | - }, [setOpen, inputRef]); | |
| 73 | + }, [inputRef]); | |
| 79 | 74 | |
| 80 | 75 | // Search settings and results |
| 81 | 76 | const [caseSensitive, setCaseSensitive] = useState<boolean>(false); |
| @@ -97,7 +92,7 @@ | ||
| 97 | 92 | behavior: "smooth", |
| 98 | 93 | }); |
| 99 | 94 | }, |
| 100 | - [searchRef.current], | |
| 95 | + [searchRef], | |
| 101 | 96 | ); |
| 102 | 97 | |
| 103 | 98 | const nextMatch = useCallback(() => { |
| @@ -143,327 +138,166 @@ | ||
| 143 | 138 | }, [inputRef, matches, nextMatch]); |
| 144 | 139 | |
| 145 | 140 | // 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]); | |
| 169 | 147 | |
| 170 | 148 | // Main function for finding matches and generating highlight overlays |
| 171 | 149 | 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, | |
| 190 | 154 | { |
| 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, | |
| 205 | 158 | }, |
| 206 | 159 | ); |
| 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); | |
| 274 | 161 | // 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) { | |
| 290 | 163 | if (scrollTo === "first") { |
| 291 | - scrollToMatch(filteredMatches[0]); | |
| 164 | + scrollToMatch(results[0]); | |
| 292 | 165 | } |
| 293 | 166 | if (scrollTo === "closest") { |
| 294 | - if (closestMatchToMiddle) { | |
| 295 | - scrollToMatch(closestMatchToMiddle); | |
| 167 | + if (closestToMiddle) { | |
| 168 | + scrollToMatch(closestToMiddle); | |
| 296 | 169 | } |
| 297 | 170 | } |
| 298 | 171 | if (scrollTo === "none") { |
| 299 | - if (closestMatchToMiddle) { | |
| 300 | - setCurrentMatch(closestMatchToMiddle); | |
| 172 | + if (closestToMiddle) { | |
| 173 | + setCurrentMatch(closestToMiddle); | |
| 301 | 174 | } else { |
| 302 | - setCurrentMatch(filteredMatches[0]); | |
| 175 | + setCurrentMatch(results[0]); | |
| 303 | 176 | } |
| 304 | 177 | } |
| 305 | 178 | } |
| 306 | 179 | }, |
| 307 | - [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex], | |
| 180 | + [ | |
| 181 | + searchTerm, | |
| 182 | + caseSensitive, | |
| 183 | + useRegex, | |
| 184 | + searchRef, | |
| 185 | + headerHeight, | |
| 186 | + scrollToMatch, | |
| 187 | + ], | |
| 308 | 188 | ); |
| 309 | 189 | |
| 310 | 190 | // Triggers that should cause immediate refresh of results to closest search value: |
| 311 | - // Input change (debounced) and window click | |
| 312 | - const lastUpdateRef = useRef(0); | |
| 313 | 191 | 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([]); | |
| 322 | 194 | } else { |
| 323 | - const handler = setTimeout(() => { | |
| 324 | - debounce(); | |
| 325 | - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); | |
| 326 | - return () => { | |
| 327 | - clearTimeout(handler); | |
| 328 | - }; | |
| 195 | + refreshSearch("closest"); | |
| 329 | 196 | } |
| 330 | - }, [refreshSearch, input]); | |
| 197 | + }, [refreshSearch, open, disabled, isResizing]); | |
| 331 | 198 | |
| 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 | |
| 334 | 201 | useEffect(() => { |
| 335 | 202 | const searchContainer = searchRef.current; |
| 336 | 203 | if (!open || !searchContainer) return; |
| 337 | 204 | const handleSearchRefClick = () => { |
| 338 | - refreshSearch("none"); | |
| 205 | + setTimeout(() => { | |
| 206 | + refreshSearch("none"); | |
| 207 | + }, 150); | |
| 339 | 208 | }; |
| 340 | 209 | searchContainer.addEventListener("click", handleSearchRefClick); |
| 341 | 210 | return () => { |
| 342 | 211 | searchContainer.removeEventListener("click", handleSearchRefClick); |
| 343 | 212 | }; |
| 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]); | |
| 363 | 214 | |
| 364 | 215 | // 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"> | |
| 411 | 236 | <HeaderButtonWithToolTip |
| 412 | - disabled={active} | |
| 413 | - inverted={caseSensitive} | |
| 414 | 237 | tooltipPlacement="top-end" |
| 415 | - text={ | |
| 416 | - caseSensitive | |
| 417 | - ? "Turn off case sensitivity" | |
| 418 | - : "Turn on case sensitivity" | |
| 419 | - } | |
| 238 | + text={"Previous Match"} | |
| 420 | 239 | onClick={(e) => { |
| 421 | 240 | e.stopPropagation(); |
| 422 | - setCaseSensitive((curr) => !curr); | |
| 241 | + previousMatch(); | |
| 423 | 242 | }} |
| 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} | |
| 425 | 245 | > |
| 426 | - Aa | |
| 246 | + <ArrowUpIcon className="h-4 w-4" /> | |
| 427 | 247 | </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} | |
| 433 | 257 | > |
| 434 | - <XMarkIcon className="h-4 w-4" /> | |
| 435 | - </HeaderButton> | |
| 258 | + <ArrowDownIcon className="h-4 w-4" /> | |
| 259 | + </HeaderButtonWithToolTip> | |
| 436 | 260 | </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 | + ); | |
| 448 | 288 | |
| 449 | 289 | // Generate the highlight overlay elements |
| 450 | 290 | const highlights = useMemo(() => { |
| 451 | 291 | return matches.map((match) => ( |
| 452 | 292 | <HighlightOverlay |
| 453 | - {...match.overlayRectangle} | |
| 293 | + rectangle={match.overlayRectangle} | |
| 454 | 294 | isCurrent={currentMatch?.index === match.index} |
| 455 | 295 | /> |
| 456 | 296 | )); |
| 457 | 297 | }, [matches, currentMatch]); |
| 458 | 298 | |
| 459 | 299 | return { |
| 460 | - matches, | |
| 461 | 300 | highlights, |
| 462 | - inputRef, | |
| 463 | - input: debouncedInput, | |
| 464 | - setInput, | |
| 465 | - open, | |
| 466 | - setOpen, | |
| 467 | 301 | widget, |
| 468 | 302 | }; |
| 469 | 303 | }; |
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"; | |
| 2 | 2 | import { useSelector } from "react-redux"; |
| 3 | 3 | import styled from "styled-components"; |
| 4 | 4 | import { AnimatedEllipsis } from "../.."; |
| @@ -40,12 +40,27 @@ | ||
| 40 | 40 | ); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | +function ApplyingIndicator() { | |
| 44 | + return ( | |
| 45 | + <div className="text-xs text-gray-400"> | |
| 46 | + <span>Applying</span> | |
| 47 | + <AnimatedEllipsis /> | |
| 48 | + </div> | |
| 49 | + ); | |
| 50 | +} | |
| 51 | + | |
| 43 | 52 | export function LumpToolbar() { |
| 44 | 53 | const dispatch = useAppDispatch(); |
| 45 | 54 | const ideMessenger = useContext(IdeMessengerContext); |
| 46 | 55 | const ttsActive = useAppSelector((state) => state.ui.ttsActive); |
| 47 | 56 | const isStreaming = useAppSelector((state) => state.session.isStreaming); |
| 48 | 57 | 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]); | |
| 49 | 64 | |
| 50 | 65 | const toolCallState = useSelector(selectCurrentToolCall); |
| 51 | 66 | |
| @@ -89,6 +104,26 @@ | ||
| 89 | 104 | ); |
| 90 | 105 | } |
| 91 | 106 | |
| 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 | + | |
| 92 | 127 | if (isStreaming) { |
| 93 | 128 | return ( |
| 94 | 129 | <Container> |
modified gui/src/pages/gui/Chat.tsx +11 −6
| @@ -44,16 +44,17 @@ | ||
| 44 | 44 | setDialogMessage, |
| 45 | 45 | setShowDialog, |
| 46 | 46 | } from "../../redux/slices/uiSlice"; |
| 47 | +import { streamResponseThunk } from "../../redux/thunks"; | |
| 47 | 48 | import { cancelStream } from "../../redux/thunks/cancelStream"; |
| 48 | 49 | import { streamEditThunk } from "../../redux/thunks/editMode"; |
| 49 | 50 | import { loadLastSession } from "../../redux/thunks/session"; |
| 50 | -import { streamResponseThunk } from "../../redux/thunks"; | |
| 51 | 51 | import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; |
| 52 | 52 | import { |
| 53 | 53 | FREE_TRIAL_LIMIT_REQUESTS, |
| 54 | 54 | incrementFreeTrialCount, |
| 55 | 55 | } from "../../util/freeTrial"; |
| 56 | 56 | |
| 57 | +import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; | |
| 57 | 58 | import CodeToEditCard from "../../components/mainInput/CodeToEditCard"; |
| 58 | 59 | import EditModeDetails from "../../components/mainInput/EditModeDetails"; |
| 59 | 60 | import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; |
| @@ -61,7 +62,6 @@ | ||
| 61 | 62 | import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; |
| 62 | 63 | import { ToolCallDiv } from "./ToolCallDiv"; |
| 63 | 64 | import { useAutoScroll } from "./useAutoScroll"; |
| 64 | -import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; | |
| 65 | 65 | |
| 66 | 66 | const StepsDiv = styled.div` |
| 67 | 67 | position: relative; |
| @@ -113,6 +113,7 @@ | ||
| 113 | 113 | const [stepsOpen] = useState<(boolean | undefined)[]>([]); |
| 114 | 114 | const mainTextInputRef = useRef<HTMLInputElement>(null); |
| 115 | 115 | const stepsDivRef = useRef<HTMLDivElement>(null); |
| 116 | + const tabsRef = useRef<HTMLDivElement>(null); | |
| 116 | 117 | const history = useAppSelector((state) => state.session.history); |
| 117 | 118 | const showChatScrollbar = useAppSelector( |
| 118 | 119 | (state) => state.config.config.ui?.showChatScrollbar, |
| @@ -143,6 +144,7 @@ | ||
| 143 | 144 | !e.shiftKey |
| 144 | 145 | ) { |
| 145 | 146 | dispatch(cancelStream()); |
| 147 | + ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter | |
| 146 | 148 | } |
| 147 | 149 | }; |
| 148 | 150 | window.addEventListener("keydown", listener); |
| @@ -152,7 +154,11 @@ | ||
| 152 | 154 | }; |
| 153 | 155 | }, [isStreaming, jetbrains]); |
| 154 | 156 | |
| 155 | - const { widget, highlights } = useFindWidget(stepsDivRef); | |
| 157 | + const { widget, highlights } = useFindWidget( | |
| 158 | + stepsDivRef, | |
| 159 | + tabsRef, | |
| 160 | + isStreaming, | |
| 161 | + ); | |
| 156 | 162 | |
| 157 | 163 | const currentToolCallApplyState = useAppSelector( |
| 158 | 164 | selectCurrentToolCallApplyState, |
| @@ -286,13 +292,12 @@ | ||
| 286 | 292 | |
| 287 | 293 | return ( |
| 288 | 294 | <> |
| 295 | + {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />} | |
| 289 | 296 | {widget} |
| 290 | 297 | |
| 291 | - {!!showSessionTabs && mode !== "edit" && <TabBar />} | |
| 292 | - | |
| 293 | 298 | <StepsDiv |
| 294 | 299 | 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" : ""}`} | |
| 296 | 301 | > |
| 297 | 302 | {highlights} |
| 298 | 303 | {history.map((item, index: number) => ( |
modified gui/src/pages/gui/StreamError.tsx +86 −47
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowTopRightOnSquareIcon, |
| 3 | - Cog8ToothIcon, | |
| 3 | + ClipboardIcon, | |
| 4 | + Cog6ToothIcon, | |
| 5 | + KeyIcon, | |
| 4 | 6 | } from "@heroicons/react/24/outline"; |
| 5 | 7 | import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; |
| 6 | 8 | import { useContext, useMemo } from "react"; |
| 7 | -import { Button, SecondaryButton } from "../../components"; | |
| 9 | +import { GhostButton, SecondaryButton } from "../../components"; | |
| 8 | 10 | import { DiscordIcon } from "../../components/svg/DiscordIcon"; |
| 9 | 11 | import { GithubIcon } from "../../components/svg/GithubIcon"; |
| 12 | +import ToggleDiv from "../../components/ToggleDiv"; | |
| 10 | 13 | import { useAuth } from "../../context/Auth"; |
| 11 | 14 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 12 | 15 | import { selectSelectedProfile } from "../../redux/"; |
| @@ -48,11 +51,15 @@ | ||
| 48 | 51 | ); |
| 49 | 52 | |
| 50 | 53 | const handleRefreshProfiles = () => { |
| 51 | - refreshProfiles(); | |
| 54 | + void refreshProfiles(); | |
| 52 | 55 | dispatch(setShowDialog(false)); |
| 53 | 56 | dispatch(setDialogMessage(undefined)); |
| 54 | 57 | }; |
| 55 | 58 | |
| 59 | + const copyErrorToClipboard = () => { | |
| 60 | + void navigator.clipboard.writeText(parsedError); | |
| 61 | + }; | |
| 62 | + | |
| 56 | 63 | // Collect model information to display useful error info |
| 57 | 64 | let modelTitle = "Chat model"; |
| 58 | 65 | let providerName = "the model provider"; |
| @@ -99,30 +106,29 @@ | ||
| 99 | 106 | } |
| 100 | 107 | |
| 101 | 108 | const checkKeysButton = apiKeyUrl ? ( |
| 102 | - <Button | |
| 103 | - className="cursor-pointer hover:underline" | |
| 109 | + <GhostButton | |
| 110 | + className="flex items-center" | |
| 104 | 111 | onClick={() => { |
| 105 | 112 | ideMessenger.post("openUrl", apiKeyUrl!); |
| 106 | 113 | }} |
| 107 | 114 | > |
| 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> | |
| 110 | 118 | ) : null; |
| 111 | 119 | |
| 112 | 120 | 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" | |
| 115 | 123 | onClick={() => { |
| 116 | 124 | ideMessenger.post("config/openProfile", { |
| 117 | 125 | profileId: undefined, |
| 118 | 126 | }); |
| 119 | 127 | }} |
| 120 | 128 | > |
| 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> | |
| 126 | 132 | ); |
| 127 | 133 | |
| 128 | 134 | if ( |
| @@ -131,7 +137,20 @@ | ||
| 131 | 137 | return <ModelsAddOnLimitDialog />; |
| 132 | 138 | } |
| 133 | 139 | |
| 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 | + ); | |
| 135 | 154 | |
| 136 | 155 | // Display components for specific errors |
| 137 | 156 | if (statusCode === 429) { |
| @@ -141,7 +160,7 @@ | ||
| 141 | 160 | {`This might mean your ${modelTitle} usage has been rate limited |
| 142 | 161 | by ${providerName}.`} |
| 143 | 162 | </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"> | |
| 145 | 164 | {checkKeysButton} |
| 146 | 165 | {configButton} |
| 147 | 166 | </div> |
| @@ -230,51 +249,71 @@ | ||
| 230 | 249 | ); |
| 231 | 250 | } |
| 232 | 251 | |
| 252 | + console.log({ message }); | |
| 253 | + | |
| 233 | 254 | 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> | |
| 253 | 293 | </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" | |
| 262 | 301 | onClick={() => { |
| 263 | 302 | ideMessenger.post("openUrl", GITHUB_LINK); |
| 264 | 303 | }} |
| 265 | 304 | > |
| 266 | 305 | <GithubIcon className="h-5 w-5" /> |
| 267 | 306 | <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" | |
| 271 | 310 | onClick={() => { |
| 272 | 311 | ideMessenger.post("openUrl", DISCORD_LINK); |
| 273 | 312 | }} |
| 274 | 313 | > |
| 275 | 314 | <DiscordIcon className="h-5 w-5" /> |
| 276 | 315 | <span className="xs:flex hidden">Discord</span> |
| 277 | - </SecondaryButton> | |
| 316 | + </GhostButton> | |
| 278 | 317 | </div> |
| 279 | 318 | </div> |
| 280 | 319 | </div> |
modified manual-testing-sandbox/AdvancedPage.tsx +1 −4
| @@ -13,10 +13,7 @@ | ||
| 13 | 13 | className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`} |
| 14 | 14 | > |
| 15 | 15 | <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 | + {" "} | |
| 20 | 17 | <button |
| 21 | 18 | className="rounded bg-blue-500 px-4 py-2 text-white" |
| 22 | 19 | onClick={toggleDarkMode} |
modified packages/config-yaml/package-lock.json +2 −2
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.87", | |
| 3 | + "version": "1.0.88", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/config-yaml", |
| 9 | - "version": "1.0.87", | |
| 9 | + "version": "1.0.88", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@continuedev/config-types": "^1.0.14", |
modified packages/config-yaml/package.json +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.87", | |
| 3 | + "version": "1.0.88", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
modified packages/config-yaml/src/load/clientRender.ts +1 −0
| @@ -160,6 +160,7 @@ | ||
| 160 | 160 | apiKeyLocation: z.string().optional(), |
| 161 | 161 | apiBase: z.string().optional(), |
| 162 | 162 | orgScopeId: z.string().nullable(), |
| 163 | + env: z.record(z.string(), z.any()).optional(), | |
| 163 | 164 | }); |
| 164 | 165 | |
| 165 | 166 | export type ContinueProperties = z.infer<typeof continuePropertiesSchema>; |
modified packages/config-yaml/src/schemas/index.ts +6 −2
| @@ -9,13 +9,16 @@ | ||
| 9 | 9 | params: z.any().optional(), |
| 10 | 10 | }); |
| 11 | 11 | |
| 12 | +// TODO: This should be a discriminated union by type | |
| 12 | 13 | const mcpServerSchema = z.object({ |
| 13 | 14 | name: z.string(), |
| 14 | - command: z.string(), | |
| 15 | + command: z.string().optional(), | |
| 16 | + type: z.enum(["sse", "stdio"]).optional(), | |
| 17 | + url: z.string().optional(), | |
| 15 | 18 | faviconUrl: z.string().optional(), |
| 16 | 19 | args: z.array(z.string()).optional(), |
| 17 | 20 | env: z.record(z.string()).optional(), |
| 18 | - connectionTimeout: z.number().gt(0).optional() | |
| 21 | + connectionTimeout: z.number().gt(0).optional(), | |
| 19 | 22 | }); |
| 20 | 23 | |
| 21 | 24 | export type MCPServer = z.infer<typeof mcpServerSchema>; |
| @@ -39,6 +42,7 @@ | ||
| 39 | 42 | const ruleObjectSchema = z.object({ |
| 40 | 43 | name: z.string(), |
| 41 | 44 | rule: z.string(), |
| 45 | + description: z.string().optional(), | |
| 42 | 46 | globs: z.union([z.string(), z.array(z.string())]).optional(), |
| 43 | 47 | }); |
| 44 | 48 | const ruleSchema = z.union([z.string(), ruleObjectSchema]); |
modified packages/config-yaml/src/schemas/models.ts +1 −0
| @@ -117,6 +117,7 @@ | ||
| 117 | 117 | model: z.string(), |
| 118 | 118 | apiKey: z.string().optional(), |
| 119 | 119 | apiBase: z.string().optional(), |
| 120 | + maxStopWords: z.number().optional(), | |
| 120 | 121 | roles: modelRolesSchema.array().optional(), |
| 121 | 122 | capabilities: modelCapabilitySchema.array().optional(), |
| 122 | 123 | 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 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/fetch", |
| 3 | - "version": "1.0.6", | |
| 3 | + "version": "1.0.9", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/fetch", |
| 9 | - "version": "1.0.6", | |
| 9 | + "version": "1.0.9", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@continuedev/config-types": "^1.0.5", |
modified packages/fetch/package.json +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/fetch", |
| 3 | - "version": "1.0.9", | |
| 3 | + "version": "1.0.10", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "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 | +}); | |
| 4 | 64 | |
| 5 | 65 | describe("parseDataLine", () => { |
| 6 | 66 | test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => { |
modified packages/fetch/src/stream.ts +2 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | nodeReadable: NodeJS.ReadableStream, |
| 3 | 3 | ): AsyncGenerator<Uint8Array> { |
| 4 | 4 | for await (const chunk of nodeReadable) { |
| 5 | - // @ts-expect-error | |
| 5 | + // @ts-ignore | |
| 6 | 6 | yield chunk as Uint8Array; |
| 7 | 7 | } |
| 8 | 8 | } |
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | if (response.status === 499) { |
| 14 | 14 | return; // In case of client-side cancellation, just return |
| 15 | 15 | } |
| 16 | + | |
| 16 | 17 | if (response.status !== 200) { |
| 17 | 18 | throw new Error(await response.text()); |
| 18 | 19 | } |
modified packages/fetch/tsconfig.json +1 −1
| @@ -19,5 +19,5 @@ | ||
| 19 | 19 | "declaration": true |
| 20 | 20 | // "sourceMap": true |
| 21 | 21 | }, |
| 22 | - "include": ["src/**/*"] | |
| 22 | + "include": ["src/**/*", "jest.globals.d.ts"] | |
| 23 | 23 | } |
modified packages/openai-adapters/README.md +1 −1
| @@ -64,7 +64,7 @@ | ||
| 64 | 64 | - [x] Vllm |
| 65 | 65 | - [ ] Vertex AI |
| 66 | 66 | - [x] Voyage AI |
| 67 | -- [ ] WatsonX | |
| 67 | +- [x] WatsonX | |
| 68 | 68 | - [x] xAI |
| 69 | 69 | - [x] Fireworks |
| 70 | 70 | - [x] Moonshot |
modified packages/openai-adapters/package-lock.json +6 −6
| @@ -1,18 +1,18 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/openai-adapters", |
| 3 | - "version": "1.0.21", | |
| 3 | + "version": "1.0.22", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/openai-adapters", |
| 9 | - "version": "1.0.21", | |
| 9 | + "version": "1.0.22", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@azure/openai": "^1.0.0-beta.12", |
| 13 | 13 | "@continuedev/config-types": "^1.0.5", |
| 14 | 14 | "@continuedev/config-yaml": "^1.0.51", |
| 15 | - "@continuedev/fetch": "^1.0.3", | |
| 15 | + "@continuedev/fetch": "^1.0.10", | |
| 16 | 16 | "dotenv": "^16.5.0", |
| 17 | 17 | "json-schema": "^0.4.0", |
| 18 | 18 | "node-fetch": "^3.3.2", |
| @@ -716,9 +716,9 @@ | ||
| 716 | 716 | } |
| 717 | 717 | }, |
| 718 | 718 | "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==", | |
| 722 | 722 | "dependencies": { |
| 723 | 723 | "@continuedev/config-types": "^1.0.5", |
| 724 | 724 | "follow-redirects": "^1.15.6", |
modified packages/openai-adapters/package.json +2 −2
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/openai-adapters", |
| 3 | - "version": "1.0.21", | |
| 3 | + "version": "1.0.26", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | "@azure/openai": "^1.0.0-beta.12", |
| 16 | 16 | "@continuedev/config-types": "^1.0.5", |
| 17 | 17 | "@continuedev/config-yaml": "^1.0.51", |
| 18 | - "@continuedev/fetch": "^1.0.3", | |
| 18 | + "@continuedev/fetch": "^1.0.10", | |
| 19 | 19 | "dotenv": "^16.5.0", |
| 20 | 20 | "json-schema": "^0.4.0", |
| 21 | 21 | "node-fetch": "^3.3.2", |
modified packages/openai-adapters/src/apis/Anthropic.ts +5 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | import { ChatCompletionCreateParams } from "openai/src/resources/index.js"; |
| 13 | 13 | import { AnthropicConfig } from "../types.js"; |
| 14 | 14 | import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js"; |
| 15 | +import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; | |
| 15 | 16 | import { |
| 16 | 17 | BaseLlmApi, |
| 17 | 18 | CreateRerankResponse, |
| @@ -157,6 +158,10 @@ | ||
| 157 | 158 | }, |
| 158 | 159 | ); |
| 159 | 160 | |
| 161 | + if (response.status === 499) { | |
| 162 | + return EMPTY_CHAT_COMPLETION; | |
| 163 | + } | |
| 164 | + | |
| 160 | 165 | const completion = (await response.json()) as any; |
| 161 | 166 | return { |
| 162 | 167 | id: completion.id, |
modified packages/openai-adapters/src/apis/Cohere.ts +5 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | } from "openai/resources/index"; |
| 16 | 16 | import { CohereConfig } from "../types.js"; |
| 17 | 17 | import { chatCompletion, customFetch, embedding } from "../util.js"; |
| 18 | +import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; | |
| 18 | 19 | import { |
| 19 | 20 | BaseLlmApi, |
| 20 | 21 | CreateRerankResponse, |
| @@ -77,6 +78,10 @@ | ||
| 77 | 78 | }, |
| 78 | 79 | ); |
| 79 | 80 | |
| 81 | + if (resp.status === 499) { | |
| 82 | + return EMPTY_CHAT_COMPLETION; | |
| 83 | + } | |
| 84 | + | |
| 80 | 85 | const data = (await resp.json()) as any; |
| 81 | 86 | const { input_tokens, output_tokens } = data.meta.tokens; |
| 82 | 87 | return chatCompletion({ |
modified packages/openai-adapters/src/apis/Relace.ts +4 −0
| @@ -105,6 +105,10 @@ | ||
| 105 | 105 | signal, |
| 106 | 106 | }); |
| 107 | 107 | |
| 108 | + if (response.status === 499) { | |
| 109 | + return; // Aborted by user | |
| 110 | + } | |
| 111 | + | |
| 108 | 112 | const result = (await response.json()) as any; |
| 109 | 113 | const mergedCode = result.mergedCode; |
| 110 | 114 |
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 @@ | ||
| 11 | 11 | import { MoonshotApi } from "./apis/Moonshot.js"; |
| 12 | 12 | import { OpenAIApi } from "./apis/OpenAI.js"; |
| 13 | 13 | import { RelaceApi } from "./apis/Relace.js"; |
| 14 | +import { WatsonXApi } from "./apis/WatsonX.js"; | |
| 14 | 15 | import { BaseLlmApi } from "./apis/base.js"; |
| 15 | 16 | import { LLMConfig, OpenAIConfigSchema } from "./types.js"; |
| 16 | 17 | |
| @@ -48,6 +49,8 @@ | ||
| 48 | 49 | return new RelaceApi(config); |
| 49 | 50 | case "inception": |
| 50 | 51 | return new InceptionApi(config); |
| 52 | + case "watsonx": | |
| 53 | + return new WatsonXApi(config); | |
| 51 | 54 | case "x-ai": |
| 52 | 55 | return openAICompatible("https://api.x.ai/v1/", config); |
| 53 | 56 | case "voyage": |
| @@ -75,7 +78,10 @@ | ||
| 75 | 78 | case "nvidia": |
| 76 | 79 | return openAICompatible("https://integrate.api.nvidia.com/v1/", config); |
| 77 | 80 | 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 | + ); | |
| 79 | 85 | case "scaleway": |
| 80 | 86 | return openAICompatible("https://api.scaleway.ai/v1/", config); |
| 81 | 87 | case "fireworks": |
| @@ -111,10 +117,9 @@ | ||
| 111 | 117 | type Completion, |
| 112 | 118 | type CompletionCreateParams, |
| 113 | 119 | type CompletionCreateParamsNonStreaming, |
| 114 | - type CompletionCreateParamsStreaming | |
| 120 | + type CompletionCreateParamsStreaming, | |
| 115 | 121 | } from "openai/resources/index"; |
| 116 | 122 | |
| 117 | 123 | // export |
| 118 | 124 | export type { BaseLlmApi } from "./apis/base.js"; |
| 119 | 125 | export type { LLMConfig } from "./types.js"; |
| 120 | - |
modified packages/openai-adapters/src/test/main.test.ts +1 −0
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | provider: config.provider as any, |
| 11 | 11 | apiKey: config.apiKey, |
| 12 | 12 | apiBase: config.apiBase, |
| 13 | + env: config.env, | |
| 13 | 14 | }); |
| 14 | 15 | |
| 15 | 16 | if (false) { |
modified packages/openai-adapters/src/types.ts +12 −0
| @@ -99,6 +99,17 @@ | ||
| 99 | 99 | }); |
| 100 | 100 | export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>; |
| 101 | 101 | |
| 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 | + | |
| 102 | 113 | export const JinaConfigSchema = OpenAIConfigSchema.extend({ |
| 103 | 114 | provider: z.literal("jina"), |
| 104 | 115 | }); |
| @@ -118,6 +129,7 @@ | ||
| 118 | 129 | AzureConfigSchema, |
| 119 | 130 | GeminiConfigSchema, |
| 120 | 131 | AnthropicConfigSchema, |
| 132 | + WatsonXConfigSchema, | |
| 121 | 133 | JinaConfigSchema, |
| 122 | 134 | MockConfigSchema, |
| 123 | 135 | 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 | +}; |