From b072c5fee401a5ffc8f5dc437570c6d8b7a5b049 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 2 May 2025 12:07:15 -0700 Subject: [PATCH 01/38] WIP: message abort controllers --- core/core.ts | 94 ++++++++++++++++++------------------ core/edit/streamDiffLines.ts | 9 +++- core/llm/streamChat.ts | 62 +++++++++++------------- 3 files changed, 80 insertions(+), 85 deletions(-) diff --git a/core/core.ts b/core/core.ts index e5c9eeab0..36b4a399c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,7 +35,6 @@ import { TTS } from "./util/tts"; import { ContextItemWithId, - DiffLine, IdeSettings, ModelDescription, RangeInFile, @@ -63,43 +62,6 @@ import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; -async function* streamDiffLinesGenerator( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, -): AsyncGenerator { - const data = msg.data; - - const { config } = await configHandler.loadConfig(); - if (!config) { - throw new Error("Failed to load config"); - } - - const llm = config.selectedModelByRole.chat; - - if (!llm) { - throw new Error("No chat model selected"); - } - - for await (const diffLine of streamDiffLines({ - highlighted: data.highlighted, - prefix: data.prefix, - suffix: data.suffix, - llm, - rules: config.rules, - input: data.input, - language: data.language, - onlyOneInsertion: false, - overridePrompt: undefined, - })) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - yield diffLine; - } -} - export class Core { configHandler: ConfigHandler; codebaseIndexerPromise: Promise; @@ -114,7 +76,18 @@ export class Core { this.globalContext.get("indexingPaused") === true, ); - private abortedMessageIds: Set = new Set(); + private messageAbortControllers = new Map(); + private addMessageAbortController(messageId: string): AbortController { + const controller = new AbortController(); + this.messageAbortControllers.set(messageId, controller); + controller.signal.addEventListener("abort", () => { + this.messageAbortControllers.delete(messageId); + }); + return controller; + } + private abortMessage(messageId: string) { + this.messageAbortControllers.get(messageId)?.abort(); + } invoke( messageType: T, @@ -283,7 +256,7 @@ export class Core { }); on("abort", (msg) => { - this.abortedMessageIds.add(msg.messageId); + this.abortMessage(msg.messageId); }); on("ping", (msg) => { @@ -452,15 +425,16 @@ export class Core { } }); - on("llm/streamChat", (msg) => - llmStreamChat( + on("llm/streamChat", (msg) => { + const abortController = this.addMessageAbortController(msg.messageId); + return llmStreamChat( this.configHandler, - this.abortedMessageIds, + abortController, msg, this.ide, this.messenger, - ), - ); + ); + }); on("llm/complete", async (msg) => { const model = (await this.configHandler.loadConfig()).config @@ -514,9 +488,33 @@ export class Core { this.completionProvider.cancel(); }); - on("streamDiffLines", (msg) => - streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg), - ); + on("streamDiffLines", async (msg) => { + const abortController = this.addMessageAbortController(msg.messageId); + + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Failed to load config"); + } + + const llm = config.selectedModelByRole.chat; + if (!llm) { + throw new Error("No chat model selected"); + } + + const { data } = msg; + return streamDiffLines({ + highlighted: data.highlighted, + prefix: data.prefix, + suffix: data.suffix, + llm, + rules: config.rules, + input: data.input, + language: data.language, + onlyOneInsertion: false, + overridePrompt: undefined, + abortController, + }); + }); on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 320962b7c..bcf74bf80 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -67,6 +67,7 @@ export async function* streamDiffLines({ onlyOneInsertion, overridePrompt, rules, + abortController, }: { prefix: string; highlighted: string; @@ -77,6 +78,7 @@ export async function* streamDiffLines({ onlyOneInsertion: boolean; overridePrompt: ChatMessage[] | undefined; rules: RuleWithSource[]; + abortController: AbortController; }): AsyncGenerator { void Telemetry.capture( "inlineEdit", @@ -158,12 +160,12 @@ export async function* streamDiffLines({ const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, new AbortController().signal, { + ? llm.streamComplete(prompt, abortController.signal, { raw: true, prediction, reasoning: false, }) - : llm.streamChat(prompt, new AbortController().signal, { + : llm.streamChat(prompt, abortController.signal, { prediction, reasoning: false, }); @@ -190,6 +192,9 @@ export async function* streamDiffLines({ let seenGreen = false; for await (const diffLine of diffLines) { + if (abortController.signal.aborted) { + break; + } yield diffLine; if (diffLine.type === "new") { seenGreen = true; diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 223b5b20e..c899e437f 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -8,7 +8,7 @@ import { TTS } from "../util/tts"; export async function* llmStreamChat( configHandler: ConfigHandler, - abortedMessageIds: Set, + abortController: AbortController, msg: Message, ide: IDE, messenger: IMessenger, @@ -75,52 +75,44 @@ export async function* llmStreamChat( selectedCode, config, fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), + fetchwithRequestOptions( + url, + { + ...init, + signal: abortController.signal, + }, + config.requestOptions, + ), completionOptions, }); - const checkActiveInterval = setInterval(() => { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - clearInterval(checkActiveInterval); + let next = await gen.next(); + while (!next.done) { + if (abortController.signal.aborted) { + next = await gen.return(errorPromptLog); + break; } - }, 100); - try { - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - next = await gen.return(errorPromptLog); - clearInterval(checkActiveInterval); - break; - } - if (next.value) { - yield { - role: "assistant", - content: next.value, - }; - } - next = await gen.next(); + if (next.value) { + yield { + role: "assistant", + content: next.value, + }; } - if (!next.done) { - throw new Error("Will never happen"); - } - - return next.value; - } catch (e) { - throw e; - } finally { - clearInterval(checkActiveInterval); + next = await gen.next(); } + if (!next.done) { + throw new Error("Will never happen"); + } + + return next.value; } else { const gen = model.streamChat( messages, - new AbortController().signal, + abortController.signal, completionOptions, ); let next = await gen.next(); while (!next.done) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); + if (abortController.signal.aborted) { next = await gen.return(errorPromptLog); break; } From 1f31554ea675f13d7988aecb03e09869fe76c315 Mon Sep 17 00:00:00 2001 From: Tobias Kulmburg Date: Wed, 14 May 2025 22:13:09 +0200 Subject: [PATCH 02/38] Feat: allow maxStopWords model config option in yaml --- core/config/util.ts | 1 + core/control-plane/schema.ts | 1 + docs/docs/reference.md | 1 + packages/config-yaml/src/schemas/models.ts | 3 ++- 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core/config/util.ts b/core/config/util.ts index cc187fc55..9128fc0b5 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -77,6 +77,7 @@ export function addModel( model: model.model, apiKey: model.apiKey, apiBase: model.apiBase, + maxStopWords: model.maxStopWords, defaultCompletionOptions: model.completionOptions, }; if (model.systemMessage) { diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index 66b0837ab..c860d99ee 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -26,6 +26,7 @@ const modelDescriptionSchema = z.object({ apiKey: z.string().optional(), apiBase: z.string().optional(), contextLength: z.number().optional(), + maxStopWords: z.number().optional(), template: z .enum([ "llama2", diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 4d0009d5c..0f452d958 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -188,6 +188,7 @@ chat, editing, and summarizing. not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [ `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [ diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index d98460815..c4b79a2e3 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -107,7 +107,7 @@ const templateSchema = z.enum([ const promptTemplatesSchema = z.object({ apply: z.string().optional(), chat: templateSchema.optional(), - edit: z.string().optional(), + edit: z.string().optional(), autocomplete: z.string().optional(), }); export type PromptTemplates = z.infer; @@ -117,6 +117,7 @@ const baseModelFields = { model: z.string(), apiKey: z.string().optional(), apiBase: z.string().optional(), + maxStopWords: z.number().optional(), roles: modelRolesSchema.array().optional(), capabilities: modelCapabilitySchema.array().optional(), defaultCompletionOptions: completionOptionsSchema.optional(), From 5f132eedf20d5dd1c1d1b721b42ff1326128341a Mon Sep 17 00:00:00 2001 From: Tobias Kulmburg Date: Wed, 14 May 2025 22:21:48 +0200 Subject: [PATCH 03/38] Feat: allow maxStopWords model config option in yaml --- packages/config-yaml/src/schemas/models.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index c4b79a2e3..926f15d05 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -107,7 +107,7 @@ const templateSchema = z.enum([ const promptTemplatesSchema = z.object({ apply: z.string().optional(), chat: templateSchema.optional(), - edit: z.string().optional(), + edit: z.string().optional(), autocomplete: z.string().optional(), }); export type PromptTemplates = z.infer; From bc7954c9ef0507801e19872f6eec6bedd6a607b0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 15 May 2025 04:10:36 +0000 Subject: [PATCH 04/38] chore(deps): bump @nestjs/common and @openapitools/openapi-generator-cli Bumps [@nestjs/common](https://github.com/nestjs/nest/tree/HEAD/packages/common) to 11.0.20 and updates ancestor dependency [@openapitools/openapi-generator-cli](https://github.com/OpenAPITools/openapi-generator-cli). These dependencies need to be updated together. Updates `@nestjs/common` from 10.4.6 to 11.0.20 - [Release notes](https://github.com/nestjs/nest/releases) - [Commits](https://github.com/nestjs/nest/commits/v11.0.20/packages/common) Updates `@openapitools/openapi-generator-cli` from 2.15.3 to 2.20.0 - [Release notes](https://github.com/OpenAPITools/openapi-generator-cli/releases) - [Changelog](https://github.com/OpenAPITools/openapi-generator-cli/blob/master/.releaserc) - [Commits](https://github.com/OpenAPITools/openapi-generator-cli/compare/v2.15.3...v2.20.0) --- updated-dependencies: - dependency-name: "@nestjs/common" dependency-version: 11.0.20 dependency-type: indirect - dependency-name: "@openapitools/openapi-generator-cli" dependency-version: 2.20.0 dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- extensions/vscode/package-lock.json | 421 +++++++++++++++------------- extensions/vscode/package.json | 2 +- 2 files changed, 224 insertions(+), 199 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index f0968956e..207a877dc 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -64,7 +64,7 @@ "devDependencies": { "@biomejs/biome": "1.6.4", "@nestjs/common": "^11.0.16", - "@openapitools/openapi-generator-cli": "^2.5.2", + "@openapitools/openapi-generator-cli": "^2.20.0", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", @@ -1442,14 +1442,28 @@ "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" }, + "node_modules/@nestjs/axios": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz", + "integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^10.0.0 || ^11.0.0", + "axios": "^1.3.1", + "rxjs": "^7.0.0" + } + }, "node_modules/@nestjs/common": { - "version": "11.0.16", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.16.tgz", - "integrity": "sha512-agvuQ8su4aZ+PVxAmY89odG1eR97HEQvxPmTMdDqyvDWzNerl7WQhUEd+j4/UyNWcF1or1UVcrtPj52x+eUSsA==", + "version": "11.0.20", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.20.tgz", + "integrity": "sha512-/GH8NDCczjn6+6RNEtSNAts/nq/wQE8L1qZ9TRjqjNqEsZNE1vpFuRIhmcO2isQZ0xY5rySnpaRdrOAul3gQ3A==", "dev": true, "license": "MIT", "dependencies": { + "file-type": "20.4.1", "iterare": "1.2.1", + "load-esm": "1.0.2", "tslib": "2.8.1", "uid": "2.0.2" }, @@ -1460,7 +1474,6 @@ "peerDependencies": { "class-transformer": "*", "class-validator": "*", - "file-type": "^20.4.1", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, @@ -1473,6 +1486,58 @@ } } }, + "node_modules/@nestjs/core": { + "version": "11.0.20", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.0.20.tgz", + "integrity": "sha512-yUkEzBGiRNSEThVl6vMCXgoA9sDGWoRbJsTLdYdCC7lg7PE1iXBnna1FiBfQjT995pm0fjyM1e3WsXmyWeJXbw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@nuxt/opencollective": "0.4.1", + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "8.2.0", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "engines": { + "node": ">= 20" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^11.0.0", + "@nestjs/microservices": "^11.0.0", + "@nestjs/platform-express": "^11.0.0", + "@nestjs/websockets": "^11.0.0", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + }, + "@nestjs/websockets": { + "optional": true + } + } + }, + "node_modules/@nestjs/core/node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1565,11 +1630,29 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/@nuxt/opencollective": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz", + "integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "consola": "^3.2.3" + }, + "bin": { + "opencollective": "bin/opencollective.js" + }, + "engines": { + "node": "^14.18.0 || >=16.10.0", + "npm": ">=5.10.0" + } + }, "node_modules/@nuxtjs/opencollective": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz", "integrity": "sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==", "dev": true, + "license": "MIT", "dependencies": { "chalk": "^4.1.0", "consola": "^2.15.0", @@ -1583,11 +1666,19 @@ "npm": ">=5.0.0" } }, + "node_modules/@nuxtjs/opencollective/node_modules/consola": { + "version": "2.15.3", + "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", + "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", + "dev": true, + "license": "MIT" + }, "node_modules/@nuxtjs/opencollective/node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", "dev": true, + "license": "MIT", "dependencies": { "whatwg-url": "^5.0.0" }, @@ -1607,48 +1698,52 @@ "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@nuxtjs/opencollective/node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true + "dev": true, + "license": "BSD-2-Clause" }, "node_modules/@nuxtjs/opencollective/node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", "dev": true, + "license": "MIT", "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "node_modules/@openapitools/openapi-generator-cli": { - "version": "2.15.3", - "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.15.3.tgz", - "integrity": "sha512-2UBnsDlMt36thhdXxisbA1qReVtbCaw+NCvXoslRXlaJBL4qkAmZUhNeDLNu3LCbwA2PASMWhJSqeLwgwMCitw==", + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.20.0.tgz", + "integrity": "sha512-Amtd7/9Lodaxnmfsru8R5n0CW9lyWOI40UsppGMfuNFkFFbabq51/VAJFsOHkNnDRwVUc7AGKWjN5icphDGlTQ==", "dev": true, "hasInstallScript": true, + "license": "Apache-2.0", "dependencies": { - "@nestjs/axios": "3.1.1", - "@nestjs/common": "10.4.6", - "@nestjs/core": "10.4.6", + "@nestjs/axios": "4.0.0", + "@nestjs/common": "11.0.20", + "@nestjs/core": "11.0.20", "@nuxtjs/opencollective": "0.3.2", - "axios": "1.7.7", + "axios": "1.8.4", "chalk": "4.1.2", "commander": "8.3.0", "compare-versions": "4.1.4", "concurrently": "6.5.1", "console.table": "0.10.0", - "fs-extra": "10.1.0", + "fs-extra": "11.3.0", "glob": "9.3.5", "inquirer": "8.2.6", "lodash": "4.17.21", - "proxy-agent": "6.4.0", - "reflect-metadata": "0.1.13", - "rxjs": "7.8.1", + "proxy-agent": "6.5.0", + "reflect-metadata": "0.2.2", + "rxjs": "7.8.2", "tslib": "2.8.1" }, "bin": { @@ -1662,97 +1757,6 @@ "url": "https://opencollective.com/openapi_generator" } }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/axios": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz", - "integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", - "axios": "^1.3.1", - "rxjs": "^6.0.0 || ^7.0.0" - } - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common": { - "version": "10.4.6", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.6.tgz", - "integrity": "sha512-KkezkZvU9poWaNq4L+lNvx+386hpOxPJkfXBBeSMrcqBOx8kVr36TGN2uYkF4Ta4zNu1KbCjmZbc0rhHSg296g==", - "dev": true, - "dependencies": { - "iterare": "1.2.1", - "tslib": "2.7.0", - "uid": "2.0.2" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/nest" - }, - "peerDependencies": { - "class-transformer": "*", - "class-validator": "*", - "reflect-metadata": "^0.1.12 || ^0.2.0", - "rxjs": "^7.1.0" - }, - "peerDependenciesMeta": { - "class-transformer": { - "optional": true - }, - "class-validator": { - "optional": true - } - } - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common/node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", - "dev": true - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/core": { - "version": "10.4.6", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-10.4.6.tgz", - "integrity": "sha512-zXVPxCNRfO6gAy0yvEDjUxE/8gfZICJFpsl2lZAUH31bPb6m+tXuhUq2mVCTEltyMYQ+DYtRe+fEYM2v152N1g==", - "dev": true, - "hasInstallScript": true, - "dependencies": { - "@nuxtjs/opencollective": "0.3.2", - "fast-safe-stringify": "2.1.1", - "iterare": "1.2.1", - "path-to-regexp": "3.3.0", - "tslib": "2.7.0", - "uid": "2.0.2" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/nest" - }, - "peerDependencies": { - "@nestjs/common": "^10.0.0", - "@nestjs/microservices": "^10.0.0", - "@nestjs/platform-express": "^10.0.0", - "@nestjs/websockets": "^10.0.0", - "reflect-metadata": "^0.1.12 || ^0.2.0", - "rxjs": "^7.1.0" - }, - "peerDependenciesMeta": { - "@nestjs/microservices": { - "optional": true - }, - "@nestjs/platform-express": { - "optional": true - }, - "@nestjs/websockets": { - "optional": true - } - } - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/core/node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", - "dev": true - }, "node_modules/@openapitools/openapi-generator-cli/node_modules/brace-expansion": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", @@ -1762,6 +1766,21 @@ "balanced-match": "^1.0.0" } }, + "node_modules/@openapitools/openapi-generator-cli/node_modules/fs-extra": { + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz", + "integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/@openapitools/openapi-generator-cli/node_modules/glob": { "version": "9.3.5", "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", @@ -1804,18 +1823,6 @@ "node": ">=8" } }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/path-to-regexp": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz", - "integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==", - "dev": true - }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/reflect-metadata": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", - "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", - "dev": true - }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -1957,7 +1964,6 @@ "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "debug": "^4.4.0", "fflate": "^0.8.2", @@ -1977,7 +1983,6 @@ "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -1995,8 +2000,7 @@ "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@tootallnate/once": { "version": "2.0.0", @@ -2010,7 +2014,8 @@ "version": "0.23.0", "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@types/body-parser": { "version": "1.19.5", @@ -3076,12 +3081,10 @@ } }, "node_modules/agent-base": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", - "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", - "dependencies": { - "debug": "^4.3.4" - }, + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "license": "MIT", "engines": { "node": ">= 14" } @@ -3341,6 +3344,7 @@ "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", "dev": true, + "license": "MIT", "dependencies": { "tslib": "^2.0.1" }, @@ -3375,9 +3379,10 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.7.7", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz", - "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==", + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", + "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -3432,6 +3437,7 @@ "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", "dev": true, + "license": "MIT", "engines": { "node": ">=10.0.0" } @@ -4604,10 +4610,14 @@ } }, "node_modules/consola": { - "version": "2.15.3", - "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", - "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", - "dev": true + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } }, "node_modules/console-control-strings": { "version": "1.1.0", @@ -4970,6 +4980,7 @@ "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", "dev": true, + "license": "MIT", "dependencies": { "ast-types": "^0.13.4", "escodegen": "^2.1.0", @@ -5458,6 +5469,7 @@ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", @@ -5479,6 +5491,7 @@ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -5647,6 +5660,7 @@ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true, + "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", "esvalidate": "bin/esvalidate.js" @@ -5954,7 +5968,8 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/fastq": { "version": "1.17.1", @@ -5999,8 +6014,7 @@ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/figures": { "version": "3.2.0", @@ -6044,7 +6058,6 @@ "integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@tokenizer/inflate": "^0.2.6", "strtok3": "^10.2.0", @@ -6489,15 +6502,15 @@ } }, "node_modules/get-uri": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz", - "integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==", + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.4.tgz", + "integrity": "sha512-E1b1lFFLvLgak2whF2xDBcOy6NLVGZBqqjJjsIhvopKfWWEi64pLVTWWehV8KlLerZkfNTA95sTe2OdJKm1OzQ==", "dev": true, + "license": "MIT", "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", - "debug": "^4.3.4", - "fs-extra": "^11.2.0" + "debug": "^4.3.4" }, "engines": { "node": ">= 14" @@ -6508,24 +6521,11 @@ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", "dev": true, + "license": "MIT", "engines": { "node": ">= 14" } }, - "node_modules/get-uri/node_modules/fs-extra": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", - "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", - "dev": true, - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=14.14" - } - }, "node_modules/getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", @@ -6984,11 +6984,12 @@ } }, "node_modules/https-proxy-agent": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", - "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", "dependencies": { - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "4" }, "engines": { @@ -7919,6 +7920,26 @@ "uc.micro": "^1.0.1" } }, + "node_modules/load-esm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.2.tgz", + "integrity": "sha512-nVAvWk/jeyrWyXEAs84mpQCYccxRqgKY4OznLuJhJCa0XsPSfdOIr2zvBZEj3IHEHbX97jjscKRRV539bW0Gpw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "engines": { + "node": ">=13.2.0" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -9265,6 +9286,7 @@ "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.4.0" } @@ -9963,31 +9985,33 @@ } }, "node_modules/pac-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.0.2.tgz", - "integrity": "sha512-BFi3vZnO9X5Qt6NRz7ZOaPja3ic0PhlsmCRYLOpN11+mWBCR6XJDqW5RF3j8jm4WGGQZtBA+bTfxYzeKW73eHg==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", "dev": true, + "license": "MIT", "dependencies": { "@tootallnate/quickjs-emscripten": "^0.23.0", - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "^4.3.4", "get-uri": "^6.0.1", "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.5", + "https-proxy-agent": "^7.0.6", "pac-resolver": "^7.0.1", - "socks-proxy-agent": "^8.0.4" + "socks-proxy-agent": "^8.0.5" }, "engines": { "node": ">= 14" } }, "node_modules/pac-proxy-agent/node_modules/socks-proxy-agent": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", - "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "^7.1.1", + "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" }, @@ -10000,6 +10024,7 @@ "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", "dev": true, + "license": "MIT", "dependencies": { "degenerator": "^5.0.0", "netmask": "^2.0.2" @@ -10192,7 +10217,6 @@ "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -10678,19 +10702,20 @@ } }, "node_modules/proxy-agent": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.4.0.tgz", - "integrity": "sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==", + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", + "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "^4.3.4", "http-proxy-agent": "^7.0.1", - "https-proxy-agent": "^7.0.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^7.14.1", - "pac-proxy-agent": "^7.0.1", + "pac-proxy-agent": "^7.1.0", "proxy-from-env": "^1.1.0", - "socks-proxy-agent": "^8.0.2" + "socks-proxy-agent": "^8.0.5" }, "engines": { "node": ">= 14" @@ -10701,17 +10726,19 @@ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", "dev": true, + "license": "ISC", "engines": { "node": ">=12" } }, "node_modules/proxy-agent/node_modules/socks-proxy-agent": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", - "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "^7.1.1", + "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" }, @@ -11075,11 +11102,11 @@ } }, "node_modules/reflect-metadata": { - "version": "0.1.14", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.14.tgz", - "integrity": "sha512-ZhYeb6nRaXCfhnndflDK8qI6ZQ/YcWZCISRAWICW9XYqMUwjZM9Z0DveWX/ABN01oxSHwVxKQmxeYZSsm0jh5A==", + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", "dev": true, - "peer": true + "license": "Apache-2.0" }, "node_modules/regenerator-runtime": { "version": "0.14.1", @@ -11416,10 +11443,11 @@ "integrity": "sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA==" }, "node_modules/rxjs": { - "version": "7.8.1", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", - "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "dev": true, + "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" } @@ -12166,7 +12194,6 @@ "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@tokenizer/token": "^0.3.0", "peek-readable": "^7.0.0" @@ -12822,7 +12849,6 @@ "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" @@ -13080,7 +13106,6 @@ "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 4ea6bddfd..a70995944 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -631,7 +631,7 @@ "devDependencies": { "@biomejs/biome": "1.6.4", "@nestjs/common": "^11.0.16", - "@openapitools/openapi-generator-cli": "^2.5.2", + "@openapitools/openapi-generator-cli": "^2.20.0", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", From 1a47f962596722a9b4bc347e32c945af290efb0e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 15 May 2025 18:45:55 -0700 Subject: [PATCH 05/38] catch client abort errors --- core/llm/index.ts | 3 + core/llm/llms/Anthropic.ts | 5 ++ core/llm/llms/Asksage.ts | 12 +-- core/llm/llms/Cohere.ts | 4 + core/llm/llms/Flowise.ts | 10 ++- core/llm/llms/Gemini.ts | 4 + core/llm/llms/Ollama.ts | 4 + core/llm/llms/OpenAI.ts | 4 + core/llm/llms/VertexAI.ts | 26 +++++- core/llm/llms/WatsonX.ts | 88 +++++++++------------ core/llm/stream.ts | 39 +++++---- extensions/vscode/src/commands.ts | 6 ++ manual-testing-sandbox/AdvancedPage.tsx | 5 +- packages/fetch/src/fetch.ts | 35 +++++--- packages/fetch/src/stream.ts | 38 +++++---- packages/openai-adapters/src/apis/Relace.ts | 4 + 16 files changed, 176 insertions(+), 111 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index 96fdb319c..68623d2e2 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -382,6 +382,9 @@ export abstract class BaseLLM implements ILLM { // Error mapping to be more helpful if (!resp.ok) { + if (resp.status === 499) { + return resp; // client side cancellation + } let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { const error = JSON.parse(text)?.error?.replace(/"/g, "'"); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 5bec42d49..00a97b826 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -213,6 +213,11 @@ class Anthropic extends BaseLLM { signal, }); + if (response.status === 499) { + // Aborted by user + return; + } + if (!response.ok) { const json = await response.json(); if (json.type === "error") { diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 59554efe5..988c57ac6 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -134,10 +134,8 @@ class Asksage extends BaseLLM { body: JSON.stringify(args), }); - if (!response.ok) { - throw new Error( - `API request failed with status ${response.status}: ${response.statusText}`, - ); + if (response.status === 499) { + return ""; // Aborted by user } const data = await response.json(); @@ -167,10 +165,8 @@ class Asksage extends BaseLLM { signal, }); - if (!response.ok) { - throw new Error( - `API request failed with status ${response.status}: ${response.statusText}`, - ); + if (response.status === 499) { + return; // Aborted by user } const data = await response.json(); diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index ecc9c5208..17b5e4352 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -84,6 +84,10 @@ class Cohere extends BaseLLM { signal, }); + if (resp.status === 499) { + return; // Aborted by user + } + if (options.stream === false) { const data = await resp.json(); yield { role: "assistant", content: data.text }; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index cdc4f8f77..57bb18ccc 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -132,12 +132,16 @@ class Flowise extends BaseLLM { ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); const { socket, socketInfo } = await this._initializeSocket(); - const request = this.fetch(this._getChatUrl(), { + const response = await this.fetch(this._getChatUrl(), { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), signal, - }).then((res) => res.json()); + }); + + if (response.status === 499) { + return; // Aborted by user + } while (await socketInfo.hasNextToken()) { yield { role: "assistant", content: socketInfo.getCurrentMessage() }; @@ -145,7 +149,7 @@ class Flowise extends BaseLLM { if (socketInfo.error) { socket.disconnect(); try { - yield { role: "assistant", content: (await request).text }; + yield { role: "assistant", content: await response.text() }; } catch (error: any) { yield { role: "assistant", content: (error as Error).message ?? error }; } diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1e3c35449..4e8d4ff49 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -438,6 +438,10 @@ class Gemini extends BaseLLM { body: JSON.stringify(body), signal, }); + if (response.status === 499) { + // Aborted by user + return; + } const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index cd312c681..398f42ae5 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -457,6 +457,10 @@ class Ollama extends BaseLLM implements ModelInstaller { } if (chatOptions.stream === false) { + if (response.status === 499) { + // Aborted by user + return; + } const json = (await response.json()) as OllamaChatResponse; yield convertChatMessage(json); } else { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index f6dbc2bf3..4c476f45a 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -352,6 +352,10 @@ class OpenAI extends BaseLLM { // Handle non-streaming response if (body.stream === false) { + if (response.status === 499) { + // Aborted by user + return; + } const data = await response.json(); yield data.choices[0].message; return; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index cc1b70b19..3c49523fb 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -95,6 +95,7 @@ class VertexAI extends BaseLLM { protected async *StreamChatAnthropic( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const systemMessage = stripImages( messages.filter((m) => m.role === "system")[0]?.content ?? "", @@ -128,8 +129,13 @@ class VertexAI extends BaseLLM { ] : systemMessage, }), + signal, }); + if (response.status === 499) { + return; // Aborted by user + } + if (options.stream === false) { const data = await response.json(); yield { role: "assistant", content: data.content[0].text }; @@ -150,6 +156,7 @@ class VertexAI extends BaseLLM { private async *streamChatGemini( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const apiURL = new URL( `publishers/google/models/${options.model}:streamGenerateContent`, @@ -160,6 +167,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal, }); for await (const message of this.geminiInstance.processGeminiResponse( streamResponse(response), @@ -171,6 +179,7 @@ class VertexAI extends BaseLLM { private async *streamChatBison( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const instances = messages.map((message) => ({ prompt: message.content })); @@ -193,7 +202,11 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal, }); + if (response.status === 499) { + return; // Aborted by user + } const data = await response.json(); yield { role: "assistant", content: data.predictions[0].content }; } @@ -203,6 +216,7 @@ class VertexAI extends BaseLLM { protected async *StreamChatMistral( messages: ChatMessage[], options: CompletionOptions, + signal: AbortSignal, ): AsyncGenerator { const apiBase = this.apiBase!; const apiURL = new URL( @@ -228,6 +242,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal, }); for await (const chunk of streamSse(response)) { @@ -304,6 +319,9 @@ class VertexAI extends BaseLLM { }), signal, }); + if (resp.status === 499) { + return; // Aborted by user + } // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. yield (await resp.json()).predictions[0].content; @@ -323,14 +341,14 @@ class VertexAI extends BaseLLM { ? this.geminiInstance.removeSystemMessage(messages) : messages; if (this.vertexProvider === "gemini") { - yield* this.streamChatGemini(convertedMsgs, options); + yield* this.streamChatGemini(convertedMsgs, options, signal); } else if (this.vertexProvider === "mistral") { - yield* this.StreamChatMistral(messages, options); + yield* this.StreamChatMistral(messages, options, signal); } else if (this.vertexProvider === "anthropic") { - yield* this.StreamChatAnthropic(messages, options); + yield* this.StreamChatAnthropic(messages, options, signal); } else { if (options.model.includes("bison")) { - yield* this.streamChatBison(convertedMsgs, options); + yield* this.streamChatBison(convertedMsgs, options, signal); } else { throw new Error(`Unsupported model: ${options.model}`); } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 49b2f9ce8..0db209ca2 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -4,11 +4,8 @@ import { CompletionOptions, LLMOptions, } from "../../index.js"; -import { - fromChatCompletionChunk, -} from "../openaiTypeConverters.js"; -import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; +import { fromChatCompletionChunk } from "../openaiTypeConverters.js"; import { streamResponse, streamSse } from "../stream.js"; let watsonxToken = { @@ -86,7 +83,7 @@ class WatsonX extends BaseLLM { } _getEndpoint(endpoint: string): string { - return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}` + return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`; } static providerName = "watsonx"; @@ -182,7 +179,6 @@ class WatsonX extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - await this.updateWatsonxToken(); const stopSequences = options.stop?.slice(0, 6) ?? []; @@ -214,44 +210,38 @@ class WatsonX extends BaseLLM { payload.project_id = this.projectId; } - var response = await this.fetch(url, { + const response = await this.fetch(url, { method: "POST", headers: headers, body: JSON.stringify(payload), signal, }); - if (!response.ok || response.body === null) { - throw new Error( - "Something went wrong. No response received, check your connection", - ); - } else { - for await (const value of streamResponse(response)) { - const lines = value.split("\n"); - let generatedChunk = ""; - let generatedTextIndex = undefined; - lines.forEach((el: string) => { - // console.log(`${el}`); - if (el.startsWith("id:")) { - generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); - if (isNaN(generatedTextIndex)) { - console.error(`Unable to parse stream chunk ID: ${el}`); - } - } else if (el.startsWith("data:")) { - const dataStr = el.replace(/^data:\s+/, ""); - try { - const data = JSON.parse(dataStr); - data.results.forEach((result: any) => { - generatedChunk += result.generated_text || ""; - }); - } catch (e) { - // parsing error is expected with streaming response - // console.error(`Error parsing JSON string: ${dataStr}`, e); - } + for await (const value of streamResponse(response)) { + const lines = value.split("\n"); + let generatedChunk = ""; + let generatedTextIndex = undefined; + lines.forEach((el: string) => { + // console.log(`${el}`); + if (el.startsWith("id:")) { + generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); + if (isNaN(generatedTextIndex)) { + console.error(`Unable to parse stream chunk ID: ${el}`); } - }); - yield generatedChunk - } + } else if (el.startsWith("data:")) { + const dataStr = el.replace(/^data:\s+/, ""); + try { + const data = JSON.parse(dataStr); + data.results.forEach((result: any) => { + generatedChunk += result.generated_text || ""; + }); + } catch (e) { + // parsing error is expected with streaming response + // console.error(`Error parsing JSON string: ${dataStr}`, e); + } + } + }); + yield generatedChunk; } } @@ -267,7 +257,7 @@ class WatsonX extends BaseLLM { const headers = this._getHeaders(); const payload: any = { - messages: messages, + messages: messages, max_tokens: options.maxTokens ?? 1024, stop: stopSequences, frequency_penalty: options.frequencyPenalty || 1, @@ -281,36 +271,30 @@ class WatsonX extends BaseLLM { if (!!options.temperature) { payload.temperature = options.temperature; - } + } if (!!options.topP) { payload.top_p = options.topP; } if (!!options.tools) { payload.tools = options.tools; if (options.toolChoice) { - payload.tool_choice = options.toolChoice; + payload.tool_choice = options.toolChoice; } else { - payload.tool_choice_option = "auto"; + payload.tool_choice_option = "auto"; } } - var response = await this.fetch(url, { + const response = await this.fetch(url, { method: "POST", headers: headers, body: JSON.stringify(payload), signal, }); - if (!response.ok || response.body === null) { - throw new Error( - "Something went wrong. No response received, check your connection", - ); - } else { - for await (const value of streamSse(response)) { - const chunk = fromChatCompletionChunk(value); - if (chunk) { - yield chunk; - } + for await (const value of streamSse(response)) { + const chunk = fromChatCompletionChunk(value); + if (chunk) { + yield chunk; } } } diff --git a/core/llm/stream.ts b/core/llm/stream.ts index 0a014d931..dd0983605 100644 --- a/core/llm/stream.ts +++ b/core/llm/stream.ts @@ -10,6 +10,10 @@ async function* toAsyncIterable( export async function* streamResponse( response: Response, ): AsyncGenerator { + if (response.status === 499) { + return; // In case of client-side cancellation, just return + } + if (response.status !== 200) { throw new Error(await response.text()); } @@ -21,22 +25,29 @@ export async function* streamResponse( // Get the major version of Node.js const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10); - if (nodeMajorVersion >= 20) { - // Use the new API for Node 20 and above - const stream = (ReadableStream as any).from(response.body); - for await (const chunk of stream.pipeThrough( - new TextDecoderStream("utf-8"), - )) { - yield chunk; + try { + if (nodeMajorVersion >= 20) { + // Use the new API for Node 20 and above + const stream = (ReadableStream as any).from(response.body); + for await (const chunk of stream.pipeThrough( + new TextDecoderStream("utf-8"), + )) { + yield chunk; + } + } else { + // Fallback for Node versions below 20 + // Streaming with this method doesn't work as version 20+ does + const decoder = new TextDecoder("utf-8"); + const nodeStream = response.body as unknown as NodeJS.ReadableStream; + for await (const chunk of toAsyncIterable(nodeStream)) { + yield decoder.decode(chunk, { stream: true }); + } } - } else { - // Fallback for Node versions below 20 - // Streaming with this method doesn't work as version 20+ does - const decoder = new TextDecoder("utf-8"); - const nodeStream = response.body as unknown as NodeJS.ReadableStream; - for await (const chunk of toAsyncIterable(nodeStream)) { - yield decoder.decode(chunk, { stream: true }); + } catch (e) { + if (e instanceof Error && e.name.startsWith("AbortError")) { + return; // In case of client-side cancellation, just return } + throw e; } } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index cb312a101..84885f757 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -97,6 +97,7 @@ async function processDiff( action: "accept" | "reject", sidebar: ContinueGUIWebviewViewProvider, ide: VsCodeIde, + core: Core, verticalDiffManager: VerticalDiffManager, newFileUri?: string, streamId?: string, @@ -121,6 +122,9 @@ async function processDiff( // Clear vertical diffs depending on action verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); + if (action === "reject") { + core.invoke("cancelApply", undefined); + } if (streamId) { const fileContent = await ide.readFile(newOrCurrentUri); @@ -236,6 +240,7 @@ const getCommandsMap: ( "accept", sidebar, ide, + core, verticalDiffManager, newFileUri, streamId, @@ -246,6 +251,7 @@ const getCommandsMap: ( "reject", sidebar, ide, + core, verticalDiffManager, newFileUri, streamId, diff --git a/manual-testing-sandbox/AdvancedPage.tsx b/manual-testing-sandbox/AdvancedPage.tsx index 9f7d321ec..e75004bb1 100644 --- a/manual-testing-sandbox/AdvancedPage.tsx +++ b/manual-testing-sandbox/AdvancedPage.tsx @@ -13,10 +13,7 @@ const AdvancedPage = () => { className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`} >
- I apologize, but there seems to be a misunderstanding. The user's - request doesn't appear to be related to rewriting the code section you - provided. The request mentions editing a readme.md file, which is not - part of the React component code you've shown. + {" "} + + ); +}; + +describe("FindWidget", () => { + beforeEach(() => { + // Reset window size and scroll position + window.innerHeight = 768; + window.innerWidth = 1024; + }); + + it("should open search widget and find matches", async () => { + render(); + + // Open search widget + const openButton = screen.getByText("Open Search"); + fireEvent.click(openButton); + + // Find search input + const searchInput = screen.getByPlaceholderText("Search..."); + expect(searchInput).toBeInTheDocument(); + + // Type search term + await act(async () => { + fireEvent.change(searchInput, { target: { value: "test" } }); + // Wait for debounce + await new Promise((resolve) => setTimeout(resolve, 350)); + }); + + // Check if matches are found (should find 2 instances of "test") + const matchCount = screen.getByText("1 of 2"); + expect(matchCount).toBeInTheDocument(); + + // Test case sensitivity toggle + const caseSensitiveButton = screen.getByText("Aa"); + fireEvent.click(caseSensitiveButton); + + // Check highlight elements + const highlights = document.querySelectorAll( + ".bg-findMatch\\/50, .bg-findMatch-selected\\/50", + ); + expect(highlights.length).toBe(2); + }); + + it("should navigate between matches", async () => { + render( + // + , + // + ); + + // Open search and type + fireEvent.click(screen.getByText("Open Search")); + const searchInput = screen.getByPlaceholderText("Search..."); + + await act(async () => { + fireEvent.change(searchInput, { target: { value: "test" } }); + await new Promise((resolve) => setTimeout(resolve, 350)); + }); + + // Find navigation buttons + const nextButton = screen.getByText("Next Match"); + const prevButton = screen.getByText("Previous Match"); + + // Navigate through matches + fireEvent.click(nextButton); + expect(screen.getByText("2 of 2")).toBeInTheDocument(); + + fireEvent.click(prevButton); + expect(screen.getByText("1 of 2")).toBeInTheDocument(); + }); +}); diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index a0f5a8e90..c7e6dcb96 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -12,7 +12,6 @@ import { useState, } from "react"; import { HeaderButton, Input } from ".."; -import { useAppSelector } from "../../redux/hooks"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; interface SearchMatch { @@ -67,7 +66,8 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { export const useFindWidget = ( searchRef: RefObject, headerRef: RefObject, - dependencies: React.DependencyList, + refreshDependencies: React.DependencyList, + disabled: boolean, ) => { // Search input, debounced const [input, setInput] = useState(""); @@ -329,7 +329,7 @@ export const useFindWidget = ( scrollToMatch, caseSensitive, useRegex, - ...dependencies, + ...refreshDependencies, ], ); @@ -369,14 +369,10 @@ export const useFindWidget = ( }; }, [searchRef, refreshSearch, open]); - // Triggers that should cause results to temporarily disappear and then reload - // Active = LLM is generating, etc. - const active = useAppSelector((state) => state.session.isStreaming); - useEffect(() => { - if (active || isResizing) setMatches([]); + if (disabled || isResizing) setMatches([]); else setTimeout(() => refreshSearch("none"), 300); // this gives plenty of time for resizing to finish - }, [refreshSearch, active, isResizing]); + }, [refreshSearch, disabled, isResizing]); useEffect(() => { if (!open) setMatches([]); @@ -394,7 +390,7 @@ export const useFindWidget = ( 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`} > @@ -429,13 +425,13 @@ export const useFindWidget = ( nextMatch(); }} className="h-4 w-4 focus:ring" - disabled={matches.length < 2 || active} + disabled={matches.length < 2 || disabled} > { + if (clearFirst) setMatches([]); + + const searchContainer = searchRef.current; + const header = headerRef.current; + + const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable + if (!searchContainer || !_query) { + setMatches([]); + return; + } + const query = caseSensitive ? _query : _query.toLowerCase(); + + // First grab all text nodes + // Skips any elements with the "find-widget-skip" class + const textNodes: Text[] = []; + const walker = document.createTreeWalker( + searchRef.current, + NodeFilter.SHOW_ALL, + { + acceptNode: (node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + if ((node as Element).classList.contains("find-widget-skip")) + return NodeFilter.FILTER_REJECT; + return NodeFilter.FILTER_ACCEPT; + } else if (node.nodeType === Node.TEXT_NODE) { + if (!node.nodeValue) return NodeFilter.FILTER_REJECT; + const nodeValue = caseSensitive + ? node.nodeValue + : node.nodeValue.toLowerCase(); + if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; + } + return NodeFilter.FILTER_REJECT; + }, + }, + ); + + while (walker.nextNode()) { + if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; + textNodes.push(walker.currentNode as Text); + } + + // Now walk through each node match and extract search results + // One node can have several matches + const newMatches: SearchMatch[] = []; + textNodes.forEach((textNode, idx) => { + // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail + const highlightFullLine = + textNode.parentElement?.className.includes("hljs"); + + let nodeTextValue = caseSensitive + ? textNode.nodeValue + : textNode.nodeValue.toLowerCase(); + let startIndex = 0; + while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { + // Create a range to measure the size and position of the match + const range = document.createRange(); + range.setStart(textNode, startIndex); + const endIndex = startIndex + query.length; + range.setEnd(textNode, endIndex); + const rect = range.getBoundingClientRect(); + range.detach(); + startIndex = endIndex; + + const headerHeight = header?.clientHeight ?? 0; + + const top = + rect.top + + searchContainer.clientTop + + searchContainer.scrollTop - + headerHeight; + const left = + rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; + + // Build a match result and push to matches + const newMatch: SearchMatch = { + index: 0, // will set later + textNode, + overlayRectangle: { + top, + left: highlightFullLine ? 2 : left, + width: highlightFullLine + ? searchContainer.clientWidth - 4 + : rect.width, // equivalent of adding 2 px x padding + height: rect.height, + }, + }; + newMatches.push(newMatch); + + if (highlightFullLine) { + break; // Since highlighting full line no need for multiple overlays, will cause darker highlight + } + } + }); + + // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) + // Filter them out by using the overlay rectangle as a hash key + const matchHash = Object.fromEntries( + newMatches.map((match) => [ + JSON.stringify(match.overlayRectangle), + match, + ]), + ); + const filteredMatches = Object.values(matchHash).map((match, index) => ({ + ...match, + index, + })); + + // Find match closest to the middle of the view + const verticalMiddle = + searchRef.current.scrollTop + searchRef.current.clientHeight / 2; + let closestDist = Infinity; + let closestMatchToMiddle: SearchMatch | null = null; + filteredMatches.forEach((match) => { + const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); + if (dist < closestDist) { + closestDist = dist; + closestMatchToMiddle = match; + } + }); + + // Update matches and scroll to the closest or first match + setMatches(filteredMatches); + if (query.length > 1 && filteredMatches.length) { + if (scrollTo === "first") { + scrollToMatch(filteredMatches[0]); + } + if (scrollTo === "closest") { + if (closestMatchToMiddle) { + scrollToMatch(closestMatchToMiddle); + } + } + if (scrollTo === "none") { + if (closestMatchToMiddle) { + setCurrentMatch(closestMatchToMiddle); + } else { + setCurrentMatch(filteredMatches[0]); + } + } + } + }, + [ + headerRef, + searchRef, + debouncedInput, + scrollToMatch, + caseSensitive, + useRegex, + ...refreshDependencies, + ], +} \ No newline at end of file diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 0b16934c5..6297643fd 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -153,7 +153,12 @@ export function Chat() { }; }, [isStreaming, jetbrains]); - const { widget, highlights } = useFindWidget(stepsDivRef, tabsRef, [history]); + const { widget, highlights } = useFindWidget( + stepsDivRef, + tabsRef, + [history], + isStreaming, + ); const currentToolCallApplyState = useAppSelector( selectCurrentToolCallApplyState, From ecb63a0222c7ae5e051bea02d98a4a2de7c1e2e5 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 23 May 2025 14:37:07 -0700 Subject: [PATCH 36/38] feat: improve StreamError dialog --- gui/src/pages/gui/StreamError.tsx | 129 +++++++++++++++++++----------- 1 file changed, 84 insertions(+), 45 deletions(-) diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 50caf7dfe..7d5f652bf 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -1,12 +1,15 @@ import { ArrowTopRightOnSquareIcon, - Cog8ToothIcon, + ClipboardIcon, + Cog6ToothIcon, + KeyIcon, } from "@heroicons/react/24/outline"; import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; import { useContext, useMemo } from "react"; -import { Button, SecondaryButton } from "../../components"; +import { GhostButton, SecondaryButton } from "../../components"; import { DiscordIcon } from "../../components/svg/DiscordIcon"; import { GithubIcon } from "../../components/svg/GithubIcon"; +import ToggleDiv from "../../components/ToggleDiv"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { selectSelectedProfile } from "../../redux/"; @@ -48,11 +51,15 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); const handleRefreshProfiles = () => { - refreshProfiles(); + void refreshProfiles(); dispatch(setShowDialog(false)); dispatch(setDialogMessage(undefined)); }; + const copyErrorToClipboard = () => { + void navigator.clipboard.writeText(parsedError); + }; + // Collect model information to display useful error info let modelTitle = "Chat model"; let providerName = "the model provider"; @@ -99,30 +106,29 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { } const checkKeysButton = apiKeyUrl ? ( - + + View key + ) : null; const configButton = ( - { ideMessenger.post("config/openProfile", { profileId: undefined, }); }} > -
- -
- Open Assistant configuration -
+ + View config + ); if ( @@ -131,7 +137,20 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { return ; } - let errorContent: React.ReactNode = <>; + let errorContent = ( +
+
+

+ There was an error handling the response from{" "} + {selectedModel?.title || "the model"}. +

+

+ Please try to submit your message again, and if the error persists, + let us know by reporting the issue using the buttons below. +

+
+
+ ); // Display components for specific errors if (statusCode === 429) { @@ -141,7 +160,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { {`This might mean your ${modelTitle} usage has been rate limited by ${providerName}.`} -
+
{checkKeysButton} {configButton}
@@ -230,51 +249,71 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); } + console.log({ message }); + return ( -
-

- {statusCode ? `Error (status code ${statusCode})` : "Error"} -

+
+ {/* Concise error title */} +

+ Error handling model response +

- {message ? ( -
- - {parsedError} - -
{ - ideMessenger.post("toggleDevTools", undefined); - }} - > - View Logs - -
+ {errorContent} + + {/* Expandable technical details using ToggleDiv */} + {message && ( +
+ +
+ + {parsedError} + + +
+ + + Copy output + + + { + ideMessenger.post("toggleDevTools", undefined); + }} + className="flex items-center" + > + + View Logs + +
+
+
- ) : null} -
{errorContent}
+ )} -
- Report this error: -
- + Report this error +
+ { ideMessenger.post("openUrl", GITHUB_LINK); }} > Github - - + { ideMessenger.post("openUrl", DISCORD_LINK); }} > Discord - +
From c36391f436a28924ab79e7c425feae1b7948069b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 23 May 2025 15:48:58 -0700 Subject: [PATCH 37/38] find widget cleanup --- gui/src/components/find/FindWidget.test.tsx | 105 ----- gui/src/components/find/FindWidget.tsx | 427 +++++-------------- gui/src/components/find/findWidgetSearch.ts | 279 ++++++------ gui/src/components/find/useDebouncedInput.ts | 48 +++ gui/src/components/find/useElementDims.ts | 42 ++ 5 files changed, 340 insertions(+), 561 deletions(-) delete mode 100644 gui/src/components/find/FindWidget.test.tsx create mode 100644 gui/src/components/find/useDebouncedInput.ts create mode 100644 gui/src/components/find/useElementDims.ts diff --git a/gui/src/components/find/FindWidget.test.tsx b/gui/src/components/find/FindWidget.test.tsx deleted file mode 100644 index 8f05a4d86..000000000 --- a/gui/src/components/find/FindWidget.test.tsx +++ /dev/null @@ -1,105 +0,0 @@ -import { act, fireEvent, render, screen } from "@testing-library/react"; -import { useRef } from "react"; -import { useFindWidget } from "./FindWidget"; - -// Test component that uses the find widget -const TestComponent = () => { - const searchRef = useRef(null); - const headerRef = useRef(null); - - const { widget, highlights, open, setOpen } = useFindWidget( - searchRef, - headerRef, - [], - false, - ); - - return ( -
- {widget} -
- Header Content -
-
-

This is a test paragraph

-

We can search for content here

-

Multiple instances of test should work

- {highlights} -
- -
- ); -}; - -describe("FindWidget", () => { - beforeEach(() => { - // Reset window size and scroll position - window.innerHeight = 768; - window.innerWidth = 1024; - }); - - it("should open search widget and find matches", async () => { - render(); - - // Open search widget - const openButton = screen.getByText("Open Search"); - fireEvent.click(openButton); - - // Find search input - const searchInput = screen.getByPlaceholderText("Search..."); - expect(searchInput).toBeInTheDocument(); - - // Type search term - await act(async () => { - fireEvent.change(searchInput, { target: { value: "test" } }); - // Wait for debounce - await new Promise((resolve) => setTimeout(resolve, 350)); - }); - - // Check if matches are found (should find 2 instances of "test") - const matchCount = screen.getByText("1 of 2"); - expect(matchCount).toBeInTheDocument(); - - // Test case sensitivity toggle - const caseSensitiveButton = screen.getByText("Aa"); - fireEvent.click(caseSensitiveButton); - - // Check highlight elements - const highlights = document.querySelectorAll( - ".bg-findMatch\\/50, .bg-findMatch-selected\\/50", - ); - expect(highlights.length).toBe(2); - }); - - it("should navigate between matches", async () => { - render( - // - , - // - ); - - // Open search and type - fireEvent.click(screen.getByText("Open Search")); - const searchInput = screen.getByPlaceholderText("Search..."); - - await act(async () => { - fireEvent.change(searchInput, { target: { value: "test" } }); - await new Promise((resolve) => setTimeout(resolve, 350)); - }); - - // Find navigation buttons - const nextButton = screen.getByText("Next Match"); - const prevButton = screen.getByText("Previous Match"); - - // Navigate through matches - fireEvent.click(nextButton); - expect(screen.getByText("2 of 2")).toBeInTheDocument(); - - fireEvent.click(prevButton); - expect(screen.getByText("1 of 2")).toBeInTheDocument(); - }); -}); diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index c7e6dcb96..a6b35acbd 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -3,44 +3,27 @@ import { ArrowUpIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { - RefObject, - useCallback, - useEffect, - useMemo, - useRef, - useState, -} from "react"; +import { RefObject, useCallback, useEffect, useMemo, useState } from "react"; import { HeaderButton, Input } from ".."; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { + Rectangle, + SearchMatch, + searchWithinContainer, +} from "./findWidgetSearch"; +import { useDebouncedInput } from "./useDebouncedInput"; +import { useElementSize } from "./useElementDims"; -interface SearchMatch { - index: number; - textNode: Text; - overlayRectangle: Rectangle; -} - -type ScrollToMatchOption = "closest" | "first" | "none"; - -const SEARCH_DEBOUNCE = 300; -const RESIZE_DEBOUNCE = 200; - -interface Rectangle { - top: number; - left: number; - width: number; - height: number; -} - -interface HighlightOverlayProps extends Rectangle { +interface HighlightOverlayProps { + rectangle: Rectangle; isCurrent: boolean; } const HighlightOverlay = (props: HighlightOverlayProps) => { - const { isCurrent, top, left, width, height } = props; + const { top, left, width, height } = props.rectangle; return (
{ ); }; +type ScrollToMatchOption = "closest" | "first" | "none"; + /* useFindWidget takes a container ref and returns 1. A widget that can be placed anywhere to search the contents of that container @@ -70,16 +55,18 @@ export const useFindWidget = ( disabled: boolean, ) => { // Search input, debounced - const [input, setInput] = useState(""); - const debouncedInput = useRef(""); - const inputRef = useRef(null); + const { + inputRef, + debouncedValue: searchTerm, + currentValue, + } = useDebouncedInput(); // Widget open/closed state const [open, setOpen] = useState(false); const openWidget = useCallback(() => { setOpen(true); inputRef?.current?.select(); - }, [setOpen, inputRef]); + }, [inputRef]); // Search settings and results const [caseSensitive, setCaseSensitive] = useState(false); @@ -147,221 +134,75 @@ export const useFindWidget = ( }, [inputRef, matches, nextMatch]); // Handle container resize changes - highlight positions must adjust - const [isResizing, setIsResizing] = useState(false); - useEffect(() => { - let timeoutId: NodeJS.Timeout | null = null; - if (!searchRef?.current) return; - - const resizeObserver = new ResizeObserver((entries) => { - if (timeoutId) { - clearTimeout(timeoutId); - } - setIsResizing(true); - timeoutId = setTimeout(() => { - setIsResizing(false); - }, RESIZE_DEBOUNCE); - }); - - resizeObserver.observe(searchRef.current); - if (headerRef.current) { - resizeObserver.observe(headerRef.current); - } - return () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - if (searchRef.current) { - resizeObserver.unobserve(searchRef.current); - } - if (headerRef.current) { - resizeObserver.unobserve(headerRef.current); - } - }; - }, [searchRef, headerRef]); + const headerSize = useElementSize(headerRef); + const containerSize = useElementSize(searchRef); + const isResizing = useMemo(() => { + return containerSize.isResizing || headerSize.isResizing; + }, [containerSize, headerSize]); + const headerHeight = useMemo(() => { + return headerSize.size.height; + }, [headerSize]); // Main function for finding matches and generating highlight overlays const refreshSearch = useCallback( - (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { - if (clearFirst) setMatches([]); - - const searchContainer = searchRef.current; - const header = headerRef.current; - - const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable - if (!searchContainer || !_query) { - setMatches([]); - return; - } - const query = caseSensitive ? _query : _query.toLowerCase(); - - // First grab all text nodes - // Skips any elements with the "find-widget-skip" class - const textNodes: Text[] = []; - const walker = document.createTreeWalker( - searchRef.current, - NodeFilter.SHOW_ALL, + (scrollTo: ScrollToMatchOption = "none") => { + const { results, closestToMiddle } = searchWithinContainer( + searchRef, + searchTerm, { - acceptNode: (node) => { - if (node.nodeType === Node.ELEMENT_NODE) { - if ((node as Element).classList.contains("find-widget-skip")) - return NodeFilter.FILTER_REJECT; - return NodeFilter.FILTER_ACCEPT; - } else if (node.nodeType === Node.TEXT_NODE) { - if (!node.nodeValue) return NodeFilter.FILTER_REJECT; - const nodeValue = caseSensitive - ? node.nodeValue - : node.nodeValue.toLowerCase(); - if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; - } - return NodeFilter.FILTER_REJECT; - }, + caseSensitive, + useRegex, + offsetHeight: headerHeight, }, ); - - while (walker.nextNode()) { - if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; - textNodes.push(walker.currentNode as Text); - } - - // Now walk through each node match and extract search results - // One node can have several matches - const newMatches: SearchMatch[] = []; - textNodes.forEach((textNode, idx) => { - // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail - const highlightFullLine = - textNode.parentElement?.className.includes("hljs"); - - let nodeTextValue = caseSensitive - ? textNode.nodeValue - : textNode.nodeValue.toLowerCase(); - let startIndex = 0; - while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { - // Create a range to measure the size and position of the match - const range = document.createRange(); - range.setStart(textNode, startIndex); - const endIndex = startIndex + query.length; - range.setEnd(textNode, endIndex); - const rect = range.getBoundingClientRect(); - range.detach(); - startIndex = endIndex; - - const headerHeight = header?.clientHeight ?? 0; - - const top = - rect.top + - searchContainer.clientTop + - searchContainer.scrollTop - - headerHeight; - const left = - rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; - - // Build a match result and push to matches - const newMatch: SearchMatch = { - index: 0, // will set later - textNode, - overlayRectangle: { - top, - left: highlightFullLine ? 2 : left, - width: highlightFullLine - ? searchContainer.clientWidth - 4 - : rect.width, // equivalent of adding 2 px x padding - height: rect.height, - }, - }; - newMatches.push(newMatch); - - if (highlightFullLine) { - break; // Since highlighting full line no need for multiple overlays, will cause darker highlight - } - } - }); - - // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) - // Filter them out by using the overlay rectangle as a hash key - const matchHash = Object.fromEntries( - newMatches.map((match) => [ - JSON.stringify(match.overlayRectangle), - match, - ]), - ); - const filteredMatches = Object.values(matchHash).map((match, index) => ({ - ...match, - index, - })); - + setMatches(results); // Find match closest to the middle of the view - const verticalMiddle = - searchRef.current.scrollTop + searchRef.current.clientHeight / 2; - let closestDist = Infinity; - let closestMatchToMiddle: SearchMatch | null = null; - filteredMatches.forEach((match) => { - const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); - if (dist < closestDist) { - closestDist = dist; - closestMatchToMiddle = match; - } - }); - - // Update matches and scroll to the closest or first match - setMatches(filteredMatches); - if (query.length > 1 && filteredMatches.length) { + if (searchTerm.length > 1 && results.length) { if (scrollTo === "first") { - scrollToMatch(filteredMatches[0]); + scrollToMatch(results[0]); } if (scrollTo === "closest") { - if (closestMatchToMiddle) { - scrollToMatch(closestMatchToMiddle); + if (closestToMiddle) { + scrollToMatch(closestToMiddle); } } if (scrollTo === "none") { - if (closestMatchToMiddle) { - setCurrentMatch(closestMatchToMiddle); + if (closestToMiddle) { + setCurrentMatch(closestToMiddle); } else { - setCurrentMatch(filteredMatches[0]); + setCurrentMatch(results[0]); } } } }, [ - headerRef, - searchRef, - debouncedInput, - scrollToMatch, + searchTerm, caseSensitive, useRegex, - ...refreshDependencies, + searchRef, + headerHeight, + scrollToMatch, ], ); // Triggers that should cause immediate refresh of results to closest search value: - // Input change (debounced) and window click - const lastUpdateRef = useRef(0); useEffect(() => { - const debounce = () => { - debouncedInput.current = input; - lastUpdateRef.current = Date.now(); - refreshSearch("closest"); - }; - const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; - if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { - debounce(); + if (disabled || isResizing || !open) { + setMatches([]); } else { - const handler = setTimeout(() => { - debounce(); - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); - return () => { - clearTimeout(handler); - }; + refreshSearch("closest"); } - }, [refreshSearch, input]); + }, [refreshSearch, open, disabled, isResizing, ...refreshDependencies]); - // Could consider doing any window click but I only handled search div here - // Since usually only clicks in search div will cause content changes in search div + // Clicks in search div can cause content changes that for some reason don't trigger resize + // Refresh clicking within container useEffect(() => { const searchContainer = searchRef.current; if (!open || !searchContainer) return; const handleSearchRefClick = () => { - refreshSearch("none"); + setTimeout(() => { + refreshSearch("none"); + }, 150); }; searchContainer.addEventListener("click", handleSearchRefClick); return () => { @@ -369,123 +210,89 @@ export const useFindWidget = ( }; }, [searchRef, refreshSearch, open]); - useEffect(() => { - if (disabled || isResizing) setMatches([]); - else setTimeout(() => refreshSearch("none"), 300); // this gives plenty of time for resizing to finish - }, [refreshSearch, disabled, isResizing]); - - useEffect(() => { - if (!open) setMatches([]); - else refreshSearch("closest"); - }, [refreshSearch, open]); - - useEffect(() => { - refreshSearch("closest"); - }, [refreshSearch, caseSensitive, useRegex]); - // Find widget component - const widget = useMemo(() => { - return ( -
- { - setInput(e.target.value); - }} - placeholder="Search..." - /> -

- {matches.length === 0 - ? "No results" - : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} -

-
- { - e.stopPropagation(); - previousMatch(); - }} - className="h-4 w-4 focus:ring" - disabled={matches.length < 2 || disabled} - > - - - { - e.stopPropagation(); - nextMatch(); - }} - className="h-4 w-4 focus:ring" - disabled={matches.length < 2 || disabled} - > - - -
+ const widget = ( +
+ +

+ {matches.length === 0 + ? "No results" + : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} +

+
{ e.stopPropagation(); - setCaseSensitive((curr) => !curr); + previousMatch(); }} - className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" + className="h-4 w-4 focus:ring" + disabled={matches.length < 2 || disabled} > - Aa + - {/* TODO - add useRegex functionality */} - setOpen(false)} - className="focus:ring" + { + e.stopPropagation(); + nextMatch(); + }} + className="h-4 w-4 focus:ring" + disabled={matches.length < 2 || disabled} > - - + +
- ); - }, [ - open, - input, - inputRef, - caseSensitive, - matches, - currentMatch, - previousMatch, - nextMatch, - ]); + { + e.stopPropagation(); + setCaseSensitive((curr) => !curr); + }} + className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" + > + Aa + + {/* TODO - add useRegex functionality */} + setOpen(false)} + className="focus:ring" + > + + +
+ ); // Generate the highlight overlay elements const highlights = useMemo(() => { return matches.map((match) => ( )); }, [matches, currentMatch]); return { - matches, highlights, - inputRef, - input: debouncedInput, - setInput, - open, - setOpen, widget, }; }; diff --git a/gui/src/components/find/findWidgetSearch.ts b/gui/src/components/find/findWidgetSearch.ts index f3c51cfb8..819d024eb 100644 --- a/gui/src/components/find/findWidgetSearch.ts +++ b/gui/src/components/find/findWidgetSearch.ts @@ -1,158 +1,145 @@ +export interface Rectangle { + top: number; + left: number; + width: number; + height: number; +} + export interface SearchMatch { index: number; textNode: Text; overlayRectangle: Rectangle; } +interface SearchOptions { + caseSensitive: boolean; + useRegex: boolean; + offsetHeight: number; +} -const refreshSearch = (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { - if (clearFirst) setMatches([]); +export const searchWithinContainer = ( + containerRef: React.RefObject, + searchQuery: string, + options: SearchOptions, +): { + results: SearchMatch[]; + closestToMiddle: SearchMatch | null; +} => { + const searchContainer = containerRef.current; - const searchContainer = searchRef.current; - const header = headerRef.current; + if (!searchContainer || !searchQuery) { + return { + results: [], + closestToMiddle: null, + }; + } + const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase(); - const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable - if (!searchContainer || !_query) { - setMatches([]); - return; - } - const query = caseSensitive ? _query : _query.toLowerCase(); - - // First grab all text nodes - // Skips any elements with the "find-widget-skip" class - const textNodes: Text[] = []; - const walker = document.createTreeWalker( - searchRef.current, - NodeFilter.SHOW_ALL, - { - acceptNode: (node) => { - if (node.nodeType === Node.ELEMENT_NODE) { - if ((node as Element).classList.contains("find-widget-skip")) - return NodeFilter.FILTER_REJECT; - return NodeFilter.FILTER_ACCEPT; - } else if (node.nodeType === Node.TEXT_NODE) { - if (!node.nodeValue) return NodeFilter.FILTER_REJECT; - const nodeValue = caseSensitive - ? node.nodeValue - : node.nodeValue.toLowerCase(); - if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; - } + // First grab all text nodes + // Skips any elements with the "find-widget-skip" class + const textNodes: Text[] = []; + const walker = document.createTreeWalker( + searchContainer, + NodeFilter.SHOW_ALL, + { + acceptNode: (node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + if ((node as Element).classList.contains("find-widget-skip")) return NodeFilter.FILTER_REJECT; - }, - }, - ); - - while (walker.nextNode()) { - if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; - textNodes.push(walker.currentNode as Text); - } - - // Now walk through each node match and extract search results - // One node can have several matches - const newMatches: SearchMatch[] = []; - textNodes.forEach((textNode, idx) => { - // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail - const highlightFullLine = - textNode.parentElement?.className.includes("hljs"); - - let nodeTextValue = caseSensitive - ? textNode.nodeValue - : textNode.nodeValue.toLowerCase(); - let startIndex = 0; - while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { - // Create a range to measure the size and position of the match - const range = document.createRange(); - range.setStart(textNode, startIndex); - const endIndex = startIndex + query.length; - range.setEnd(textNode, endIndex); - const rect = range.getBoundingClientRect(); - range.detach(); - startIndex = endIndex; - - const headerHeight = header?.clientHeight ?? 0; - - const top = - rect.top + - searchContainer.clientTop + - searchContainer.scrollTop - - headerHeight; - const left = - rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; - - // Build a match result and push to matches - const newMatch: SearchMatch = { - index: 0, // will set later - textNode, - overlayRectangle: { - top, - left: highlightFullLine ? 2 : left, - width: highlightFullLine - ? searchContainer.clientWidth - 4 - : rect.width, // equivalent of adding 2 px x padding - height: rect.height, - }, - }; - newMatches.push(newMatch); - - if (highlightFullLine) { - break; // Since highlighting full line no need for multiple overlays, will cause darker highlight - } + return NodeFilter.FILTER_ACCEPT; + } else if (node.nodeType === Node.TEXT_NODE) { + if (!node.nodeValue) return NodeFilter.FILTER_REJECT; + const nodeValue = options.caseSensitive + ? node.nodeValue + : node.nodeValue.toLowerCase(); + if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; } - }); - - // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) - // Filter them out by using the overlay rectangle as a hash key - const matchHash = Object.fromEntries( - newMatches.map((match) => [ - JSON.stringify(match.overlayRectangle), - match, - ]), - ); - const filteredMatches = Object.values(matchHash).map((match, index) => ({ - ...match, - index, - })); - - // Find match closest to the middle of the view - const verticalMiddle = - searchRef.current.scrollTop + searchRef.current.clientHeight / 2; - let closestDist = Infinity; - let closestMatchToMiddle: SearchMatch | null = null; - filteredMatches.forEach((match) => { - const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); - if (dist < closestDist) { - closestDist = dist; - closestMatchToMiddle = match; - } - }); - - // Update matches and scroll to the closest or first match - setMatches(filteredMatches); - if (query.length > 1 && filteredMatches.length) { - if (scrollTo === "first") { - scrollToMatch(filteredMatches[0]); - } - if (scrollTo === "closest") { - if (closestMatchToMiddle) { - scrollToMatch(closestMatchToMiddle); - } - } - if (scrollTo === "none") { - if (closestMatchToMiddle) { - setCurrentMatch(closestMatchToMiddle); - } else { - setCurrentMatch(filteredMatches[0]); - } - } - } + return NodeFilter.FILTER_REJECT; + }, }, - [ - headerRef, - searchRef, - debouncedInput, - scrollToMatch, - caseSensitive, - useRegex, - ...refreshDependencies, - ], -} \ No newline at end of file + ); + + while (walker.nextNode()) { + if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; + textNodes.push(walker.currentNode as Text); + } + + // Now walk through each node match and extract search results + // One node can have several matches + const newMatches: SearchMatch[] = []; + textNodes.forEach((textNode, idx) => { + // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail + const highlightFullLine = + textNode.parentElement?.className.includes("hljs"); + + let nodeTextValue = options.caseSensitive + ? textNode.nodeValue + : textNode.nodeValue.toLowerCase(); + let startIndex = 0; + while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { + // Create a range to measure the size and position of the match + const range = document.createRange(); + range.setStart(textNode, startIndex); + const endIndex = startIndex + query.length; + range.setEnd(textNode, endIndex); + const rect = range.getBoundingClientRect(); + range.detach(); + startIndex = endIndex; + + const top = + rect.top + searchContainer.clientTop + searchContainer.scrollTop; + // - + // options.offsetHeight; + + const left = + rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; + + // Build a match result and push to matches + const newMatch: SearchMatch = { + index: 0, // will set later + textNode, + overlayRectangle: { + top, + left: highlightFullLine ? 2 : left, + width: highlightFullLine + ? searchContainer.clientWidth - 4 + : rect.width, // equivalent of adding 2 px x padding + height: rect.height, + }, + }; + newMatches.push(newMatch); + + if (highlightFullLine) { + break; // Since highlighting full line no need for multiple overlays, will cause darker highlight + } + } + }); + + // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) + // Filter them out by using the overlay rectangle as a hash key + const matchHash = Object.fromEntries( + newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]), + ); + const filteredMatches = Object.values(matchHash).map((match, index) => ({ + ...match, + index, + })); + + // Find the match closest to the vertical middle of the container + const verticalMiddle = + searchContainer.scrollTop + searchContainer.clientHeight / 2; + let closestDist = Infinity; + let closestMatchToMiddle: SearchMatch | null = null; + filteredMatches.forEach((match) => { + const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); + if (dist < closestDist) { + closestDist = dist; + closestMatchToMiddle = match; + } + }); + + return { + results: filteredMatches, + closestToMiddle: closestMatchToMiddle, + }; +}; diff --git a/gui/src/components/find/useDebouncedInput.ts b/gui/src/components/find/useDebouncedInput.ts new file mode 100644 index 000000000..e00cd8721 --- /dev/null +++ b/gui/src/components/find/useDebouncedInput.ts @@ -0,0 +1,48 @@ +import { debounce } from "lodash"; +import { useEffect, useRef, useState } from "react"; + +interface UseDebouncedInputResult { + inputRef: React.RefObject; + debouncedValue: string; + currentValue: string; +} + +export const useDebouncedInput = ( + debounceDelay: number = 300, +): UseDebouncedInputResult => { + const [debouncedValue, setDebouncedValue] = useState(""); + const [currentValue, setCurrentValue] = useState(""); + const inputRef = useRef(null); + + const debouncedSetValue = useRef( + debounce((value: string) => { + setDebouncedValue(value); + }, debounceDelay), + ).current; + + useEffect(() => { + debouncedSetValue(currentValue); + // Initial value is set immediately + if (currentValue === "") { + setDebouncedValue(""); + } + + return () => { + debouncedSetValue.cancel(); + }; + }, [currentValue, debouncedSetValue]); + + useEffect(() => { + const input = inputRef.current; + if (!input) return; + + const handleChange = (event: Event) => { + setCurrentValue((event.target as HTMLInputElement).value); + }; + + input.addEventListener("input", handleChange); + return () => input.removeEventListener("input", handleChange); + }, []); + + return { inputRef, debouncedValue, currentValue }; +}; diff --git a/gui/src/components/find/useElementDims.ts b/gui/src/components/find/useElementDims.ts new file mode 100644 index 000000000..ba4398d98 --- /dev/null +++ b/gui/src/components/find/useElementDims.ts @@ -0,0 +1,42 @@ +import { debounce } from "lodash"; +import { useEffect, useState } from "react"; + +export function useElementSize( + ref: React.RefObject, + resizeDebounce = 200, +) { + const [size, setSize] = useState({ + height: 0, + width: 0, + }); + const [isResizing, setIsResizing] = useState(false); + + useEffect(() => { + if (!ref.current) return; + + const element = ref.current; + const debouncedSetSize = debounce((entries: ResizeObserverEntry[]) => { + if (!entries.length) return; + + setIsResizing(false); + setSize({ + height: entries[0].contentRect.height, + width: entries[0].contentRect.width, + }); + }, resizeDebounce); + + const resizeObserver = new ResizeObserver((entries) => { + setIsResizing(true); + debouncedSetSize(entries); + }); + resizeObserver.observe(element); + + return () => { + debouncedSetSize.cancel(); + resizeObserver.unobserve(element); + resizeObserver.disconnect(); + }; + }, [ref, resizeDebounce]); + + return { ref, size, isResizing }; +} From b55079e2d7c288d91f6ad0345b3152ce86b16516 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 23 May 2025 16:58:40 -0700 Subject: [PATCH 38/38] works with tab resize now --- gui/src/components/TabBar/TabBar.tsx | 13 +++- gui/src/components/find/FindWidget.tsx | 39 ++++++---- gui/src/components/find/findWidgetSearch.ts | 7 +- gui/src/components/find/useDebounce.ts | 19 +++++ gui/src/components/find/useDebouncedInput.ts | 48 ------------ gui/src/components/find/useElementDims.ts | 42 ---------- gui/src/components/find/useElementSize.ts | 81 ++++++++++++++++++++ gui/src/pages/gui/Chat.tsx | 1 - 8 files changed, 135 insertions(+), 115 deletions(-) create mode 100644 gui/src/components/find/useDebounce.ts delete mode 100644 gui/src/components/find/useDebouncedInput.ts delete mode 100644 gui/src/components/find/useElementDims.ts create mode 100644 gui/src/components/find/useElementSize.ts diff --git a/gui/src/components/TabBar/TabBar.tsx b/gui/src/components/TabBar/TabBar.tsx index d7fa4d588..7f881edd5 100644 --- a/gui/src/components/TabBar/TabBar.tsx +++ b/gui/src/components/TabBar/TabBar.tsx @@ -35,6 +35,8 @@ const TabBarContainer = styled.div` border-bottom: none; position: relative; margin-top: 2px; + max-height: 100px; + overflow: auto; /* Hide scrollbar but keep functionality */ scrollbar-width: none; @@ -223,10 +225,13 @@ export const TabBar = React.forwardRef((_, ref) => { } }; - return tabs.length === 1 ? ( - <> - ) : ( - + return ( + {tabs.map((tab) => ( , headerRef: RefObject, - refreshDependencies: React.DependencyList, disabled: boolean, ) => { // Search input, debounced - const { - inputRef, - debouncedValue: searchTerm, - currentValue, - } = useDebouncedInput(); + const inputRef = useRef(null); + const [currentValue, setCurrentValue] = useState(""); + const searchTerm = useDebounceValue(currentValue, 300); // Widget open/closed state const [open, setOpen] = useState(false); @@ -134,14 +138,12 @@ export const useFindWidget = ( }, [inputRef, matches, nextMatch]); // Handle container resize changes - highlight positions must adjust - const headerSize = useElementSize(headerRef); - const containerSize = useElementSize(searchRef); + const { clientHeight: headerHeight, isResizing: headerResizing } = + useElementSize(headerRef); + const { isResizing: containerResizing } = useElementSize(searchRef); const isResizing = useMemo(() => { - return containerSize.isResizing || headerSize.isResizing; - }, [containerSize, headerSize]); - const headerHeight = useMemo(() => { - return headerSize.size.height; - }, [headerSize]); + return containerResizing || headerResizing; + }, [containerResizing, headerResizing]); // Main function for finding matches and generating highlight overlays const refreshSearch = useCallback( @@ -192,7 +194,7 @@ export const useFindWidget = ( } else { refreshSearch("closest"); } - }, [refreshSearch, open, disabled, isResizing, ...refreshDependencies]); + }, [refreshSearch, open, disabled, isResizing]); // Clicks in search div can cause content changes that for some reason don't trigger resize // Refresh clicking within container @@ -220,6 +222,9 @@ export const useFindWidget = ( type="text" ref={inputRef} value={currentValue} + onChange={(e) => { + setCurrentValue(e.target.value); + }} placeholder="Search..." />

diff --git a/gui/src/components/find/findWidgetSearch.ts b/gui/src/components/find/findWidgetSearch.ts index 819d024eb..8b03d77af 100644 --- a/gui/src/components/find/findWidgetSearch.ts +++ b/gui/src/components/find/findWidgetSearch.ts @@ -87,9 +87,10 @@ export const searchWithinContainer = ( startIndex = endIndex; const top = - rect.top + searchContainer.clientTop + searchContainer.scrollTop; - // - - // options.offsetHeight; + rect.top + + searchContainer.clientTop + + searchContainer.scrollTop - + options.offsetHeight; const left = rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; diff --git a/gui/src/components/find/useDebounce.ts b/gui/src/components/find/useDebounce.ts new file mode 100644 index 000000000..8a9898429 --- /dev/null +++ b/gui/src/components/find/useDebounce.ts @@ -0,0 +1,19 @@ +import { useEffect, useState } from "react"; + +function useDebounceValue(value: T, delay: number = 500): T { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timer = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(timer); + }; + }, [value, delay]); + + return debouncedValue; +} + +export default useDebounceValue; diff --git a/gui/src/components/find/useDebouncedInput.ts b/gui/src/components/find/useDebouncedInput.ts deleted file mode 100644 index e00cd8721..000000000 --- a/gui/src/components/find/useDebouncedInput.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { debounce } from "lodash"; -import { useEffect, useRef, useState } from "react"; - -interface UseDebouncedInputResult { - inputRef: React.RefObject; - debouncedValue: string; - currentValue: string; -} - -export const useDebouncedInput = ( - debounceDelay: number = 300, -): UseDebouncedInputResult => { - const [debouncedValue, setDebouncedValue] = useState(""); - const [currentValue, setCurrentValue] = useState(""); - const inputRef = useRef(null); - - const debouncedSetValue = useRef( - debounce((value: string) => { - setDebouncedValue(value); - }, debounceDelay), - ).current; - - useEffect(() => { - debouncedSetValue(currentValue); - // Initial value is set immediately - if (currentValue === "") { - setDebouncedValue(""); - } - - return () => { - debouncedSetValue.cancel(); - }; - }, [currentValue, debouncedSetValue]); - - useEffect(() => { - const input = inputRef.current; - if (!input) return; - - const handleChange = (event: Event) => { - setCurrentValue((event.target as HTMLInputElement).value); - }; - - input.addEventListener("input", handleChange); - return () => input.removeEventListener("input", handleChange); - }, []); - - return { inputRef, debouncedValue, currentValue }; -}; diff --git a/gui/src/components/find/useElementDims.ts b/gui/src/components/find/useElementDims.ts deleted file mode 100644 index ba4398d98..000000000 --- a/gui/src/components/find/useElementDims.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { debounce } from "lodash"; -import { useEffect, useState } from "react"; - -export function useElementSize( - ref: React.RefObject, - resizeDebounce = 200, -) { - const [size, setSize] = useState({ - height: 0, - width: 0, - }); - const [isResizing, setIsResizing] = useState(false); - - useEffect(() => { - if (!ref.current) return; - - const element = ref.current; - const debouncedSetSize = debounce((entries: ResizeObserverEntry[]) => { - if (!entries.length) return; - - setIsResizing(false); - setSize({ - height: entries[0].contentRect.height, - width: entries[0].contentRect.width, - }); - }, resizeDebounce); - - const resizeObserver = new ResizeObserver((entries) => { - setIsResizing(true); - debouncedSetSize(entries); - }); - resizeObserver.observe(element); - - return () => { - debouncedSetSize.cancel(); - resizeObserver.unobserve(element); - resizeObserver.disconnect(); - }; - }, [ref, resizeDebounce]); - - return { ref, size, isResizing }; -} diff --git a/gui/src/components/find/useElementSize.ts b/gui/src/components/find/useElementSize.ts new file mode 100644 index 000000000..fc4b307a2 --- /dev/null +++ b/gui/src/components/find/useElementSize.ts @@ -0,0 +1,81 @@ +import { RefObject, useCallback, useEffect, useState } from "react"; + +interface ElementSize { + clientWidth: number; + clientHeight: number; + scrollWidth: number; + scrollHeight: number; + isResizing: boolean; +} + +interface UseElementSizeOptions { + debounceMs?: number; +} + +export const useElementSize = ( + ref: RefObject, + debounceMs = 250, +): ElementSize => { + const [size, setSize] = useState({ + clientWidth: 0, + clientHeight: 0, + scrollWidth: 0, + scrollHeight: 0, + isResizing: false, + }); + + // Debounced update function + const debouncedSetSize = useCallback( + (measurements: Omit) => { + let timeoutId: NodeJS.Timeout; + + setSize((prev) => ({ ...prev, isResizing: true })); + + timeoutId = setTimeout(() => { + setSize({ + ...measurements, + isResizing: false, + }); + }, debounceMs); + + return () => clearTimeout(timeoutId); + }, + [debounceMs], + ); + + useEffect(() => { + if (!ref.current) return; + + const updateSize = () => { + const element = ref.current; + if (!element) return; + + const measurements = { + clientWidth: element.clientWidth, + clientHeight: element.clientHeight, + scrollWidth: element.scrollWidth, + scrollHeight: element.scrollHeight, + }; + + debouncedSetSize(measurements); + }; + + // Create ResizeObserver instance + const resizeObserver = new ResizeObserver(() => { + updateSize(); + }); + + // Start observing the element + resizeObserver.observe(ref.current); + + // Initial size calculation + updateSize(); + + // Cleanup + return () => { + resizeObserver.disconnect(); + }; + }, [ref, debouncedSetSize]); + + return size; +}; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6297643fd..7b3c383f3 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -156,7 +156,6 @@ export function Chat() { const { widget, highlights } = useFindWidget( stepsDivRef, tabsRef, - [history], isStreaming, );